运行时警告:从未等待协同程序'qr.<locals>.confirm'

2024-04-26 20:40:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在烧瓶里写一个网络应用程序。在我的一个路由中,我有一个函数监听API并等待注册付款。函数名为confirm()。我在render_template中以confirm=confirm的形式传递它,并在页面上使用Jinja2:{{ confirm(cost) }}调用它

我已经意识到需要异步调用函数,因为否则页面在付款之前不会加载。然而,我得到了一个名义上的错误,这个函数需要等待。读过之后,我尝试将路由更改为async def qr(),但Flask不会加载它,因此我不确定在这种情况下应该如何使用await

async def confirm(cost):
        json = { "action": "account_history", "account": app.config['NANO'], "count": 5, "raw": False, "reverse": False }
        now = datetime.now()
        delta = timedelta(seconds=60)
        while datetime.now() < now+delta:
            test = requests.post("https://nanoverse.io/api/node",json=json).json()
            for item in test["history"]:
                if item["amount"] == cost:
                    flash("Payment Received!")
                    break
            else:
                continue
            break

Tags: 函数testjsonfalse路由datetimeasyncdef
1条回答
网友
1楼 · 发布于 2024-04-26 20:40:45

为了能够在jinja2模板中使用Awaitable对象,必须使用enable_async选项创建environment。 参考:https://jinja.palletsprojects.com/en/2.11.x/api/#async-support

要从flask执行此操作,您需要在运行应用程序之前通过jinja_options进行设置。像这样:

from flask import Flask

app = Flask(__name__)
app.jinja_options['enable_async'] = True

现在只剩下一个问题了。根据jinja2的AsyncSupport文件:

asyncio.get_event_loop() must return an event loop. Since flask creates a new Thread for each request there will be no evet_loop for jinja. So something like this must be done to get it working:

@app.route('/')
def example():
    # ...
    asyncio.set_event_loop(asyncio.new_event_loop())
    
    return render_template('index.html', confirm=confirm)

要小心如何提供事件循环。我不认为这是一种生产就绪的方法。这只是一个概念证明,以演示它应该如何工作。我认为“为flask线程提供事件循环的最佳实践”是另一个问题

相关问题 更多 >