Created
November 8, 2016 14:06
-
-
Save naushadzaman/b65534d912f1551c7d8366b326b7a151 to your computer and use it in GitHub Desktop.
Reload python flask server by function / API endpoint
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
# Reload python flask server by function / API endpoint | |
# References: | |
# https://docs.python.org/3/library/multiprocessing.html | |
# http://stackoverflow.com/questions/27723287/reload-python-flask-server-by-function | |
import os | |
import sys | |
import time | |
import subprocess | |
from flask import Flask, request, jsonify | |
from multiprocessing import Process, Queue | |
some_queue = None | |
app = Flask(__name__) | |
#CORS(app) | |
@app.after_request | |
def after_request(response): | |
response.headers.add('Access-Control-Allow-Origin', '*') | |
response.headers.add('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers') | |
response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS') | |
return response | |
@app.route('/') | |
def routes(): | |
return jsonify(items={'error':'YOU SHOULD NOT BE HERE!'}) | |
@app.route('/restart') | |
def restart(): | |
try: | |
some_queue.put("something") | |
print "Restarted successfully" | |
return "Quit" | |
except: | |
print "Failed in restart" | |
return "Failed" | |
def start_flaskapp(queue): | |
global some_queue | |
some_queue = queue | |
app.run() | |
if __name__ =='__main__': | |
q = Queue() | |
p = Process(target=start_flaskapp, args=[q,]) | |
p.start() | |
while True: #wathing queue, if there is no call than sleep, otherwise break | |
if q.empty(): | |
time.sleep(1) | |
else: | |
break | |
p.terminate() #terminate flaskapp and then restart the app on subprocess | |
args = [sys.executable] + [sys.argv[0]] | |
subprocess.call(args) |
How to redirect to main url after reload?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
p = Process(target=start_flaskapp, args=[q,])
should bep = Process(target=start_flaskapp, args=(q,))
Except for the small syntax error, not bad solution.