我正在使用flask为应用程序构建后端api,我需要做的一件事是:
1. get the content the user submited
2. send a twitter with that content
3. save the content to my DB and return the id of the new item
现在问题是第2步花费的时间太长,所以它会减慢总请求时间。
更具体地说,第2步是:twitter.send(content)
我怎么能让第2步异步? PS:我不需要知道第2步是否成功
答案 0 :(得分:4)
有一个烧瓶芹菜pacakge.http://pypi.python.org/pypi/Flask-Celery。 http://ask.github.com/celery/getting-started/introduction
你可以告诉芹菜不要异步做什么。
<强>更新强>
自Celery 3.0起,flask-celery不是必需的,您可以直接使用芹菜:pip install -U Celery
答案 1 :(得分:4)
我发现Celery和其他分布式任务框架对于像你或我这样的简单任务来说太重了,它们会异步发送电子邮件。
我最终使用工作流程池来处理我的电子邮件。 this answer问题的Asynchronous method call in Python?解释了该方法。在这个问题上接受的答案提供了一个使用Pool但没有装饰器的解决方案,所以它更简单。