使用asyncio执行异步任务

问题描述

我有python flask应用程序,可在kafka中推送任务以使用浮士德进行处理。 我正在执行send_data之类的浮士德函数loop.run_until_complete(send_data())

并实现我所写文件的顶部

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

我的问题是我必须在调用浮士德函数的每一页上编写以下代码

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

代码

main.py

import os
from flask import Flask
from page_views import call

os.environ.setdefault('FAUST_LOOP','eventlet')
app = Flask(__name__)

@app.route("/")
def hello():
  return call()

page_views.py

import faust
from faust.types import StreamT
import asyncio

app = faust.App(
  'page_views',broker='kafka://localhost:9092',origin='faust-app'
)

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

class PageView(faust.Record):
  id: str
  user: str

page_view_topic = app.topic('page_view_topic',value_type=PageView)

# add table if didn't worked
page_views = app.Table('page_views',default=int)

@app.agent(page_view_topic)
async def count_page_views(views: StreamT[PageView]):
  async for view in views:
    print(view.id)

async def send_data():
  await count_page_views.send(value=PageView(id=100,user="sahilpaudel"))

def call():
  loop.run_until_complete(send_data())
  return "hello world"

像page_views.py一样,我还有其他异步任务和需要调用的路由。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)