将 Python 项目加密打包后的.whl 文件部署到 Linux 服务器
第一部分:在本地打包 .whl 文件(适用于 Linux)
- 1 项目结构(示例)
- 2 使用 Cython 加密并生成 .so 文件(window下为.pyd文件)
pip install cython setuptools wheel
python3 setup.py bdist_wheel
- 3 得到类似文件:
dist/fdqa-0.1.0-cp38-cp38-linux_x86_64.whl
第二部分:上传并部署 .whl 到服务器
2.1 上传 .whl 文件(用 scp 或 Xftp)
scp dist/fdqa-*.whl lung@your_server:/home/lung/
2.2 登录服务器并准备环境
ssh lung@your_server
cd /home/lung
sudo apt update
sudo apt install python3.8 python3.8-venv
python3.8 -m venv venv
source venv/bin/activate
2.3 安装 .whl 包
pip install ./fdqa-0.1.0-cp38-cp38-linux_x86_64.whl
第三部分:运行你的 FastAPI 项目
3.1 创建启动脚本 run_server.py
from fdqa import api_server # 你封装的包里必须包含 api_server.py
if __name__ == '__main__':
import uvicorn
uvicorn.run(api_server.app, host='0.0.0.0', port=9514)
3.2 启动服务
python run_server.py
第四部分:Nginx + HTTPS 反向代理部署
4.1 安装 Nginx 和 Certbot
sudo apt install nginx certbot python3-certbot-nginx
4.2 设置 Nginx 配置文件
创建 /etc/nginx/sites-available/fdqa_ssl
server {
listen 443 ssl;
server_name yourdomain.com;
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
location / {
proxy_pass http://127.0.0.1:9514;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
server {
listen 80;
server_name yourdomain.com;
return 301 https://$host$request_uri;
}
4.3 启用配置并申请 HTTPS
sudo ln -s /etc/nginx/sites-available/fdqa_ssl /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx
sudo certbot --nginx -d yourdomain.com