gpt4 book ai didi

python Tornado websocket错误: RuntimeError: There is no current event loop in thread 'Thread-1'

转载 作者:行者123 更新时间:2023-12-01 14:15:22 25 4
gpt4 key购买 nike


我有以下代码,它在 Tornado <5 上运行良好,但如果我在 Tornado>= 5 上运行它会失败,

import tornado.httpserver
import tornado.ioloop
import threading
import tornado.web,tornado.websocket

class thr(threading.Thread):
def __init__(self,handler):
self.handler=handler
threading.Thread.__init__(self)
def run(self):
self.handler.write_message("test")
class ClientWebSocketConnectionHandler(tornado.websocket.WebSocketHandler):
def open(self):
print ("opened")
def on_message(self, message):
thr(self).start()

class MainApplication(tornado.web.Application):
def __init__(self):
handlers = [(r'/User', ClientWebSocketConnectionHandler),]
tornado.web.Application.__init__(self, handlers,)

TheShieldsWebSocket = MainApplication()
server = tornado.httpserver.HTTPServer(TheShieldsWebSocket)
server.listen(8085,'0.0.0.0')
tornado.ioloop.IOLoop.instance().start()



错误提示:RuntimeError: There is no current event loop in thread 'Thread-1'

这到底是怎么回事?看起来和线程有关。

最佳答案

假设你想写一个 api,这个 api 在渲染到客户端之前可能需要等待一些东西!这是实现这一目标的几种方法!因为你已经使用了 thread 这很好但不推荐。所以我们在 Tornado 中调用了并发,你可以看到细节 here .

这里你的代码可以修改如下:

import tornado.httpserver
import tornado.ioloop
import tornado.web,tornado.websocket


class ClientWebSocketConnectionHandler(tornado.websocket.WebSocketHandler):
def open(self):
print ("opened")
def on_message(self, message):
self.write_message('test')

class MainApplication(tornado.web.Application):
def __init__(self):
handlers = [(r'/User', ClientWebSocketConnectionHandler),]
tornado.web.Application.__init__(self, handlers,)

TheShieldsWebSocket = MainApplication()
server = tornado.httpserver.HTTPServer(TheShieldsWebSocket)
server.listen(8085,'0.0.0.0')
tornado.ioloop.IOLoop.instance().start()

通常,您会收到 403 错误,在这种情况下,您可以添加一个函数名称作为 check_origin

    # rest of above code
def check_origin(self, param):
return True

def open(self):
print ("opened")
def on_message(self, message):
self.write_message('test')

然后如果你想让你的服务器可以处理多连接,你可以使用`并发方式来做到这一点,如下所示:

    @gen.coroutine
def on_message(self, message):
http_client = AsyncHTTPClient()
response = yield http_client.fetch("http://example.com")
do_something_with_response(response)
self.write_message('test')

关于python Tornado websocket错误: RuntimeError: There is no current event loop in thread 'Thread-1' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50171354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com