2

我正在研究 Sanic,因为我们正在寻找基于烧瓶的休息服务的替代品。我对 sanic 的异步特性很感兴趣,但我知道我们会遇到很多根本不支持异步的代码(例如,我们在 DynamoDB 之上使用了大量的 boto3 和一些 ORM,没有其中支持等待)。

所以:我需要找到能够在像 Sanic 这样的异步框架中运行同步代码的最简洁的方法。在 python 3.7 中有一个我觉得很有趣的 asyncio.create_task 调用。

想知道这是否是一种可能的方式:

主要.py:

#default boilerplate sanic code excluded for brevity
from app_logic import AppLogic

@app.route("/")
async def test(request):
    task = await asyncio.create_task(AppLogic.sync_request('https://stuff.com'))
    return json({"hello": "world", 'status_code': task.status_code})

app_logic.py:

import requests

class AppLogic(object):
    @staticmethod
    async def sync_request(url='https://myurl.com'):
        #Some non-async library/code thingy
        print('requesting the thing')
        return requests.get(url)

这似乎可行,并且返回的任务对象是常规requests响应。

但是,我不知道这是否“安全”——例如,我不确定如何调查事件循环并验证它没有以任何方式阻塞。我确信这种方法完全愚蠢还有其他原因,所以把它们放在我身上:-)

4

0 回答 0