python sanic加速_python 最快 web 框架 Sanic 快速入门

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼

操作请求数据

对于web 应用来说对客户端向服务器发送的数据做出相应很重要,在Sanic中由传入的参数 request来提供请求信息。

为什么不像Flask 一样提供一个全局变量 request?

Flask 是同步请求,每次请求都有一个独立的新线程来处理,这个线程中也只处理这一个请求。而Sanic是基于协程的处理方式,一个线程可以同时处理几个、几十个甚至几百个请求,把request作为全局变量显然会比较难以处理。

Request 对象常用参数有

json(any) json body

from sanic.response import json

@app.route("/json")

def post_json(request):

return json({ "received": True, "message": request.json })

args(dict) URL请求参数

?key1=value1&key2=value2 将转变为

{'key1': ['value1'], 'key2': ['value2']}

raw_args(dict) 和args 类似

?key1=value1&key2=value2 将转变为

{'key1': 'value1', 'key2': 'value2'}

form(dict)处理 POST 表单请求,数据是一个字典

body(bytes)处理POST 表单请求,数据是一个字符串

其他参数还有:

file

ip

app

url

scheme

path

query_string

详细信息参考文档: Request Data

关于响应

Sanic使用response 函数创建响应对象。

文本 response.text('hello world')

html response.html('

hello world

')

json response.json({'hello': 'world'})

file response.file('/srv/www/hello.txt')

streaming

from sanic import response

@app.route("/streaming")

async def index(request):

async def streaming_fn(response):

response.write('foo')

response.write('bar')

return response.stream(streaming_fn, content_type='text/plain')

redirect response.file('/json')

raw response.raw('raw data')

如果想修改响应的headers可以传入headers 参数

from sanic import response

@app.route('/json')

def handle_request(request):

return response.json(

{'message': 'Hello world!'},

headers={'X-Served-By': 'sanic'},

status=200

)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值