2

I'm using flask to build the backend api for an application, one thing I need to do is:

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

now the problem is that step 2 takes too long time so it slows down the total request time.

to be more specific, step 2 is: twitter.send(content)

How could I make step 2 async? PS: I don't need to know if step 2 is successful or not

wong2
  • 34,358
  • 48
  • 134
  • 179

2 Answers2

4

there is a flask celery pacakge.http://pypi.python.org/pypi/Flask-Celery. http://ask.github.com/celery/getting-started/introduction.

You can tell celery what to do asyncronously.

  1. get content user submitted
  2. send celery a message that it should send a tweet as soon as it can
  3. save content to db and return the id of the new item.

step 2 coudl take as long as it needs this way and the user would never know.

UPDATE:
Since Celery 3.0, flask-celery is not required, you can use celery directly by: pip install -U Celery

zengr
  • 38,346
  • 37
  • 130
  • 192
dm03514
  • 54,664
  • 18
  • 108
  • 145
4

I find Celery and other distributed task frameworks too heavyweight for simple tasks like yours or mine, which is sending emails asynchronously.

I ended up using a Pool of worker processes to handle my emails. The method is explained in this answer to the Asynchronous method call in Python? question. The accepted answer on this question provides a solution that uses a Pool but without a decorator, so it is simpler.

Community
  • 1
  • 1
Miguel Grinberg
  • 65,299
  • 14
  • 133
  • 152