初识 Bottle (一)

1. 安装

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

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

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函数表示app

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中的关键字,能够进行属性的限制筛选匹配post

@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 条件,留意后续章节url

4. http 请求方法

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

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 进一步细说code

相关文章
相关标签/搜索