Python 为什么我不能更改运行 Flask 应用程序的主机和端口?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41940663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why can't I change the host and port that my Flask app runs on?
提问by Marco Cutecchia
I want to change the host and port that my app runs on. I set hostand portin app.run, but the flask runcommand still runs on the default 127.0.0.1:8000. How can I change the host and port that the flaskcommand uses?
我想更改运行我的应用程序的主机和端口。我设置host并port输入app.run,但该flask run命令仍然在默认127.0.0.1:8000. 如何更改flask命令使用的主机和端口?
if __name__ == '__main__':
app.run(host='0.0.0.0', port=3000)
set FLASK_APP=onlinegame
set FLASK_DEBUG=true
python -m flask run
回答by davidism
The flaskcommand is separate from the flask.runmethod. It doesn't see the app or its configuration. To change the host and port, pass them as options to the command.
的flask命令是从所述分离的flask.run方法。它看不到应用程序或其配置。要更改主机和端口,请将它们作为选项传递给命令。
flask run -h localhost -p 3000
Pass --helpfor the full list of options.
传递--help完整的选项列表。
Setting the SERVER_NAMEconfig will not affect the command either, as the command can't see the app's config.
设置SERVER_NAME配置也不会影响命令,因为命令看不到应用程序的配置。
Neverexpose the dev server to the outside (such as binding to 0.0.0.0). Use a production WSGI server such as uWSGI or Gunicorn.
永远不要将开发服务器暴露给外部(例如绑定到0.0.0.0)。使用生产 WSGI 服务器,例如 uWSGI 或 Gunicorn。
gunicorn -w 2 -b 0.0.0.0:3000 myapp:app
回答by G?khan Gerdan
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == '__main__':
app.run(host="localhost", port=8000, debug=True)
Configure host and port like this in the script and run it with
在脚本中像这样配置主机和端口并运行它
python app.py
回答by Akronix
You can also use the environment variable FLASK_RUN_PORT, for instance:
您还可以使用环境变量FLASK_RUN_PORT,例如:
export FLASK_RUN_PORT=8000
flask run
* Running on http://127.0.0.1:8000/
Source: The Flask docs.
来源:Flask 文档。
回答by TeknasVaruas
When you run the application server using the flask runcommand, the __name__of the module is not "__main__". So the ifblock in your code is not executed -- hence the server is not getting bound to 0.0.0.0, as you expect.
当您使用该flask run命令运行应用程序服务器__name__时,模块的 不是"__main__"。所以if你的代码中的块没有被执行——因此服务器没有0.0.0.0像你期望的那样绑定到。
For using this command, you can bind a custom host using the --hostflag.
要使用此命令,您可以使用--host标志绑定自定义主机。
flask run --host=0.0.0.0
回答by Станислав Немытов
You also can use it:
你也可以使用它:
if __name__ == "__main__":
app.run(host='127.0.0.1', port=5002)
and then in the console use it
然后在控制台中使用它
set FLASK_ENV=development
python app.py

