port management in python/flask application

前提是你 提交于 2019-12-13 08:32:39

问题


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 os

app = 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?


回答1:


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.



来源:https://stackoverflow.com/questions/47393479/port-management-in-python-flask-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!