什么是异步运行一些Python代码的正确方法? [英] What's the proper way to run some Python code asynchronously?

查看:228
本文介绍了什么是异步运行一些Python代码的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从我的Flask应用程序发送邮件,所以我想最简单的方法是使用smtplib发送邮件。但是我不得不这样做 - 你不能在请求中插入一个3秒的延迟 - 对吧?所以我把电子邮件添加到一个队列(psql表),并从另一个程序读取此表并使用smptlib发送它。



第二个程序(maildonkey)正在运行作为一个独立的进程,在一个独立的新贵服务。

现在我需要另一个小asynchoronous服务,我在想如果我应该写另一个python脚本第三,计数我的Flask应用程序和'maildonkey'),还是应该使用类似Python的'multiprocess',甚至'线程',并重写第二个程序? >(当我在Clojure编程时,我可以很容易地运行代码在一个单独的线程与'期货',所以通常我会做到这一点。)

解决方案

您应该考虑使用芹菜。它被广泛用于异步处理的web框架,并支持许多不同的后端,如AMQP,数据库等。

I needed to send mail from my plain Flask app, so I thought the simplest way would be to send it using smtplib. But I had to do it asynchronously - you can't just insert a 3 second delay into the request - right? So I add the email to a queue (psql table), and send it from another program that reads this table and uses smptlib.

This second program (maildonkey) is running as a separate process, in an independent upstart service.

Now I need another one of those little asynchoronous services, and I'm thinking if I should write another python script (third, counting my Flask app and 'maildonkey') or should I use something like Python's 'multiprocess', or even 'threads' and rewrite the second program?

(When I was programming in Clojure, I could easily run code in a separate thread with 'futures', so normally I would do that.)

解决方案

You should consider using Celery. It is very widely used in web frameworks for asynchronous processing and supports a lot of different backends like AMQP, databases etc.

这篇关于什么是异步运行一些Python代码的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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