프로그래밍/Python

초경량 Python 웹서버 bottle을 이용한 MVC 예제 + Cookie

Terry Cho 2013. 5. 3. 23:34


초경량 Python 웹서버 bottle

MVC 예제


Controller 파일 구현 

/controller.py

import bottle

 

mythings = ['apple','orange','banana','peach']

 

@bottle.route('/')

def home_page():

    fruit = bottle.request.get_cookie("fruit")

    return bottle.template("hello_world",username="Andrew",things=mythings,like=fruit)

               

@bottle.post('/favorite_fruits')

def favorite_fruits():

    fruit = bottle.request.forms.get('fruit')

    if(fruit == None or fruit==""):

        fruit="No Fruit Selected"

    bottle.response.set_cookie('fruit',fruit)

    return bottle.template("fruit.tpl",{'fruit':fruit})

 

bottle.debug(True)

bottle.run(host='localhost',port=8080)


 

TBL 파일들은 템플릿으로, Python 변수는 {{ }}로 표현 (cf. jsp에서 <%=xx %>)

파이썬 로직은 %로 표현 (cf. jsp에서 <% %>)


/hello_world.tpl

<html>

<body>

Welcome {{username}}<br/>

You like <b>{{like}}</b>

<p>

<ul>

%for thing in things:

<li>{{thing}}</li>

%end

</ul>

<form action="/favorite_fruits" method=POST>

    What fruit do you like ?

    <input type="text" name="fruit" size=20 value="">

    <input type="submit" value="submit">

</form>

</body>

</html>


/fruit.tpl

<body>

Your like {{fruit}}

</body> 


실행 예




 

그리드형