配置 Flask 开发服务器在网络上可见

发布于 2024-11-29 04:26:20 字数 208 浏览 1 评论 0原文

我不确定这是否是 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

心病无药医 2024-12-06 04:26:20

虽然这是可能的,但您不应该在生产中使用 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 快速入门文档在“外部可见服务器”部分对此进行了解释:

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

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

$flask 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.


The --host option to flask run, or the host parameter to app.run(), controls what address the development server listens to. By default it runs on localhost, change it to flask run --host=0.0.0.0 (or app.run(host="0.0.0.0")) to run on all your machine's IP addresses.

0.0.0.0 is a special value that you can't use in the browser directly, you'll need to navigate to the actual IP address of the machine on the network. You may also need to adjust your firewall to allow external access to the port.

The Flask quickstart docs explain this in the "Externally Visible Server" section:

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.

最终幸福 2024-12-06 04:26:20

如果您使用 flask 可执行文件启动服务器,请使用 flask run --host=0.0.0.0 更改默认值 127.0.0.1 并将其打开为非本地连接。

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

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

$flask run --host=0.0.0.0

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

参考:https://flask.palletsprojects.com/quickstart/

If you use the flask executable to start your server, 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.

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: https://flask.palletsprojects.com/quickstart/

夕色琉璃 2024-12-06 04:26:20

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

东西

无聊的 -服务器。我尝试了 0.0.0.0 方法,但没有成功。然后我尝试更改端口,但没有成功。因此,在尝试了一堆不同的组合之后,我找到了这个,它解决了我在本地服务器上部署应用程序的问题。

步骤

  1. 获取计算机的本地 IPv4 地址。
    这可以通过在 Windows 上输入 ipconfig 和在 Linux 上输入 ifconfig 来完成
    和麦克。

IPv4 (Windows )

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

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

    flask run -h 192.168.XX

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

    flask run -h 192.168.1.100

运行 Flask 应用

在我的移动设备上

< img src="https://i.sstatic.net/lGGYG.jpg" alt="我的手机屏幕截图">

可选内容

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

就是这样。如果您觉得这有帮助,请点赞。

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 gets 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 extension (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 shellcode in getIP.ps1.

Cool.????

追星践月 2024-12-06 04:26:20

host='0.0.0.0' 添加到app.run`。

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

如果您在 Windows 上收到 OSError: [WinError 10013] An attempts to access a socket in a way by其访问权限禁止的方式,则您可能没有使用该端口的权限,或者有其他原因正在使用它,您可以通过 netstat -na|findstr 5000 找到它。

Add host='0.0.0.0' toapp.run`.

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

If you get OSError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions on Windows, you either don't have permission to use the port, or something else is using it which you can find with netstat -na|findstr 5000.

如果没有 2024-12-06 04:26:20

检查服务器上是否打开特定端口来为客户端提供服务?

在 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
相权↑美人 2024-12-06 04:26:20

如果您的 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)
)            
埋葬我深情 2024-12-06 04:26:20

如果您在访问使用 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

乖乖兔^ω^ 2024-12-06 04:26:20

您还可以通过环境变量设置主机(将其公开在面向 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:8000/ (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:8000/ (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?

怪我鬧 2024-12-06 04:26:20

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

set FLASK_APP=ABC.py

SET FLASK_ENV=development

Flask run -h [yourIP] -p 8080

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

  • 服务Flask 应用程序“expirement.py”(延迟加载)
    • 环境:发展
    • 调试模式:开启
    • 使用 stat 重新启动
    • 调试器已激活!
    • 调试器 PIN:199-519-700
    • 正在 http://[yourIP]:8080/ 上运行(按 CTRL+C 退出)< /里>

现在您可以使用 http://[yourIP]:8080/ 网址

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

风情万种。 2024-12-06 04:26:20

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

  1. 只需在命令提示符下使用 ipconfig 获取您的 ipv4 地址
  2. 转到存在 Flask 代码的文件
  3. 在主函数中 write app.run(host= 'your ipv4 address')

<强>例如:

在此处输入图像描述

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

逐鹿 2024-12-06 04:26:20

在项目根目录中创建文件.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

睡美人的小仙女 2024-12-06 04:26:20

这个答案不仅与 Flask 有关,而且应该适用于所有无法从另一个主机连接服务问题。

  1. 使用netstat -ano | grep查看地址是否为 0.0.0.0 或 ::。如果是 127.0.0.1 那么它仅用于本地请求。
  2. 使用 tcpdump 查看是否有数据包丢失。如果明显不平衡,可以通过iptables检查路由规则。

今天我像往常一样运行我的 Flask 应用程序,但我注意到它无法从其他服务器连接。然后我运行 netstat -ano | grep,本地地址是 ::0.0.0.0 (我都尝试过,我知道 127.0.0.1 只允许来自本地主机)。然后我使用telnet主机端口,结果就像connect to ...。这很奇怪。然后我想我最好用 tcpdump -i any port检查一下。 -w w.pcap。我注意到它都是这样的:

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

然后通过检查 iptables --list OUTPUT 部分,我可以看到几个规则:

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.

橪书 2024-12-06 04:26:20

这终于对我有用了。

import os

然后将其放在 python app.py 或主文件的末尾。

if __name__ == "__main__":
    port = int(os.environ.get("PORT", 5000))
    app.run(host='0.0.0.0', port=port)

This finally worked for me.

import os

Then place this at the end of your python app.py or main file.

if __name__ == "__main__":
    port = int(os.environ.get("PORT", 5000))
    app.run(host='0.0.0.0', port=port)
清旖 2024-12-06 04:26:20

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

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

我希望它可以帮助你

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

星星的軌跡 2024-12-06 04:26:20

就我而言,问题是 Windows 防火墙,只需“测试时”禁用它即可。
输入图片此处描述
这不是最佳方法,但如果您在部署到安全服务器之前进行测试,那么它可能适合您。

另外,我将附加 Flask 最小服务器进行测试:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "<p>Hello, World 2!</p>"


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

In my case the problem was the windows firewall, just disable it "while testing".
enter image description here
It's not the optimal way but if you are testing before deploying on a secure server, it could work for you.

Also I'll attach the flask minimal server to test:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "<p>Hello, World 2!</p>"


if __name__ == '__main__':
    app.run(host="0.0.0.0",debug=True,port=9600)
红墙和绿瓦 2024-12-06 04:26:20

转到项目路径
设置 FLASK_APP=ABC.py
SET FLASK_ENV=开发

烧瓶运行 -h [yourIP] -p 8080
您将在 CMD 上关注 o/p:-
* 服务 Flask 应用程序“expirement.py”(延迟加载)
* 环境:发展
* 调试模式:开
* 重新启动统计
* 调试器已激活!
* 调试器 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)

花海 2024-12-06 04:26:20

如果您需要从外部网络测试您的应用。
只需使用 ngrok.com 将其提供给整个互联网
这将像开发服务器一样部署它,但很快就在本地部署,节省了我很多时间,不,我与该公司没有关系:)

只需确保更改烧瓶应用程序中的端口:
app.run(host='0.0.0.0', port=80)

In case you need to test your app from an external network.
Simply serve it to the whole Internet with ngrok.com
which will deploy it like a dev server but in no time and locally, saved me a lot of time, and no, I'm not related to that company :)

Just make sure to change the port in your flask app:
app.run(host='0.0.0.0', port=80)

一向肩并 2024-12-06 04:26:20

如果上述解决方案均不起作用,请尝试手动将“http://”添加到网址开头。

Chrome 可以区分搜索查询中的“[ip-address]:5000”。但有时它会工作一段时间,然后停止连接,似乎我没有改变任何东西。我的假设是,浏览器有时可能会自动在前面添加 https:// (它不应该,但这在我的情况下修复了它)。

If none of the above solutions are working, try manually adding "http://" to the beginning of the url.

Chrome can distinguish "[ip-address]:5000" from a search query. But sometimes that works for a while, and then stops connecting, seemingly without me changing anything. My hypothesis is that the browser might sometimes automatically prepend https:// (which it shouldn't, but this fixed it in my case).

ˇ宁静的妩媚 2024-12-06 04:26:20

如果您在公共网络上,就像我一样,您必须关闭“阻止所有连接”

在此处输入图像描述

If you are on public Network As I was you have to turn off "block all connections"

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文