Sanic框架
第一个小例子
1.通过pip 安装 sanic
pip intsall sanic
2.代码实例
from sanic import Sanic
from sanic.response import json
app = Sanic()
@app.route('/')
async def test(request):
msg = {'message': 'Welcom to 猿人学Python'}
return json(msg, ensure_ascii=False)
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8888)
3.Sanic详解
1)首先导包,创建app(web应用)。根据app的响应数据类型从scnic.response导入相应的响应函数json()
2)app实例有两个常用的方法
- app.route()
这是一个装饰器,通过它定义app的路由,这里的小例子的访问路径就是根路径“/” - app.run()
由名知意运行app的函数
Sanic request
request对象的属性
- json:
当客户端POST来的数据是json时,可以用request.json来获取 :
from sanic import Sanic
from sanic.response import json
from sanic import response
app = Sanic()
@app.route('/args', methods=['POST'])
async def post_json(request):
print(request.body)
return response.json({"query_sting": request.form})
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8080)
2.args:
查询字符串就是URL中?后面的部分
@app.route('/args', methods=['POST'])
async def post_json(request):
print(request.args)
return response.json({"query_sting": request.query_string})
3.form:
POST方式传递的表单
4.body,host,url…:
都是字符串跟其他web框架大致一样都可以获取到
- get
get获取list的第一个值 - getlist
获取整个list
from sanic.request import RequestParameters
args = RequestParameters()
args['titles'] = [ '1', ' 2']
args.get('titles') # => '1'
args.getlist('titles') # => ['1', '2']
HTTP响应
reponse
- text
- body:响应要返回的文本字符串;
- status:默认 http 状态码200,正常返回不要修改;
- headers:自定义 http 响应头;
- content_type:纯文本的content type,不要修改;
from sanic import Sanic
from sanic.response import json
from sanic import response
app = Sanic()
@app.route('/')
async def post_json(request):
return response.text('Hello',status=202,headers={'Ahua':'shuai'})
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8080)
2.html
- body:响应要返回的html文本字符串;
- status:默认 http 状态码200,正常返回不要修改;
- headers:自定义 http 响应头;
3.json
- body:响应要返回的JSON数据,通常是一个字典;
- status:默认 http 状态码200,正常返回不要修改;
- headers:自定义 http 响应头;
- content_type:纯文本的content type,不要修改;
- dumps:把json数据(字典)dumps为字符串的函数;
- kwargs:dumps函数的参数;
4.file
- location:响应要返回的文件的路径;
- status:默认 http 状态码200,正常返回不要修改;
- mime_type:文件格式;
- headers:自定义 http 响应头;
- filename:如果传值则写入响应头headers的Content-Disposition;
- _range:指定文件的某一部分;
- io操作记得加await
from sanic import Sanic
from sanic.response import json
from sanic import response
app = Sanic()
@app.route('/')
async def post_json(request):
return await response.file('./img.txt',status=202,headers={'Ahua':'shuai','Content-Type': 'application/javascript'})
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8080)
5.raw
- body:响应要返回的bytes字符串,不是str;
- status:默认 http 状态码200,正常返回不要修改;
- headers:自定义 http 响应头;
- content_type:纯文本的content type,不要修改;
6.redirect - to:响应要返回的重定向URL字符串;
- status:默认 http 状态码302,正常返回不要修改;
- headers:自定义 http 响应头;
- content_type:HTTP 响应头的 content type,不要修改;