0

I'm a total newbie at flask...

I would like to run a long script (which takes about 30 second) after processing a post request with flask. I've found the @app.after_request option, but the problem is flask only returns the response after processing the after request script. here is my code -

#!/usr/bin/python

from flask import Flask, request
import json
import subprocess
import time
import commands
from flask import g


app = Flask(__name__)

@app.route('/payload',methods=['POST'])
def processWebhook():
    return 'OK', 200

@app.after_request
def runScript(response):
    time.sleep(30) #this is where my script will run
    return response

if __name__ == '__main__':
   app.run(port=4995,host='0.0.0.0')

how can I make flask to return the response and run the script after the request?

any help would be appreciated.

Gilad Sharaby
  • 910
  • 9
  • 12
  • 1
    you cannot run script after function return response. you should do something with asynchronous ways before return response. you can run a script to /dev/null with [subprocess](https://docs.python.org/2/library/subprocess.html) module. or more elegant way you can use message queue related techniques like [celery](http://www.celeryproject.org). – talhasch Aug 11 '16 at 11:24

1 Answers1

0

You can use APScheduler to run your code background every hour and return the response immediately after posting necessary data.

You can see the demo in that link.

  • Hi. This could be answer to the question but please note that links tend to get broken over time. Please consider copying & pasting the relevant parts of the link to your post, or adding more explanations of your own. Thanks. – lrnzcig Oct 22 '16 at 17:53