版权声明:严禁转载,如需转载请联系作者 https://blog.csdn.net/weixin_40005874/article/details/86351260
16. 自定义协议
注意⚠️: 这个高级功能要很多开发者不会使用。
开发者可以通过自定义一个asyncio.protocol的子类来重写Sanic的协议格式。用户可以通过在sanci.run()使用时进行protocol的关键字参数进行定义,开发者自定义的协议的类将会通过,接收Sanic传递的相关参数,具体如下所示:
参数 | 说明 |
---|---|
loop | 兼容的循环事件 |
connections | 当设置协议对象后,当Sanic接受Sigint或者Sigterm后,将会为所有的协议对象,执行protocol_close_if_idif |
signal | 一个标志服务器是否停止的标志,Sanic收到SIFNIT或者SIGTERM后,signal.stop将会被设置成Stop |
request_handler | 将sanic.request.Request对象和response的毁掉函数作为参数的协程 |
error_handler | 一个sanic.exceptions.Handler函数,当Sanic中发生异常后会被调用 |
request_timeout | 请求超时时间(秒) |
request_max_size | 请求数据的最大字节数 |
具体示例如下所示:
默认协议出现异常将不会返回响应对象,开发者通过重写wirte_response协议方法可以将字符串将转换成响应对象。
from sanic import Sanic
from sanic.server import HttpProtocol
from sanic.response import text
app = Sanic(__name__)
class CustomHttpProtocol(HttpProtocol):
def __init__(self, *, loop, request_handler, error_handler,
signal, connections, request_timeout, request_max_size):
super().__init__(
loop=loop, request_handler=request_handler,
error_handler=error_handler, signal=signal,
connections=connections, request_timeout=request_timeout,
request_max_size=request_max_size)
def write_response(self, response):
if isinstance(response, str):
response = text(response)
self.transport.write(
response.output(self.request.version)
)
self.transport.close()
@app.route('/')
async def string(request):
return 'string'
@app.route('/1')
async def response(request):
return text('response')
app.run(host='0.0.0.0', port=8000, protocol=CustomHttpProtocol)