HTTP 請求方法
HTTP 協議有很多種請求方法。route默認使用GET方法,只響應GET請求。method參數可以給route()函數指定使用哪種方法。或用get(),post(),put()或delete()等函數來代替route()函數。
POST 方法一般用於HTML 表單的提交。下面是一個使用POST 來實現用戶登錄的例子:
[root@jubottle]# cat login.py #!/usr/bin/envpython #coding=utf-8 from bottle import run,get,post,request @get('/login') #或者@route('/login'),默認是GET方法 def login_form(): return ''' <form method="POST"action="/login"> 用戶名:<input name="username" type="text"/><br> 密碼: <inputname="password" type="password" /><br> <input value="登錄" type="submit"/> </form>''' @post('/login') #或者@route('/login',method='POST'),POST方法要指定 def login_submit(): name = request.forms.get('username') passwd = request.forms.get('password') return "<p>用戶名:%s</p><p>密碼:%s</p>" %(name,passwd) run(host='0.0.0.0',port=8000,debug=True) #開啓服務,打開debug模式
打開瀏覽器訪問:http://192.168.116.199:8000/login
在username處輸入:ju
在password處輸入:123
點登錄後網頁顯示:
在上例中使用POST方法時,使用request.forms方法獲取相關的值,當從GET方法傳遞鍵值時,用 request.query方法來獲取,例如:
[root@jubottle]# cat get_test.py #!/usr/bin/envpython from bottle import run,get,request @get('/vars') def vars(): var1 = request.query.username var2 = request.query.password return "username=%s,password=%s"% (var1,var2) run(host='0.0.0.0',port=8000,debug=True)
打開瀏覽器訪問:http://192.168.116.199:8000/vars?username=ju&password=123
特殊請求方法: HEAD 和 ANY
HEAD 方法類似於 GET 方法,但服務器不會返回 HTTP 響應正文,一般用於獲取 HTTP 原數據而不用下載整個頁面。
非標準的ANY方法做爲一個低優先級的fallback:在沒有其它route的時候,監聽ANY方法的route會匹配所有請求,而不管請求的方法是什麼。這對於用做代理的route很有用,可將所有請求都重定向給子應用。
總之:HEAD 請求被響應GET請求的route來處理,響應 ANY 請求的 route 處理所有請求,但僅限於沒有其它 route 來匹配原先的請求的情況。
靜態文件映射
Bottle 不會處理像圖片或CSS 文件的靜態文件請求。你需要給靜態文件提供一個route,一個回調函數(用於查找和控制靜態文件的訪問)。
[root@jubottle]# cat static_test.py #!/usr/bin/envpython from bottle import static_file, route, run @route('/static/<filename:path>') def server_static(filename): return static_file(filename,root='/home/bottle/static') run(host='0.0.0.0',port=8000)
打開瀏覽器訪問:http://192.168.116.199:8000/static/lufei.jpg
錯誤頁面
如果頁面出錯,Bottle 會顯示一個默認的錯誤頁面,提供足夠的debug 信息。你也可以使用error()函數來自定義你的錯誤頁面:
from bottle import static_file,route,run,error @error(404) def error_page(error): return '沒有你還要訪問的頁面!' run(host='0.0.0.0',port=8000)
打開瀏覽器訪問一個不存在的頁面:http://192.168.116.199:8000/test