python - 使用 websocket 的龙卷风/异步问题
问题描述
我正在将我的应用程序从 Python 2 转换为 Python 3。简而言之,我的应用程序在 Python(服务器)和 Javascript(客户端)中工作,它们通过 websocket 连接,我使用 tornado 连接。在 Python,我有多个线程。我没有在任何地方使用 Python3 的 asyncio 方法。
但是,在将我的应用程序从 Python 2.7(它在 Python2 中完美运行)转换为 Python 3.7 时,我遇到了 tornado/asyncio 的问题。
首先,我得到了错误:RuntimeError: There is no current event loop in thread 'Thread-26'
.
经过一番谷歌搜索后,我发现了一个缓解这种情况的建议:
import tornado.platform.asyncio
import asyncio
asyncio.set_event_loop_policy(tornado.platform.asyncio.AnyThreadEventLoopPolicy())
这似乎解决了该错误。但是,现在我收到以下警告+错误:
2019-08-24 13:27:25,455 asyncio DEBUG Using selector: SelectSelector
2019-08-24 13:28:25,455 asyncio ERROR Task was destroyed but it is pending!
task: <Task pending coro=<WebSocketProtocol13.write_message.<locals>.wrapper() running at C:\Users\DLA\PycharmProjects\myPmese\Python3\lib\site-packages\tornado\websocket.py:1102>>
关于发生了什么的任何线索?不幸的是,我找不到我的 Python 代码的确切部分导致了这种情况。
非常感谢!任何帮助,将不胜感激 :)
您可以在下面使用 tornado 找到我的 Python websocket 的架构:
import tornado.platform.asyncio
import asyncio
asyncio.set_event_loop_policy(tornado.platform.asyncio.AnyThreadEventLoopPolicy())
application = tornado.web.Application([(r'/myPmese/websocket', WSocketHandler)])
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8295)
tornado.ioloop.IOLoop.instance().start()
class WSocketHandler(tornado.websocket.WebSocketHandler):
def initialize(self):
print('initialize') # here I initialise handlers
def open(self):
start_server_code() # triggers the code from the server.
def __call__(self, *args):
clientCommand = self.getClientCommand()
self.resetClientCommand()
self.send(clientCommand , *args)
def send(self, var_func, *args):
try:
self.write_message(json.dumps(self.getClientCommand()))
except Exception as e:
print(traceback.format_exc())
def on_message(self, message):
if message != '':
try:
eval(self.executeCommand(message))
except Exception as e:
print(traceback.format_exc())
self.send('createErrorMessage', str(e))
def on_close(self):
tornado.ioloop.IOLoop.instance().stop()
解决方案
推荐阅读
- python - 如何在 Apache Beam (Python) 中按键在静态查找表上以流模式加入 PCollection
- c# - UDP 打孔 - 可靠的算法
- html - 尝试使用scrapy spider在microsoft.com中查找登录链接
- javascript - react-native-snap-carousel 无法正确渲染
- tensorflow - Tensorflow-gpu + Keras 安装报错:无法加载原生 TensorFlow 运行时
- java - 从属性文件中读取俄语文本用问号替换俄语字符
- c# - 如何修复“提供了无效的请求 URI”。请求 URI 必须是绝对 URI 或必须设置 BaseAddress'
- google-cloud-dataflow - 有没有办法提高 Google Cloud Dataflow Worker Threading 的数量?
- c# - 播放后如何删除 WMP 播放列表?
- r - 为什么我的向量在积分等于或大于 12 的整数后变成一个列表?