Search code examples
pythonpython-3.xflaskflask-restful

Python - How to run multiple flask apps from same client machine


I have one flask application script as given below :

from flask import Flask
app = Flask(__name__)

@app.route("/<string:job_id>")
def main(job_id):
    return "Welcome!. This is Flask Test Part 1"

if __name__ == "__main__":
    job_id = 1234
    app.run(host= '0.0.0.0')

I have another flask application script as below :

from flask import Flask
app = Flask(__name__)

@app.route("/<string:ID>")
def main(ID):
    return "Welcome!. This is Flask Test Part 2"

if __name__ == "__main__":
    ID = 5678
    app.run(host= '0.0.0.0')

The only difference between both the scripts is the argument name and its value. Now my question is assume that I am executing the first script. So I will get something like

* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)

When I execute http://127.0.0.1:5000/1234 in my browser I am able to see

"Welcome!. This is Flask Test Part 1"

Now with this server active, I am executing the second script. So again I get

* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)

But when I execute http://127.0.0.1:5000/5678 in my browser I am able to see

"Welcome!. This is Flask Test Part 1"

instead of

"Welcome!. This is Flask Test Part 2"

I don't understand where I am doing mistake. Any inputs or alterations will be helpful


Solution

  • Flask development server by default listens on port 5000 so when you run a Flask app without port number it will run on 5000.

    You can run a number of Flask app on the same machine but with the different port numbers. Let's say your scripts names are script1.py and script2.py:

    $ export FLASK_APP=script1.py
    $ flask run --host 0.0.0.0 --port 5000
    

    Open up a new terminal

    $ export FLASK_APP=script2.py
    $ flask run --host 0.0.0.0 --port 5001