如何解决如何将Faust与Django集成?
我正在尝试将Faust与Django集成以将消息发布到Kafka。 这是浮士德回购中的示例:https://github.com/robinhood/faust/tree/master/examples/django
我做了一些修改,并创建了视图以通过Faust将数据推送到Kafka。
from django.shortcuts import render
from asgiref.sync import async_to_sync
from accounts.agents import AccountRecord,add_account
async def send_data() -> None:
print("sending..data")
print(await add_account.ask(AccountRecord(name="tesst",score=10.9,active=False)))
def index(request):
async_to_sync(send_data)()
return render(request,"accounts/index.html")
但是,我现在收到此错误:
RuntimeError at /
Task <Task pending name='Task-1' coro=<AsyncToSync.main_wrap() running at /Users/mysuer/.pyenv/versions/3.8.3/envs/faustdjango/lib/python3.8/site-packages/asgiref/sync.py:204> cb=[_run_until_complete_cb() at /Users/mysuer/.pyenv/versions/3.8.3/lib/python3.8/asyncio/base_events.py:184]> got Future <Future pending> attached to a different loop
我正在使用开发服务器运行此Django应用。 我在做什么错了?
解决方法
请参阅 faust documentation
中的常见问题解答部分我可以将 Faust 与 Django/Flask/等一起使用吗?
是的!使用 eventlet
作为与 asyncio
集成的桥梁。
使用eventlet
这种方法适用于任何可以与 eventlet
一起使用的阻塞 Python 库。
使用 eventlet
需要您安装 aioeventlet
模块,并且您可以将其与 Faust 一起安装为一个包:
$ pip install -U faust[eventlet]
然后要实际使用 eventlet 作为事件循环,您必须使用 -L <faust --loop>
程序的 faust
参数:
$ faust -L eventlet -A myproj worker -l info
或在入口点脚本的顶部添加 import mode.loop.eventlet
:
#!/usr/bin/env python3
import mode.loop.eventlet # noqa
警告 这是非常重要的,它位于模块的最顶部,并且在您导入库之前执行。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。