初识 Bottle (一)

1. 安装


bottle是一个轻量型的不依赖于任何第三方库的web框架,整个框架只有bottle.py一个文件。

wget http://bottlepy.org/bottle.py

2. 向bottle 打声招呼吧

新建一个文件hello.py

# coding:utf-8
from bottle import route, run

@route('/hello')
def hello():
    return "hello world"

run(host="localhost", port=8080, debug=True)

在浏览器或者postman, GET 127.0.0.1:8080/hello, 得到结果

当使用route装饰器绑定路由时,实际是使用了Bottle的默认应用,即是Bottle的一个实例。为了方便后续使用默认应用时采用route函数表示

from bottle import Bottle, run

app = Bottle()

@app.route('/hello')
def hello():
    return "Hello World!"

run(app, host='localhost', port=8080)

3. 路由

route() 函数连接url和响应函数,同时可以给默认应用添加新的路由

@route('/')
@route('/hello/<name>')
def greet(name='Stranger'):
    return template('Hello {{name}}, how are you?', name=name)

run(host="localhost", port=8080, debug=True)

试一下
GET 127.0.0.1:8080/hello/hh
GET 127.0.0.1:8080/
将url中的关键字作为参数传入给响应函数获取响应结果

对于url中的关键字,可以进行属性的限制筛选匹配

@route('/object/<id:int>')
def callback(id):
    if isinstance(id, int):
        return "T"

GET 127.0.0.1:8080/object/1
GET 127.0.0.1:8080/object/ss
后者将会出现404
同样,可以使用float,path,re正则表达式去filter参数,还可以自定义filter 条件,留意后续章节

4. http 请求方法

默认的route 将默认使用GET方法, 而POST等其他方法可以通过在route装饰器添加method参数或者直接使用get(), post(), put(), delete() or patch()等装饰器

from bottle import get, post, request, run

@get('/login') # or @route('/login')
def login():
    return '''
        <form action="/login" method="post">
            Username: <input name="username" type="text" />
            Password: <input name="password" type="password" />
            <input value="Login" type="submit" />
        </form>
    '''

@post('/login') # or @route('/login', method='POST')
def do_login():
    username = request.forms.get('username', None)
    password = request.forms.get('password', None)
    if username and password:
        return "<p>Your login information was correct.</p>"
    else:
        return "<p>Login failed.</p>"


run(host="localhost", port=8080, debug=True)

request.forms 会在request data 进一步细说

    原文作者:whales
    原文地址: https://segmentfault.com/a/1190000008245385
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞