Skip to content

Instantly share code, notes, and snippets.

@dcosson
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcosson/41d41dcc8c6b276ced50 to your computer and use it in GitHub Desktop.
Save dcosson/41d41dcc8c6b276ced50 to your computer and use it in GitHub Desktop.
Flask Hello
# 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