问题:将Flask开发服务器配置为在网络上可见

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

I’m not sure if this is Flask specific, but when I run an app in dev mode (http://localhost:5000), I cannot access it from other machines on the network (with http://[dev-host-ip]:5000). With Rails in dev mode, for example, it works fine. I couldn’t find any docs regarding the Flask dev server configuration. Any idea what should be configured to enable this?


回答 0

尽管这是可行的,但您不应在生产中使用Flask dev服务器。Flask开发服务器的设计并非特别安全,稳定或高效。有关正确的解决方案,请参阅有关部署的文档。


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

快速入门页上的“外部可见的服务器”下的Flask网站上记录

外部可见服务器

如果运行服务器,您会注意到该服务器仅可用于您自己的计算机,而不能用于网络中的任何其他服务器。这是默认设置,因为在调试模式下,应用程序的用户可以在计算机上执行任意Python代码。如果禁用了调试或信任网络上的用户,则可以使服务器公开可用。

只需将run()方法的调用更改为如下所示:

app.run(host='0.0.0.0')

这告诉您的操作系统侦听公共IP。

While this is possible, you should not use the Flask dev server in production. The Flask dev server is not designed to be particularly secure, stable, or efficient. See the docs on deploying for correct solutions.


Add a parameter to your app.run(). By default it runs on localhost, change it to app.run(host= '0.0.0.0') to run on your machines IP address.

Documented on the Flask site under “Externally Visible Server” on the 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.


回答 1

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

外部可见服务器如果运行服务器,您将注意到只能从您自己的计算机访问该服务器,而不能从网络中的任何其他服务器访问该服务器。这是默认设置,因为在调试模式下,应用程序的用户可以在计算机上执行任意Python代码。

如果禁用了调试器或信任网络上的用户,则只需在命令行中添加–host = 0.0.0.0,即可使服务器公开可用:

flask run –host = 0.0.0.0这告诉您的操作系统侦听所有公用IP。

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

If you use the flask executable to start your server, you can use flask run --host=0.0.0.0 to change the default from 127.0.0.1 and open it up to non local connections. The config and app.run methods that the other answers describe are probably better practice but this can be handy as well.

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.

Reference: http://flask.pocoo.org/docs/0.11/quickstart/


回答 2

如果0.0.0.0方法不起作用,请尝试此操作

无聊的东西

我亲自进行了很多努力,以使我的应用可以通过本地服务器访问其他设备(笔记本电脑和手机)。我尝试了0.0.0.0方法,但是没有运气。然后,我尝试更改端口,但没有成功。因此,在尝试了一堆不同的组合之后,我找到了这个组合,它解决了我在本地服务器上部署应用程序的问题。

脚步

  1. 获取计算机的本地IPv4地址。这可以通过ipconfig在Windows以及ifconfiglinux和Mac上键入来完成。

IPv4(Windows)

请注意:以上步骤将在提供该应用程序的计算机上执行,而不是在您正在访问该应用程序的计算机上执行。另请注意,如果断开连接并重新连接到网络,IPv4地址可能会更改。

  1. 现在,只需使用获取的IPv4地址运行flask应用程序即可。

    flask run -h 192.168.X.X

    例如,就我而言(参见图片),我将其运行为:

    flask run -h 192.168.1.100

运行烧瓶应用程序

在我的移动设备上

我手机的屏幕截图

可选的东西

如果您正在Windows上执行此过程,并使用Power Shell作为CLI,但仍然无法访问该网站,请在运行该应用程序的Shell中尝试使用CTRL + C命令。Power Shell有时会冻结,因此需要一点点恢复。这样做甚至可能终止服务器,但有时可以解决问题。

而已。如果您觉得有帮助,请竖起大拇指。😉

一些其他可选的东西

我创建了一个简短的Powershell脚本,可以在需要时为您提供IP地址:

$env:getIp = ipconfig
if ($env:getIp -match '(IPv4[\sa-zA-Z.]+:\s[0-9.]+)') {
    if ($matches[1] -match '([^a-z\s][\d]+[.\d]+)'){
        $ipv4 = $matches[1]
    }
}
echo $ipv4

将其保存到扩展名为.ps1的文件中(对于PowerShell),然后在启动您的应用程序之前对其运行。您可以将其保存在项目文件夹中,并以以下方式运行:

.\getIP.ps1; flask run -h $ipv4

注意:我将上面的shell代码保存在getIP.ps1中。

酷👌

Try this if the 0.0.0.0 method doesn’t work

Boring Stuff

I personally battled a lot to get my app accessible to other devices(laptops and mobile phones) through a local-server. I tried the 0.0.0.0 method, but no luck. Then I tried changing the port, but it just didn’t work. So, after trying a bunch of different combinations, I arrived to this one, and it solved my problem of deploying my app on a local-server.

Steps

  1. Get the local IPv4 address of your computer. This can be done by typing ipconfig on Windows and ifconfig on linux and Mac.

IPv4 (Windows)

Please note: The above step is to be performed on the machine you are serving the app on, and on not the machine on which you are accessing it. Also note, that the IPv4 address might change if you disconnect and reconnect to the network.

  1. Now, simply run the flask app with the acquired IPv4 address.

    flask run -h 192.168.X.X

    E.g. In my case (see the image), I ran it as:

    flask run -h 192.168.1.100

running the flask app

On my mobile device

screenshot from my mobile phone

Optional Stuff

If you are performing this procedure on Windows, and using Power Shell as the CLI, and you still aren’t able to access the website, try a CTRL + C command in the shell that’s running the app. Power Shell get frozen up sometimes and it needs a pinch to revive. Doing this might even terminate the server, but it sometimes does the trick.

That’s it. Give a thumbs up if you found this helpful.😉

Some more optional stuff

I have created a short Powershell script that will get you your IP address whenever you need one:

$env:getIp = ipconfig
if ($env:getIp -match '(IPv4[\sa-zA-Z.]+:\s[0-9.]+)') {
    if ($matches[1] -match '([^a-z\s][\d]+[.\d]+)'){
        $ipv4 = $matches[1]
    }
}
echo $ipv4

Save it to a file with .ps1 extenstion (for PowerShell), and run it on before starting your app. You can save it in your project folder and run it as:

.\getIP.ps1; flask run -h $ipv4

Note: I saved the above shell code in getIP.ps1.

Cool.👌


回答 3

如果您的cool应用程序的配置是从外部文件加载的,如以下示例所示,请不要忘记使用HOST =“ 0.0.0.0”更新相应的配置文件

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

If your cool app has it’s configuration loaded from an external file, like in the following example, then don’t forget to update the corresponding config file with HOST=”0.0.0.0″

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

回答 4

在您的项目中添加以下几行

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

Add below lines to your project

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

回答 5

检查服务器上是否打开了特定端口以服务于客户端?

在Ubuntu或Linux发行版中

sudo ufw enable
sudo ufw allow 5000/tcp //allow the server to handle the request on port 5000

配置应用程序以处理远程请求

app.run(host='0.0.0.0' , port=5000)


python3 app.py & #run application in background

Check whether the particular port is open on the server to serve the client or not?

in Ubuntu or Linux distro

sudo ufw enable
sudo ufw allow 5000/tcp //allow the server to handle the request on port 5000

Configure the application to handle remote requests

app.run(host='0.0.0.0' , port=5000)


python3 app.py & #run application in background

回答 6

转到CMD(命令提示符)上的项目路径,然后执行以下命令:

设置FLASK_APP = ABC.py

SET FLASK_ENV =开发

烧瓶运行-h [yourIP] -p 8080

您将在CMD上获得以下o / p:-

  • 正在投放Flask应用“ expirement.py”(延迟加载)

现在,您可以使用http:// [yourIP]:8080 / url 在另一台计算机上访问flask应用程序

Go to your project path on CMD(command Prompt) and execute the following command:-

set FLASK_APP=ABC.py

SET FLASK_ENV=development

flask run -h [yourIP] -p 8080

you will get following o/p on CMD:-

  • Serving Flask app “expirement.py” (lazy loading)
    • Environment: development
    • Debug mode: on
    • Restarting with stat
    • Debugger is active!
    • Debugger PIN: 199-519-700
    • Running on http://[yourIP]:8080/ (Press CTRL+C to quit)

Now you can access your flask app on another machine using http://[yourIP]:8080/ url


回答 7

如果您在访问使用PyCharm部署的Flask服务器时遇到问题,请考虑以下因素:

PyCharm不会直接运行您的主.py文件,因此if __name__ == '__main__':不会执行其中的任何代码,并且任何更改(例如app.run(host='0.0.0.0', port=5000))都不会生效。

相反,您应该使用“运行配置”配置Flask服务器,尤其是将其放置--host 0.0.0.0 --port 5000在“ 其他选项”字段中。

运行Flask服务器PyCharm的配置

有关在PyCharm中配置Flask服务器的更多信息

If you’re having troubles accessing your Flask server, deployed using PyCharm, take the following into account:

PyCharm doesn’t run your main .py file directly, so any code in if __name__ == '__main__': won’t be executed, and any changes (like app.run(host='0.0.0.0', port=5000)) won’t take effect.

Instead, you should configure the Flask server using Run Configurations, in particular, placing --host 0.0.0.0 --port 5000 into Additional options field.

Run cofigurations of Flask server PyCharm

More about configuring Flask server in PyCharm


回答 8

我遇到了同样的问题,我使用PyCharm作为编辑器,并且在创建项目时,PyCharm创建了Flask Server。我所做的就是通过以下方式用Python创建服务器;

配置Python服务器PyCharm 基本上我所做的是创建一个新服务器,但如果不是python,则使用flask

希望对您有帮助

I had the same problem, I use PyCharm as an editor and when I created the project, PyCharm created a Flask Server. What I did was create a server with Python in the following way;

Config Python Server PyCharm basically what I did was create a new server but flask if not python

I hope it helps you


回答 9

这个答案不仅与flask有关,而且应适用于所有无法连接来自另一个主机的服务

  1. 用于netstat -ano | grep <port>查看地址是0.0.0.0还是::。如果是127.0.0.1,则仅适用于本地请求。
  2. 使用tcpdump查看是否有任何数据包丢失。如果显示明显的不平衡,请通过iptables检查路由规则。

今天,我像往常一样运行烧瓶应用程序,但是我发现它无法从其他服务器连接。然后运行netstat -ano | grep <port>,本地地址为::or 0.0.0.0(我都尝试过,并且我知道127.0.0.1仅允许来自本地主机的连接)。然后我用了telnet host port,结果就像connect to ...。这很奇怪。然后我想我最好跟查一下tcpdump -i any port <port> -w w.pcap。我注意到这一切都是这样的:

tcpdump结果显示它只有来自远程主机的SYN数据包

然后通过检查iptables --listOUTPUT部分,我可以看到一些规则:

iptables列表结果

这些规则禁止握手时输出tcp重要数据包。通过删除它们,问题消失了。

This answer is not solely related with flask, but should be applicable for all cannot connect service from another host issue.

  1. use netstat -ano | grep <port> to see if the address is 0.0.0.0 or ::. If it is 127.0.0.1 then it is only for the local requests.
  2. use tcpdump to see if any packet is missing. If it shows obvious imbalance, check routing rules by iptables.

Today I run my flask app as usual, but I noticed it cannot connect from other server. Then I run netstat -ano | grep <port>, and the local address is :: or 0.0.0.0 (I tried both, and I know 127.0.0.1 only allows connection from the local host). Then I used telnet host port, the result is like connect to .... This is very odd. Then I thought I would better check it with tcpdump -i any port <port> -w w.pcap. And I noticed it is all like this:

tcpdump result shows it there is only SYN packets from remote host

Then by checking iptables --list OUTPUT section, I could see several rules:

iptables list result

these rules forbid output tcp vital packets in handshaking. By deleting them, the problem is gone.


回答 10

对我来说,我遵循上面的答案并对其进行了一些修改:

  1. 只需在命令提示符下使用ipconfig来获取您的ipv4地址
  2. 转到存在烧瓶代码的文件
  3. 在主函数中编写app.run(host =’您的ipv4地址’)

例如:

在此处输入图片说明

For me i followed the above answer and modified it a bit:

  1. Just grab your ipv4 address using ipconfig on command prompt
  2. Go to the file in which flask code is present
  3. In main function write app.run(host= ‘your ipv4 address’)

Eg:

enter image description here


回答 11

转到项目路径set FLASK_APP = ABC.py SET FLASK_ENV = development

flask run -h [yourIP] -p 8080,您将在CMD上遵循o / p:-*正在服务的Flask应用程序“ expirement.py”(延迟加载)*环境:开发*调试模式:on *以stat重新启动*调试器处于活动状态!*调试器PIN:199-519-700 *在http:// [yourIP]:8080 /上运行(按CTRL + C退出)

go to project path set FLASK_APP=ABC.py SET FLASK_ENV=development

flask run -h [yourIP] -p 8080 you will following o/p on CMD:- * Serving Flask app “expirement.py” (lazy loading) * Environment: development * Debug mode: on * Restarting with stat * Debugger is active! * Debugger PIN: 199-519-700 * Running on http://[yourIP]:8080/ (Press CTRL+C to quit)


回答 12

您还可以通过环境变量设置主机(将其暴露在面向IP地址的网络上)和端口。

$ export FLASK_APP=app.py
$ export FLASK_ENV=development
$ export FLASK_RUN_PORT=8000
$ export FLASK_RUN_HOST=0.0.0.0

$ flask run
 * Serving Flask app "app.py" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Running on https://0.0.0.0:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 329-665-000

请参见如何获取所有可用的命令选项来设置环境变量?

You can also set the host (to expose it on a network facing IP address) and port via environment variables.

$ export FLASK_APP=app.py
$ export FLASK_ENV=development
$ export FLASK_RUN_PORT=8000
$ export FLASK_RUN_HOST=0.0.0.0

$ flask run
 * Serving Flask app "app.py" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Running on https://0.0.0.0:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 329-665-000

See How to get all available Command Options to set environment variables?


回答 13

.flaskenv在项目根目录中创建文件。

该文件中的参数通常为:

FLASK_APP=app.py
FLASK_ENV=development
FLASK_RUN_HOST=[dev-host-ip]
FLASK_RUN_PORT=5000

如果您有虚拟环境,请激活它并执行pip install python-dotenv

该软件包将使用该.flaskenv文件,并且其中的声明将在终端会话之间自动导入。

那你可以做 flask run

Create file .flaskenv in the project root directory.

The parameters in this file are typically:

FLASK_APP=app.py
FLASK_ENV=development
FLASK_RUN_HOST=[dev-host-ip]
FLASK_RUN_PORT=5000

If you have a virtual environment, activate it and do a pip install python-dotenv .

This package is going to use the .flaskenv file, and declarations inside it will be automatically imported across terminal sessions.

Then you can do flask run


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。