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 using the same host and port. In the production mode (no debug) the application does not restart it self when changing the source code so I have to restart the application by my self; the problem in this case is that the application cannot run using a port previously used in an old version the application, so I am asked to change the port with every app update:
This is how my code look like:
from flask import Flask, jsonify, request
import json
import osapp = Flask(__name__) @app.route('/method1', methods=['GET'])
def method1():return jsonify({"result":"true"})@app.route('/method2', methods=['GET'])
def method2():return jsonify({"result":"true"})if __name__ == '__main__':app.run(debug=True,port=15000)
How to solve this issue? or do I have to change port with every application update?
This code test.py
doesn't change port that's specified in .run()
args:
from flask import Flask app = Flask(__name__)@app.route("/")
def index():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/2017 17: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.