2011-08-11 41 views
220

我不確定這是否是Flask特定的,但是當我在dev模式下運行應用程序時(http://localhost:5000),我無法從網絡上的其他計算機訪問它(使用http://[dev-host-ip]:5000 )。例如,在Rails模式下,它可以正常工作。我找不到關於Flask dev服務器配置的任何文檔。任何想法應該配置什麼來啓用它?將Flask dev服務器配置爲在網絡上可見

回答

385

雖然這是可能的,但您不應該在生產中使用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

10

如果您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

-1

添加到@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

31

如果使用燒瓶可執行文件來啓動服務器,您可以使用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

2

添加以下行到您的項目

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'。 –

相關問題