簡體   English   中英

我如何在龍卷風中的相同URL上提供HTTP頁面和Websocket

[英]How can I serve a HTTP page and a websocket on the same url in tornado

我有一個API,並且根據請求協議,我想為客戶端提供HTTP響應,或者我想連接一個websocket並發送響應,然后進行增量更新。 但是在龍卷風中,我只能為任何URL指定一個處理程序。

HTTP頁面請求和Websocket之間的區別是標頭的存在。 不幸的是,afaik無法告訴龍卷風路由器根據標頭(主機除外)選擇一個或另一個處理程序。

但是,我可以制作一個從我已經非常精巧的MyBaseRequestHandlerWebSocketHandler繼承的處理程序,並且具有一些魔力。 以下代碼可在python 3.5和龍卷風4.3中使用,您的里程可能在其他版本上有所不同:

class WebSocketHandlerMixin(tornado.websocket.WebSocketHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # since my parent doesn't keep calling the super() constructor,
        # I need to do it myself
        bases = type(self).__bases__
        assert WebSocketHandlerMixin in bases
        meindex = bases.index(WebSocketHandlerMixin)
        try:
            nextparent = bases[meindex + 1]
        except IndexError:
            raise Exception("WebSocketHandlerMixin should be followed "
                            "by another parent to make sense")

        # undisallow methods --- t.ws.WebSocketHandler disallows methods,
        # we need to re-enable these methods
        def wrapper(method):
            def undisallow(*args2, **kwargs2):
                getattr(nextparent, method)(self, *args2, **kwargs2)
            return undisallow

        for method in ["write", "redirect", "set_header", "set_cookie",
                       "set_status", "flush", "finish"]:
            setattr(self, method, wrapper(method))
        nextparent.__init__(self, *args, **kwargs)

    async def get(self, *args, **kwargs):
        if self.request.headers.get("Upgrade", "").lower() != 'websocket':
            return await self.http_get(*args, **kwargs)
        # super get is not async
        super().get(*args, **kwargs)


class MyDualUseHandler(WebSocketHandlerMixin, MyBaseHandler):
    def http_get():
        self.write("My HTTP page")

    def open(self, *args, **kwargs):
        self.write_message("Hello WS buddy")

    def on_message(self, message):
        self.write_message("I hear you: %s" % message)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM