Last active
August 29, 2015 14:06
Flask Hello
This file contains 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
# Simple http server to test concurrency or load balancing or whatever, | |
# specifying numprocs greater than 1 will run that many instances of the | |
# flask app in subprocesses on incrementing ports beginning with the one specified | |
# Run: | |
# sudo pip install flask | |
# python hello.py [PORT-NUM] [NUMPROCS] | |
from flask import Flask | |
import os | |
import signal | |
import subprocess | |
import sys | |
app = Flask(__name__) | |
@app.route('/') | |
def hello_world(): | |
return "Hello from {0}".format(os.getpid()) | |
def run_multi_in_subprocs(numprocs, starting_port): | |
procs = [] | |
for port in xrange(starting_port, starting_port + numprocs): | |
procs.append(subprocess.Popen(['python', __file__, str(port)])) | |
def cleanup_for_exit(signal, frame): | |
print "Caught SIGINT, killing {0} subproccesses and exiting".format(len(procs)) | |
[p.kill() for p in procs] | |
sys.exit(0) | |
signal.signal(signal.SIGINT, cleanup_for_exit) | |
signal.pause() | |
if __name__ == '__main__': | |
port = int(sys.argv[1]) if len(sys.argv) > 1 else 5000 | |
numprocs = int(sys.argv[2]) if len(sys.argv) > 2 else 1 | |
if numprocs == 1: | |
app.run(host='0.0.0.0', port=int(port)) | |
else: | |
run_multi_in_subprocs(numprocs, port) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment