我不确定这是否是特定的Flask,但当我在dev模式下运行应用程序(http://localhost:5000)时,我无法从网络上的其他机器访问它(使用http://[dev-host-ip]:5000)。例如,当Rails处于开发模式时,它工作得很好。我找不到任何关于Flask开发服务器配置的文档。你知道应该配置什么来实现这个功能吗?
当前回答
虽然这是可能的,但您不应该在生产中使用Flask开发服务器。Flask开发服务器的设计并不是特别安全、稳定或高效。有关正确的解决方案,请参阅部署文档。
flask run的——host选项或app.run()的host参数控制开发服务器侦听的地址。默认情况下,它运行在localhost上,将其更改为flask run——host=0.0.0.0(或app.run(host="0.0.0.0"))以运行在您机器的所有IP地址上。
0.0.0.0是一个不能直接在浏览器中使用的特殊值,您需要在网络中导航到机器的实际IP地址。您可能还需要调整防火墙以允许外部访问该端口。
Flask快速入门文档在“外部可见服务器”部分解释了这一点:
If you run the server you will notice that the server is only accessible from your own computer, not from any other in the network. This is the default because in debugging mode a user of the application can execute arbitrary Python code on your computer. If you have the debugger disabled or trust the users on your network, you can make the server publicly available simply by adding --host=0.0.0.0 to the command line: $ flask run --host=0.0.0.0 This tells your operating system to listen on all public IPs.
其他回答
我也有同样的问题,我使用PyCharm作为编辑器,当我创建项目时,PyCharm创建了一个Flask服务器。我所做的就是用Python创建一个服务器,方法如下:
基本上我所做的就是创建一个新的服务器,如果不是python的话,就是flask
我希望这对你有所帮助
虽然这是可能的,但您不应该在生产中使用Flask开发服务器。Flask开发服务器的设计并不是特别安全、稳定或高效。有关正确的解决方案,请参阅部署文档。
flask run的——host选项或app.run()的host参数控制开发服务器侦听的地址。默认情况下,它运行在localhost上,将其更改为flask run——host=0.0.0.0(或app.run(host="0.0.0.0"))以运行在您机器的所有IP地址上。
0.0.0.0是一个不能直接在浏览器中使用的特殊值,您需要在网络中导航到机器的实际IP地址。您可能还需要调整防火墙以允许外部访问该端口。
Flask快速入门文档在“外部可见服务器”部分解释了这一点:
If you run the server you will notice that the server is only accessible from your own computer, not from any other in the network. This is the default because in debugging mode a user of the application can execute arbitrary Python code on your computer. If you have the debugger disabled or trust the users on your network, you can make the server publicly available simply by adding --host=0.0.0.0 to the command line: $ flask run --host=0.0.0.0 This tells your operating system to listen on all public IPs.
如果以上解决方案都不起作用,请尝试手动在url的开头添加“http://”。
Chrome可以从搜索查询中区分“[ip-address]:5000”。但有时候,这种方式会起作用一段时间,然后就停止了联系,似乎我什么都没改变。我的假设是浏览器有时可能会自动在https://前加上前缀(它不应该这样,但这在我的例子中解决了这个问题)。
如果你的酷应用程序从外部文件加载了它的配置,就像下面的例子,那么不要忘记用HOST="0.0.0.0"更新相应的配置文件
cool.app.run(
host=cool.app.config.get("HOST", "localhost"),
port=cool.app.config.get("PORT", 9000)
)
这最终对我有用。
import os
然后把它放在你的python app.py或主文件的末尾。
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象