正如我在标题中所说,我希望在处理来自前端的请求时在后台运行一个任务来处理大型数据库查询。我什至可以使用 async/asyncio 来做到这一点吗?有人告诉我这是可能的...
出于上下文的目的,我想做如下的事情。另请注意,我实际上并不需要该函数告诉我何时完成(尽管我肯定想知道是否可能),因为我只是检查 .json 文件是否最终写入。
def post_data_view(request):
if request.method == 'POST':
...
do_long_query_in_the_background(some_data)
return HttpResponse('Received. Ask me in a while if I finished.')
def is_it_done_view(request):
if request.method == 'GET':
data = find_json()
if data:
return JsonResponse(data)
else:
return HttpResponse('Not yet dude...')
async def do_long_query_in_the_background(data):
# do some long processing...
# dump the result to a result.json
return
Run Code Online (Sandbox Code Playgroud)
有人告诉我这可以通过异步实现,但我真的很难理解。对于上下文,我试图简化这一点,即使如此,我发现我不太明白发生了什么:
async def f():
while True:
print(0)
await asyncio.sleep(2)
asyncio.create_task(f())
Run Code Online (Sandbox Code Playgroud)
即使我尝试的这段代码也失败了sys:1: RuntimeWarning: coroutine 'f' was never awaited,但它确实可以在控制台上运行,我不明白为什么会这样。
我还想知道这对于线程来说是否可能并且安全?
我对此感到非常沮丧,因为其他线程中建议的一般解决方案似乎只是使用芹菜,但对于一个不那么复杂的问题来说,它确实感觉有点矫枉过正。
我正在尝试创建一个不和谐机器人,我需要在另一个新线程中运行异步函数,因为主线程需要运行另一个函数(不和谐客户端)
我正在努力实现的目标:
# This methods needs to run in another thread
async def discord_async_method():
while True:
sleep(10)
print("Hello World")
... # Discord Async Logic
# This needs to run in the main thread
client.run(TOKEN)
thread = ""
try:
# This does not work, throws error "printHelloWorld Needs to be awaited"
thread = Thread(target=discord_async_method)
thread.start()
except (KeyboardInterrupt, SystemExit):
# Stop Thread when CTRL + C is pressed or when program is exited
thread.join()
Run Code Online (Sandbox Code Playgroud)
我尝试过使用 asyncio 的其他解决方案,但无法让其他解决方案发挥作用。
后续:当您创建一个线程时,当您停止程序(即KeyboardInterupt或SystemExit)时,如何停止该线程?
任何帮助将不胜感激,谢谢!