初識 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

相關文章
相關標籤/搜索