在初识Bottle(一)中,我们了解了Bottle的基本用法
在Bottle源码阅读(一)和Bottle源码阅读(二)可以查看个人对bottle源码的相关阅读笔记
下面继续阅读Bottle的官方文档https://bottlepy.org/docs/dev...
1.路由静态文件
在bottle中例如css等的文件是不会被自动加载的,因此需要自己定义callback函数,通过调用使用
from bottle import static_file
@route('/static/')
def server_static(filename):
return static_file(filename, root='/path/to/your/static/files')
2.错误页
通过error装饰器可以对相应的错误码自定义对应的应用函数
from bottle import error
@error(404)
def error404(error):
return 'Nothing here, sorry'
3.内容返回
Bottl框架允许应用函数返回如下类型的结果
Dictionaries字典:
python的字典通过框架被转换为json字符串,而header中的Content-Type则会被设置为application/json
Empty Strings, False, None or other non-true values:
header中的Content-Length被设置为0
Unicode strings
Byte strings
Instances of HTTPError or HTTPResponse
File objects
Iterables and generators
4.改变默认编码
通过在应用函数中改变response的属性可以自定义
from bottle import response
@route('/iso')
def get_iso():
response.charset = 'ISO-8859-15'
return u'This will be sent with ISO-8859-15 encoding.'
@route('/latin9')
def get_latin():
response.content_type = 'text/html; charset=latin9'
return u'ISO-8859-15 is also known as latin9.'
5.静态文件的使用
通过static_file接口,我们可以实现调用和下载
from bottle import static_file
@route('/images/')
def send_image(filename):
return static_file(filename, root='/path/to/image/files', mimetype='image/png')
@route('/static/')
def send_static(filename):
return static_file(filename, root='/path/to/static/files')
@route('/download/')
def download(filename):
return static_file(filename, root='/path/to/static/files', download=filename)
6.HTTP ERRORS AND REDIRECTS
通过abort可以快速定义错误码相应的错误页内容
redirect实现重定向
from bottle import route, abort
@route('/restricted')
def restricted():
abort(401, "Sorry, access denied.")
from bottle import redirect
@route('/wrong/url')
def wrong():
redirect("/right/url")
7.RESPONSE
response对象包括了响应的metadata例如状态码,headers,cookie等
response的状态码控制浏览器的行为,默认200ok
response的header可以通过set_header()来设置,对同一个header项,还可以通过add_header添加额外内容
cookie是保留在用户浏览器的一些数据,可以通过get_cookie和set_cookie来操作
@route('/hello')
def hello_again():
if request.get_cookie("visited"):
return "Welcome back! Nice to see you again"
else:
response.set_cookie("visited", "yes")
return "Hello there! Nice to meet you"
cookie是容易被伪造的,所以Bottle框架提供了cookie的签名机制,只需要提供一个secret的参数作为密钥
Bottle会自动持久化和去持久化保存在cookie中的数据,cookie不超过4k。
此时cookie仍然能从浏览器中查看到,而且是可以被复制的,所以最好不要将密钥的信息放在用户客户端
@route('/login')
def do_login():
username = request.forms.get('username')
password = request.forms.get('password')
if check_login(username, password):
response.set_cookie("account", username, secret='some-secret-key')
return template("Welcome {{name}}! You are now logged in.
", name=username)
else:
return "Login failed.
"
@route('/restricted')
def restricted_area():
username = request.get_cookie("account", secret='some-secret-key')
if username:
return template("Hello {{name}}. Welcome back.", name=username)
else:
return "You are not logged in. Access denied."
8.REQUEST
request 对象包括了Cookies, HTTP header, HTML