phoenix13

导航

 

1. hello world. URL hander

import bottle

@bottle.route('/')
def home_page():
    return "hello world\n"

@bottle.route('/testpage')
def test_page():
    return "this is a test page"

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

 2. template

py file

import bottle

@bottle.route('/')
def home_page():
    mythings=['apple','banana','peach']
    #option 1
    return bottle.template('hello_world',username='Steve',things=mythings)
    #option 2 use dic
    #return bottle.template('hello_world',{'username':'Steve2','things':mythings})

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

template file(mix of html and python): hello_world.tpl

put it in subfold /views

<!DOCTYPE html>
<html>
<head>
    <title>Hello World</title>
</head>
<body>
    <p>welcome {{username}}
    <p><ul>
        %for thing in things:
        <li>{{thing}}</li>
        %end
    </ul>

</body>
</html>

 3. POST

py file

import bottle

@bottle.route('/')
def home_page():
    mythings=['apple','banana','peach']
    return bottle.template('hello_world2',username='Steve3',things=mythings)


@bottle.post('/fav_fruit')
def fav_fruit():
    fruit=bottle.request.forms.get('fruit')
    if (fruit==None or fruit==''):
        fruit ='no Fruit'
    return     bottle.template('fruit_select',{'fruit':fruit})

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

template html

<!DOCTYPE html>
<html>
<head>
    <title>Hello world</title>
</head>
<body>
    <p>
        welcome {{username}}
        <p><ul>
            %for thing in things:
            <li>{{thing}}</li>
            %end
        </ul>
        <p>
            <form action="/fav_fruit" method="POST">
                what is your favourite fruit?
                <input type="text" name="fruit" size="40" value=""><br>
                    <input type="submit" value="Submit">
            </form>
    </body>
</html>

 3. cookies, redirect

import bottle

@bottle.route('/')
def home_page():
    mythings=['apple','banana','peach']
    return bottle.template('hello_world2',username='Steve3',things=mythings)


@bottle.post('/fav_fruit')
def fav_fruit():
    fruit=bottle.request.forms.get('fruit')
    if (fruit==None or fruit==''):
        fruit ='no Fruit'
    bottle.response.set_cookie("fruit",fruit)
    bottle.redirect("/show_fruit")


@bottle.route('/show_fruit')
def show_fruit():
    fruit = bottle.request.get_cookie("fruit")
    return bottle.template('fruit_select',{"fruit":fruit})

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

 

posted on 2014-09-18 09:35  phoenix13  阅读(299)  评论(0编辑  收藏  举报