有没有什么办法让Python的[Django的]一个异步函数调用? [英] Is there any way to make an asynchronous function call from Python [Django]?

查看:614
本文介绍了有没有什么办法让Python的[Django的]一个异步函数调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个Django应用程序,做各种计算长与上传的文件。我不想让用户等待文件进行处理 - 我只是想表明一个网页阅读像文件正在被解析用户

我怎样才能从视图异步函数调用?

东西,可能看起来像:

 高清视图(要求):
    ...
    如果form.is_valid():
        form.save()
        async_call(handle_file)
    返回render_to_response(...)


解决方案

而不是试图通过子进程或线程来管理这一点,我建议你完全分离出来。有两种方法:第一种是在数据库表中设置一个标志的地方,并有规律地运行一个cron作业,检查标志并执行所需的操作。

第二个选择是使用一个消息队列。文件上传过程中发送队列中的消息,和一个单独的侦听器接收消息并确实需要些什么。我用的RabbitMQ对于这样的事情,但其他人都可以。

无论哪种方式,用户不必等待进程结束,你不必担心管理的子进程。

I am creating a Django application that does various long computations with uploaded files. I don't want to make the user wait for the file to be handled - I just want to show the user a page reading something like 'file is being parsed'.

How can I make an asynchronous function call from a view?

Something that may look like that:

def view(request):
    ...
    if form.is_valid():
        form.save()
        async_call(handle_file)
    return render_to_response(...)

解决方案

Rather than trying to manage this via subprocesses or threads, I recommend you separate it out completely. There are two approaches: the first is to set a flag in a database table somewhere, and have a cron job running regularly that checks the flag and performs the required operation.

The second option is to use a message queue. Your file upload process sends a message on the queue, and a separate listener receives the message and does what's needed. I've used RabbitMQ for this sort of thing, but others are available.

Either way, your user doesn't have to wait for the process to finish, and you don't have to worry about managing subprocesses.

这篇关于有没有什么办法让Python的[Django的]一个异步函数调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆