FastAPI

一个现代的高性能 Python Web 框架,用于构建带类型提示的 API。

1. 连接到您的服务器

使用SSH连接到服务器:

ssh root@<server-ip>

2. 访问登录凭据

已创建名为 fastapi 的专用用户来管理您的应用程序。

您可以在该文件中找到登录凭据: /root/.fastapi-creds

要查看它们,请运行:

cat /root/.fastapi-creds

若需更改密码,请使用:

passwd fastapi

3. 切换至应用用户

切换到 fastapi 用户账户来管理您的应用:

su - flask

此账户包含您的FastAPI项目和环境。

4. 项目结构

以下是默认目录结构:

/home/fastapi/fastapi_app/
├── main.py          → Your main FastAPI application file
├── venv/            → Virtual environment
└── __pycache__/     → Compiled Python files (auto-generated)

5. 管理您的申请

导航至应用程序目录:

cd ~/fastapi_app

激活虚拟环境:

source venv/bin/activate

编辑主应用程序文件:

nano main.py

重启 FastAPI 服务以应用更改:

sudo systemctl restart uvicorn-fastapi

6. 查看日志

您可以通过以下方式查看Uvicorn和Nginx的日志:

  • 独角兽日志: /var/log/uvicorn/
  • Nginx 错误日志: /var/log/nginx/error.log
  • Nginx访问日志: /var/log/nginx/access.log

要查看它们:

sudo tail -f /var/log/uvicorn/*

7. 访问您的API

服务启动后,您可在浏览器中通过以下地址访问您的 FastAPI 应用: http://<server-ip>

Nginx 会自动将 HTTP 请求转发至运行 FastAPI 应用的 Uvicorn 套接字。

8. 更改域名或端口

若需更新服务器名称、端口或域名:

  1. 编辑 Nginx 站点配置: sudo nano /etc/nginx/sites-available/uvicorn-fastapi
  2. 测试配置: sudo nginx -t
  3. 重新加载 Nginx: sudo systemctl restart nginx

9. Uvicorn 服务

FastAPI 应用程序通过名为 uvicorn-fastapi 的 systemd 服务运行。

它使用 /home/fastapi/fastapi_app/main:app 作为应用程序的入口点,并在失败时自动重启。

管理服务:

systemctl status uvicorn-fastapi
systemctl restart uvicorn-fastapi

要编辑该服务:

sudo vim /etc/systemd/system/uvicorn-fastapi.service
sudo systemctl daemon-reload
sudo systemctl restart uvicorn-fastapi
sudo systemctl status uvicorn-fastapi

10. 启用 HTTPS(可选)

使用Certbot启用HTTPS。

申请详情