Skip to content

用 NGINX 在你自己的服务器上托管 Flet 应用。

AWS、Oracle、Linode 等提供了免费和廉价的云服务器套餐。

配置 Flet 环境 ​

requirements.txt 与 virtualenv ​

创建 requirements.txt,列出应用的依赖。最少应包含 flet 模块:

txt
flet

创建虚拟环境并安装依赖:

python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

Flet 应用示例 ​

python
import flet as ft

def main(page: ft.Page):
    page.title = "My Flet app"
    page.add(ft.Text("Hello, world!"))

if __name__ == "__main__":
    ft.run(main)

Flet 应用将从根 URL 提供服务,但你可以通过配置 FLET_WEB_APP_PATH 环境变量,让它服务于根路径之下,例如 /apps/myapp。

默认情况下,Flet Web 应用运行在端口 8000 上,但你可以通过设置 FLET_SERVER_PORT 环境变量来更改。

Web 应用支持的环境变量完整列表。

自动启动 Flet 应用 ​

创建 systemd 单元文件 ​

使用 systemd 服务单元文件 flet.service 来自动启动 Flet 应用。

下面的配置假设你的 Flet 应用脚本定义在 $HOME/flet-app/main.py。请根据你的实际情况替换 User、Group、WorkingDirectory 等。

ini
[Unit]
Description=Flet App
After=network.target

[Service]
User=ubuntu
Group=ubuntu
WorkingDirectory=/home/ubuntu/flet-app
Environment="PATH=/home/ubuntu/flet-app/.venv/bin"
ExecStart=/home/ubuntu/flet-app/.venv/bin/python /home/ubuntu/flet-app/main.py

[Install]
WantedBy=multi-user.target

启用 Flet 应用服务 ​

cd /etc/systemd/system
sudo ln -s /home/ubuntu/flet-app/flet.service
sudo systemctl start flet
sudo systemctl enable flet
sudo systemctl status flet

NGINX 代理配置 ​

NGINX 将代理 Flet 应用和 websocket。

在你的 /etc/nginx/sites-available/* 配置文件中,按需更新路径和端口:

txt
    location / {
        proxy_pass         http://127.0.0.1:8000/;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection keep-alive;
        proxy_set_header   Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }

    location /ws {
        proxy_pass         http://127.0.0.1:8000/ws;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection "upgrade";
        proxy_set_header   Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }

完成!重启 NGINX,然后在浏览器中打开你的应用。


关注我,学习大模型、大数据、Python等热门技术。