Bottle是一個輕量級的Web框架,此框架只由一個 bottle.py 文件構成,不依賴任何第三方模塊。
#!/usr/bin/env python # -*- coding:utf-8 -*- from bottle import template, Bottle app = Bottle() @app.route('/say') def index(): return "Hello World" # return template('Hello {{name}}!', name="bottle") if __name__ == '__main__': app.run(server="tornado",host='0.0.0.0', port=8888)
1、路由系統
路由系統是的url對應指定函數,當用戶請求某個url時,就由指定函數處理當前請求,對於Bottle的路由系統可以分為一下幾類:
靜態路由
動態路由
請求方法路由
二級路由
1.1靜態路由
@app.route("/login") # 默認為get請求 def hello(): return """Username:Password:""" @app.route("/login",method="POST") def do_login(): username = request.forms.get("username") password = request.forms.get("password") print(username,password) if username and password: return "login success" else: return "login failure"
1.2動態路由
@app.route('/say/') def callback(name): return template('Hello {{name}}!') @app.route('/say/') def callback(id): return template('Hello {{id}}!') @app.route('/say/') def callback(name): return template('Hello {{name}}!') @app.route('/static/') def callback(path): return static_file(path, root='static')
1.3請求方法路由
@app.route('/hello/', method='POST') # 等同於@app.post('/hello/') def index(): ... @app.get('/hello/') # 等同於@app.route('/hello/',method='GET') def index(): ... @app.post('/hello/') # 等同於@app.route('/hello/',method='POST') def index(): ... @app.put('/hello/') # 等同於@app.route('/hello/',method='PUT') def index(): ... @app.delete('/hello/') def index(): ...
1.4二級路由
#!/usr/bin/env python # -*- coding:utf-8 -*- from bottle import template, Bottle app01 = Bottle() @app01.route('/hello/', method='GET') def index(): return template('App01!') app01.py
#!/usr/bin/env python # -*- coding:utf-8 -*- from bottle import template, Bottle app02 = Bottle() @app02.route('/hello/', method='GET') def index(): return template('App02!') app02.py
#!/usr/bin/env python # -*- coding:utf-8 -*- from bottle import template, Bottle from bottle import static_file app = Bottle() @app.route('/hello/') def index(): return template('Root {{name}}!', name="bottle") from root_dir import app01 from root_dir import app02 app.mount('app01', app01.app01) app.mount('app02', app02.app02) app.run(host='localhost', port=8888)
1.5靜態文件映射,static_file()函數用於響應靜態文件的請求
# 靜態文件映射,static_file()函數用於響應靜態文件 的請求 @app.route("/static/") def send_image(filename): return static_file(filename, root=os.getcwd(), mimetype="image/jpg") @app.route("/static/") # 可匹配路徑 def send_image(filename): return static_file(filename, root=os.getcwd(), mimetype="image/jpg") # 強制下載 @app.route("/static/") # 可匹配路徑 def download(filename): return static_file(filename, root=os.getcwd(), download=filename)
1.6使用error()函數自定義錯誤頁面
@app.error(404)
def error404(error):
return "我找不到目標了,我發生錯誤了"
1.7HTTP錯誤和重定向
abort()函數是生成HTTP錯誤的頁面的一個捷徑
@app.route("/restricted") def restricted() abort(401,"Sorry, access denied") # 將url重定向到其他url,可以在location中設置新的url,接著返回一個303 # redirect()函數可以幫助我們做這件事 @app.route("/wrong/url") def wrong() redirect("/right/url")
其他異常
除了HTTPResponse或者HTTPError以外的其他異常,都會導致500錯誤,因此不會造成WSGI服務器崩潰
將bottle.app().catchall的值設為False來關閉這種行為,以便在中間件中處理異常
2.cookies
@app.route("/login", method="POST") def do_login(): username = request.forms.get("username") password = request.forms.get("password") print(username, password) if username and password: response.set_cookie("name",username, secret= 'some-secret-key') # 設置cookie return "login success" else: return "login failure" @app.route("/static/") def send_image(filename): username = request.get_cookie("name", secret= 'some-secret-key') # 獲取cookie if username: return static_file(filename, root=os.getcwd(), mimetype="image/jpg") else: return "verify failed"
bottle就的 set_cookie 的默認 path 是當前路徑,也就是說,在這個頁面上存入的 cookie 在別的頁面通常是取不到的,不熟悉這點的人幾乎都要栽在這裡。而且更坑的是:set_cookie 有 path 參數可以指定 path ,但 get_cookie 卻沒有這個 path 參數可選――也就是說,你即使設置了其它 path ,如果 get_cookie 的時候不是剛好在那個 path 下的話,也取不到……
解決方法:把所有的 cookie 都放到"/"下面,至少目前用下來感覺沒問題。
注:request.query 或 request.forms 都是一個 FormDict 類型,
其特點是:當以屬性方式訪問數據時――如 request.query.name,返回的結果是 unicode ,當以字典試訪問數據時,如 :request.query['name']或者request.query.get("name"),則返回的結果是原編碼字符串
[retouched ] Python輕量級web框架bottle使用方法解析已經有307次圍觀