sanic官方文档解析之Custom Protocols(自定义协议)和Socket(网络套接字)

1,Custom Protocol:自定义协议

 温馨提示:自定义协议是一个高级用法,大多数的读者不需要用到此功能

通过特殊的自定义协议,你可以改变sanic的协议,自定义协议需要继承子类asyncio.protocol,这个子类在sanic.run方法中传输关键字protocol协议

自定义协议的构造类从sanic中接收关键字参数.

  • loop: an asyncio-compatible event loop.(循环:异步兼容事件循环)
  • connections: a set to store protocol objects. When Sanic receives SIGINT or SIGTERM, it executes protocol.close_if_idle for all protocol objects stored in this set.(连接:一个存储协议对象的集合当接收到一个信号的时候,将会执行自定义的协议,close_if_idle会为所有的协议对象存储在这个集合中)
  • signal: a sanic.server.Signal object with the stopped attribute. When Sanic receives SIGINTor SIGTERMsignal.stopped is assigned True(信号:一个sanic服务器信号对象是用sanic停止的属性来控制的,当sanic接收到信号,stopped的属性就会变成Ture)
  • request_handler: a coroutine that takes a sanic.request.Request object and a response callback as arguments(处理请求:将sanic的请求对象和响应回调作为参数的协程)
  • error_handler: a sanic.exceptions.Handler which is called when exceptions are raised.(错误处理程序:当异常被抛出的时候,调用sanic.exception.Handler)
  • request_timeout: the number of seconds before a request times out(请求超时:在请求超时前会有一些秒数.)
  • request_max_size: an integer specifying the maximum size of a request, in bytes.(最大请求的量:指定请求最大的整数,以字节为单位)

例子:

如果一个处理函数没有返回一个HTTPResponse对象,表名一个错误的发生在默认的谢一中.通过重写write

_response协议方法,如果处理程序返回一个字符串被转换成一个HTTPResponse响应对象

from sanic import Sanic
from sanic.server import HttpProtocol  # 在sanic的服务中存在HTTP协议
from sanic.response import text

# 实例化一个Sanic对象
app = Sanic(__name__)


class CustomHttpProtocol(HttpProtocol):

    # 初始化方法
    def __init__(
            self,
            *,
            loop,
            request_handdler,
            error_handler,
            signal,
            connections,
            request_timeout,
            request_max_size,
    ):
        # 执行父类的初始化方法
        super().__init__(
            loop=loop,
            request_handler=request_handdler,
            error_handler=error_handler,
            signal=signal,
            connections=connections,
            request_timeout=request_timeout,
            request_max_size=request_max_size
        )

    # 返回响应的方法
    def write_response(self, response):
        # 如果存在response对象
        if isinstance(response, str):
            # 封装response响应对象
            response = text(response)
        self.transport.write(
            # 封装请求的信息
            response.output(self.request.version)
        )
        self.transport.close()


@app.route("/")
async def string(request):
    return "string"


@app.route("/i")
async def response(request):
    return text("response")

app.run(host="0.0.0.0", port=8000, protocol=CustomHttpProtocol)  # 启动服务的时候指定协议为自定义协议

2,Socket(网络套接字)

Sanic可以使用Python中的socket模块来容纳IPV4的socket

from sanic import Sanic
from sanic.response import json
import socket
# 实例化socket对象
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
sock.bind(("::", 7777))  # 绑定一个元组
# 实例化一个sanic对象
app = Sanic()


# 业务处理函数
@app.route("/")
async def test(request):
    return json({"hello": "world"})

if __name__ == '__main__':
    app.run(sock=sock)  # 以网络套接字的形式开启服务

UNIX的例子如下:

import signal
import sys
import socket
import os
from sanic import Sanic
from sanic.response import json

server_socket = "/tmp/sanic.sock"
# 实例化socket对象
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)  # socket.UNIX这个参数不对,是不是官网错了
sock.bind(server_socket)  # 绑定
# 实例化Sanic对象
app = Sanic()


@app.route("/")
async def test(request):
    return json({"hello": "world"})


def signal_handler(sig, frame):
    print("Exiting")
    os.unlink(server_socket)
    sys.exit(0)

if __name__ == '__main__':
    app.run(sock=sock)
原文地址:https://www.cnblogs.com/ljc-0923/p/10391827.html