将Flask dev服务器配置为在网络上可见

问题描述:

我不确定这是否是Flask特定的,但是当我在dev模式下运行应用程序时(http://localhost:5000),我无法从网络上的其他计算机访问它(使用http://[dev-host-ip]:5000 )。例如,在Rails模式下,它可以正常工作。我找不到关于Flask dev服务器配置的任何文档。任何想法应该配置什么来启用它?将Flask dev服务器配置为在网络上可见

虽然这是可能的,但您不应该在生产中使用Flask dev服务器。 Flask dev服务器的设计不是特别安全,稳定或高效。有关正确的解决方案,请参阅deploying上的文档。


将参数添加到app.run()。默认情况下,它在本地主机上运行,​​将其更改为app.run(host= '0.0.0.0')以在您的机器IP地址上运行。

Quickstart page下的“外部可见的服务器”文件化在烧瓶网站:

Externally Visible Server

If you run the server you will notice that the server is only available 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 debug disabled or trust the users on your network, you can make the server publicly available.

Just change the call of the run() method to look like this:

app.run(host='0.0.0.0')

This tells your operating system to listen on a public IP.

+18

要设置一个特定的IP app.run(主机= “192.168.1.7”,端口= 5010)方便的,如果你的电脑有几个IP的 – lxx

如果您cool应用有它的配置从外部文件加载,就像下面这个例子,那么不要忘记用HOST =“0.0.0.0”更新相应的配置文件

cool.app.run(
    host=cool.app.config.get("HOST", "localhost"), 
    port=cool.app.config.get("PORT", 9000) 
)    
+1

这是一个很好的方式来同时存储烧瓶配置中的主机名和端口号。我一直在寻找这个解决方案。 – compie

添加到@Shawn的答案,还有一个内置配置变量SERVER_NAME。我们可以在app.config.from_pyfile(“config.py”)中指定的配置文件中将其设置为0.0.0.0。另请注意,这将覆盖app.run主机名。
参考:http://flask.pocoo.org/docs/0.10/config/

+6

如果你按照这个答案,你会把一个SERVER_NAME的条目放到你的配置文件中,得出结论:它不会做那些应该做的事,忘掉它,尝试接受的答案,并且在浪费你的时间之后,你会发现它在你从你的配置文件中删除SERVER_NAME时起作用,然后你会回到这里并且低估这个答案。 – gnebehay

如果使用烧瓶可执行文件来启动服务器,您可以使用flask run --host=0.0.0.0从127.0.0.1更改默认设置,打开它的非本地连接。其他答案描述的config和app.run方法可能是更好的做法,但这也可以很方便。

Externally Visible Server 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.

参考:http://flask.pocoo.org/docs/0.11/quickstart/

+1

我不知道是否有其他人经历过,但我根据QuickStart文档首先尝试了这种方法,但由于一些奇怪的原因,IP仍在'127.0.0.1'上运行(我正确设置了我的Flask可执行文件,它似乎,不知道我做错了什么)。然而,在将app.run(host ='0.0.0.0')'添加到我的服务器文件的另一个答案中后,我可以跨网络访问该页面。任何人都有类似我所描述的问题或有任何信息的问题? – natureminded

添加以下行到您的项目

if __name__ == '__main__': 
    app.debug = True 
    app.run(host = '0.0.0.0',port=5005) 
+0

我得到'OSError:[WinError 10013]试图通过其访问权限禁止访问套接字' – pyd

+0

**要修复方法**您需要以管理员身份运行python文件并检查任何端口都在windows上运行'netstat -na | findstr 5005'。 –