1

To minimize the request time I want to execute the method after return 200 to client.

@app.route('/register', methods=['POST'])
def register():
      #code and code
      return 200
      send_email_with_validation_url()

How can I do it? With threads?

urb
  • 924
  • 1
  • 13
  • 28

2 Answers2

5

You can do it with threads, but without some control you could end up with lots of threads choking resources. You could also end up with processes crashing without you being aware.

This is the job for a queue system. Celery would be a good fit. Something along the lines of:

from celery import Celery

app = Celery('tasks', broker='amqp://guest@localhost//')

@app.task
send_email_job(address):
    send_email_with_validation_url()


@app.route('/register', methods=['POST'])
def register():
      #code and code
      send_email_job.delay(address)
      return 200

In this example, send_email_job will be scheduled run in the background (in a different thread or process or even machine if you want) with the given arguments and your server will return immediately.

Joe
  • 46,419
  • 33
  • 155
  • 245
0

Celery is great but if the task isn't critical asyncio would be a great option to explore, see this

Jibin Mathew
  • 4,816
  • 4
  • 40
  • 68