python - 龙卷风 RequestHandler 中的 Python AsyncHttpClient 抛出异常
问题描述
我将在 RequestHandler 中通过龙卷风 AsyncHttpClient 调用端点,但它会引发运行时异常This event loop is already running
class RegistrationHandler(tornado.web.RequestHandler):
def post(self, *args, **kwargs):
call_async_register("some params")
def call_async_register(parameters):
def call():
http_client = AsyncHTTPClient()
future = Future()
http_request = HTTPRequest(url, request_type.name, headers={'X-Peering': '1'}, body=body)
def handle_future(f: Future):
future.set_result(f.result())
fetched_future = http_client.fetch(http_request)
fetched_future.add_done_callback(handle_future)
return future
try:
instance = io_loop.IOLoop.current()
response = instance.run_sync(call)
return response.body.decode()
except Exception as err:
self.logger.exception("Account Request Failed: {}".format(err))
return None
解决方案
这是问题所在:
instance = io_loop.IOLoop.current()
response = instance.run_sync(call)
run_sync
本身尝试启动 ioloop。但从您的代码中可以明显看出,instance
它已经在运行。所以你得到了错误。
如果您想将call()
方法返回的值发送回用户,请将您的方法转换为协程(使用async/await
语法)。
例子:
class RegistrationHandler(tornado.web.RequestHandler):
async def post(self, *args, **kwargs):
response = await call_async_register("some params")
self.write(response)
async def call_async_register(parameters):
http_client = AsyncHTTPClient()
http_request = HTTPRequest(url, request_type.name, headers={'X-Peering': '1'}, body=body)
try:
response = await http_client.fetch(http_request)
return response.body.decode()
except Exception as err:
self.logger.exception("Account Request Failed: {}".format(err))
return None
推荐阅读
- python - Python切片复杂度?
- ios - 使用 UIImageView 在 UIView 中切割透明孔
- css - 选择最理想的字体格式
- ansible - Ansible Playbook 将数组列表作为变量传递
- excel - 通过比较动态值的条件格式:Excel
- javascript - 如何使用 Laravel 和 vue js 在数据库中显示单个记录?
- jmeter - 我们可以在测试执行期间添加额外的 Jmeter 负载生成器吗?
- ios - Cocoapods 无法安装 Trunk
- c# - RIDER 中缺少 ListView 控件
- anychart - 如何在 Anychart 中的股票标记系列上设置单个标记大小?