对于WSGI来说,python中的数据类型不能直接在业务函数中返回给客户端,bottle给予了某些类型和编码的转换支持。
WSGI, Web Server Gateway Interface
如全称代表的那样,WSGI不是服务器,不是API,不是Python模块,更不是什么框架,而是一种服务器和客户端交互的接口规范!更具体的规范说明请搜索“PEP 3333”。在WSGI规范下,web组件被分成三类:client, server, and middleware.WSGI apps(服从该规范的应用)能够被连接起来(be stacked)处理一个request,这也就引发了中间件这个概念,中间件同时实现c端和s端的接口,c看它是上游s,s看它是下游的c。WSGI的s端所做的工作仅仅是接收请求,传给application(做处理),然后将结果response给middleware或client.除此以外的工作都交给中间件或者application来做。
链接:https://www.zhihu.com/question/19998865/answer/26203965
来源:知乎
字典
转换为JSON格式的数据
Content-Type设置为application/json
from bottle import route,run
@route('/')
def index():
return {'a':'sunchengquan','b':8888,'c':8.888}
run(host='localhost',port=80,debug=True,reloader=True)
空值
None,False,”“,[],()
返回为空
Content-Length 设置为0
from bottle import route,run
@route('/')
def index():
return ()
run(host='localhost',port=80,debug=True,reloader=True)
字符串
依据Content-Type对其进行编码后返回
在业务函数中可以直接返回字符串,给浏览器返回内容
字节串
bytes
字符串经过编码形成的数据类型
from bottle import route,run
@route('/')
def index():
htmlstr = 'asdfghjkl'
return htmlstr.encode('utf-8')
run(host='localhost',port=80,debug=True,reloader=True)
虽然业务函数将字符串编码形成字节串,但是bottle框架依然能够正确解码成字符串,返回正确的结果。
列表与元组
在业务函数中返回列表与元组时,bottle这个框架会将列表与元组中的元素用join进行合并,因此列表与元组中的元素应为字符串或字节串(不能混有字符串,字节串),并且不能返回嵌套的列表和元组
from bottle import route,run
@route('/')
def index():
return ['sun','cheng','quan']
run(host='localhost',port=80,debug=True,reloader=True)
修改为元组,返回也是相同的结果
但如果元组中嵌套有列表,就会出错
from bottle import route,run
@route('/')
def index():
return ('sun','cheng','quan',['a','b'])
run(host='localhost',port=80,debug=True,reloader=True)
业务函数中指定返回字符编码
Response.charset=’utf-8’
Response.content_type=’text/html;charset=gbk’
from bottle import route,run,Response
@route('/')
def index():
# Response.charset='gbk'
Response.content_type='text/html;charset=gbk'
return 'bottle 是一个微框架'
run(host='localhost',port=80,debug=True,reloader=True)