1

我正在用 python 构建一个 ASGI 应用程序服务器并实现 HTTP/2 协议。我从套接字接收原始字节,解析字节并将它们转换为帧对象。当我触发 ASGI 应用程序时,send callable 只获取一个事件字典作为不包含流 ID 的参数。因为,我使用 async/await 我的服务器可以同时处理多个流。我如何知道哪个流 id 与哪个 send callable 相关联?

class Server(object):
  async def send_response(self, event):
    # event dict does not contain stream id
    if event["type"] == "http.response.start":
      # Need stream id here to create http2 frames
      ...
    elif event["type"] == "http.response.body":
      # Need stream id here to create http2 frames
      ...

  async def handle_request(self):
    try:
      while True:
        self.request_data = self.client_connection.recv(4096)
        self.frame = self.parse_request(self.request_data)

        if isinstance(self.frame, HeadersFrame):
          # stream id is available here as self.frame.stream_id
          if self.frame.end_stream:
            asgi_scope = self.get_asgi_event_dict(self.frame)
            self.asgi_app = self.application(asgi_scope)
            await self.asgi_app(self.trigger_asgi_application, self.send_response)

我希望能够在 send_response 函数中获取流 id。

4

0 回答 0