Skip to content Skip to sidebar Skip to footer

Port Management In Python/flask Application

I am writing a REST API using the micro framework Flask with python programming language. In the debug mode the application detect any change in source code and restart itself usin

Solution 1:

This code test.py doesn't change port that's specified in .run() args:

from flask import Flask    

app = Flask(__name__)

@app.route("/")defindex():
    return"123"

app.run(host="0.0.0.0", port=8080) # or host=127.0.0.1, depends on your needs

There is nothing that can force flask to bind to another TCP port in allowed range if you specified the desired port in run function. If this port is already used by another app - you will see OSError: [Errno 98] Address already in use after launching.

UPD: This is output from my pc if I run this code several time using python test.py command:

artem@artem:~/Development/$ python test.py
 * Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
^Cartem@artem:~/Development$ python test.py
 * Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
^Cartem@artem:~/Development/$ python test.py
 * Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
^Cartem@artem:~/Development/$ python test.py
 * Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
127.0.0.1 - - [20/Nov/201717:04:56] "GET / HTTP/1.1"200 -

As you can see flask gets binded to 8080 port every time.

UPD2: when you will setup production env for your service - you won't need to take care of ports in flask code - you will just need to specify desired port in web server config that will work with your scripts through wsgi layer.

Post a Comment for "Port Management In Python/flask Application"