事倍功半是蠢蛋2(SSE)

空心橙子發表於2024-11-06
class KernelSSEPushHandler(BaseHandler):

    def __init__(self, *args, **kwargs):
        super(KernelSSEPushHandler, self).__init__(*args, **kwargs)

    def initialize(self, *args, **kwargs) -> NoReturn:
        super(KernelSSEPushHandler, self).initialize(*args, **kwargs)
        # 關閉自動finish
        self._auto_finish = False

    def set_default_headers(self, *args, **kwargs):
        # 事件驅動模式
        self.set_header('Content-Type', "text/event-stream")
        self.set_header('Content-Control', "no-cache")
        self.set_header('Connection', "keep-alive")
        # 允許跨域
        self.set_header('Access-Control-Allow-Origin', "*")
        self.set_header('Access-Control-Allow-Headers', "Content-Type")
        self.set_header('Access-Control-Allow-Methods', "GET, POST, OPTIONS")
        super(KernelSSEPushHandler, self).set_default_headers(*args, **kwargs)

    async def get(self):
        import random
        client_id = id(self)
        add_key_value_pair(client_id)
        while True:
            await tornado.gen.sleep(2)
            if self.request.connection.stream.closed():
                delete_key_value_pair(client_id)
                break
            data = get_and_pop_from_queue(client_id)
            if data is None:
                continue
            self.write(f"data: {data}\n\n")
            # self.write(f"data: {data}")
            try:
                await self.flush()
            except StreamClosedError:
                pass


tornado 必須是 self.write(f"data: {data}\n\n") 否則前端列印不出來

相關文章