部署 FastAPI 应用程序:为生产环境配置 FastAPI
在生产环境中部署 FastAPI 应用程序需要确保应用程序的可靠性、安全性和性能。本篇博文将带你一步步配置 FastAPI 应用程序的生产环境,从设置生产服务器、管理环境变量到使用反向代理和 SSL/TLS 加密。我们还提供了每个步骤的实际演示,帮助你快速上手。
步骤 1:设置生产服务器
在生产环境中,FastAPI 最常使用的 ASGI 服务器是 Uvicorn,为进一步提高性能,你可以使用 Gunicorn 和 Uvicorn 工作器来运行应用程序。
演示:使用 Uvicorn 和 Gunicorn 运行 FastAPI
安装 Uvicorn 和 Gunicorn:
pip install uvicorn gunicorn
创建 gunicorn.conf.py
配置文件:
import multiprocessing
workers = multiprocessing.cpu_count() * 2 + 1
bind = "0.0.0.0:8000"
worker_class = "uvicorn.workers.UvicornWorker"
使用 Gunicorn 运行 FastAPI 应用:
gunicorn -c gunicorn.conf.py myapp:app
此命令配置了 Gunicorn 使用 Uvicorn 的工作器来运行 FastAPI 应用程序。
步骤 2:配置环境变量
环境变量有助于管理应用程序中的敏感信息,例如数据库凭据和 API 密钥。使用 .env
文件存储这些变量并使用 python-dotenv
包加载它们。
演示:使用环境变量
安装 python-dotenv
:
pip install python-dotenv
创建 .env
文件:
DATABASE_URL=postgresql://user:password@localhost/dbname
SECRET_KEY=your_secret_key
在 FastAPI 应用程序中加载环境变量:
from fastapi import FastAPI
from dotenv import load_dotenv
import os
load_dotenv()
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, World!"}
@app.get("/config")
def read_config():
return {
"database_url": os.getenv("DATABASE_URL"),
"secret_key": os.getenv("SECRET_KEY"),
}
步骤 3:使用反向代理
使用像 Nginx 这样的反向代理,可以提高 FastAPI 应用程序的性能和安全性。
演示:将 Nginx 配置为反向代理
安装 Nginx:
sudo apt update
sudo apt install nginx
为 FastAPI 应用程序创建 Nginx 配置文件:
server {
listen 80;
server_name your_domain.com;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
启用 Nginx 配置并重启服务:
sudo ln -s /etc/nginx/sites-available/fastapi /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
更新 Gunicorn 命令在本地主机上运行:
gunicorn -c gunicorn.conf.py -b 127.0.0.1:8000 myapp:app
步骤 4:设置 SSL/TLS
SSL/TLS 加密对于保护数据传输非常重要。你可以使用 Let's Encrypt 免费获取 SSL/TLS 证书。
演示:使用 Certbot 设置 SSL
安装 Certbot 和 Nginx 插件:
sudo apt install certbot python3-certbot-nginx
获取并安装证书:
sudo certbot --nginx -d your_domain.com
Certbot 会自动更新 Nginx 配置以使用 SSL/TLS。
其他生产配置演示
演示 1:设置日志记录
日志记录对于监控和调试应用程序非常重要。可以通过以下方式自定义日志配置:
创建 logging_config.py
文件:
import logging
import logging.config
LOGGING_CONFIG = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"default": {
"format": "[%(asctime)s] %(levelname)s in %(module)s: %(message)s",
},
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"formatter": "default",
},
},
"root": {
"level": "INFO",
"handlers": ["console"],
},
}
logging.config.dictConfig(LOGGING_CONFIG)
更新 main.py
使用日志记录配置:
from fastapi import FastAPI
import logging_config
app = FastAPI()
@app.get("/")
def read_root():
app.logger.info("Root endpoint called")
return {"message": "Hello, World!"}
演示 2:使用中间件提高安全性
中间件可以用于增加 HTTP 头,增强应用程序的安全性:
创建 middleware.py
文件:
from starlette.middleware.base import BaseHTTPMiddleware
class SecurityHeadersMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
response = await call_next(request)
response.headers['X-Content-Type-Options'] = 'nosniff'
response.headers['X-Frame-Options'] = 'DENY'
response.headers['X-XSS-Protection'] = '1; mode=block'
return response
更新 main.py
使用中间件:
from fastapi import FastAPI
from middleware import SecurityHeadersMiddleware
app = FastAPI()
app.add_middleware(SecurityHeadersMiddleware)
@app.get("/")
def read_root():
return {"message": "Hello, World!"}
演示 3:配置 CORS
为支持跨域请求,可以使用 CORS 中间件:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = [
"http://localhost",
"https://yourdomain.com",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
def read_root():
return {"message": "Hello, World!"}
演示 4:速率限制
使用 slowapi
实现速率限制:
安装 slowapi:
pip install slowapi
创建 rate_limit.py
文件:
from slowapi import Limiter
from slowapi.util import get_remote_address
limiter = Limiter(key_func=get_remote_address)
在 main.py
中使用速率限制:
from fastapi import FastAPI, Request
from slowapi.errors import RateLimitExceeded
from slowapi.extension import Limiter
from rate_limit import limiter
app = FastAPI()
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, lambda request, exc: {"message": "Rate limit exceeded"})
@app.get("/")
@limiter.limit("5/minute")
async def read_root(request: Request):
return {"message": "Hello, World!"}
演示 5:使用任务队列执行后台作业
使用 Celery 处理后台任务:
安装 Celery 和 Redis:
pip install celery redis
创建 celery_worker.py
:
from celery import Celery
celery_app = Celery(
'worker',
broker='redis://localhost:6379/0',
backend='redis://localhost:6379/0'
)
@celery_app.task
def add(x, y):
return x + y
在 main.py
中使用 Celery:
from fastapi import FastAPI, BackgroundTasks
from celery_worker import add
app = FastAPI()
@app.get("/add")
async def add_numbers(a: int, b: int, background_tasks: BackgroundTasks):
background_tasks.add_task(add, a, b)
return {"message": "Task added to queue"}
运行 Celery 工作器:
celery -A celery_worker.celery_app worker --loglevel=info
总结
生产环境的 FastAPI 部署涉及多个步骤,包括设置服务器、管理环境变量、配置反向代理、SSL/TLS 保护以及优化应用程序的安全性和性能。通过本文的演示,你可以为生产环境配置 FastAPI 应用,确保其在安全、可靠的环境中运行。