编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

部署 FastAPI 应用程序:为生产环境配置 FastAPI

wxchong 2024-11-10 12:16:31 开源技术 31 ℃ 0 评论

在生产环境中部署 FastAPI 应用程序涉及几个步骤,以确保您的应用程序可靠、安全且性能良好。本博客将指导您完成为生产配置 FastAPI 的过程,包括设置生产服务器、配置环境变量和使用反向代理。我们还将提供演示来说明每个步骤。

步骤 1:设置生产服务器

部署 FastAPI 应用程序的第一步是设置生产服务器。运行 FastAPI 应用程序最受欢迎的选择之一是 Uvicorn,这是一种 ASGI 服务器实现。为了获得更好的性能,您可以将 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 worker 来运行 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 设置 Let's Encrypt

安装 Certbot 和 Nginx 插件:

sudo apt install certbot python3-certbot-nginx

获取并安装证书:

sudo certbot --nginx -d your_domain.com

Certbot 将自动更新您的 Nginx 配置以使用 SSL/TLS。您可以在 /etc/nginx/sites-available/fastapi 中查看配置。

这里还有一些其他演示,重点介绍为生产配置 FastAPI 的其他重要方面:

演示 1:设置日志记录

正确的日志记录对于监控应用程序的性能和诊断问题至关重要。FastAPI 允许您自定义日志记录配置。

演示:配置日志记录

创建一个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  # Ensure this import executes the logging configuration


app = FastAPI()


@app.get("/")
def read_root():
    app.logger.info("Root endpoint called")
    return {"message": "Hello, World!"}

演示 2:使用中间件提高安全性

中间件可用于通过向响应添加标头、处理 CORS 等方式增强 FastAPI 应用程序的安全性。

演示:添加安全标头

创建一个 middleware.py 文件:

from starlette.middleware.base import BaseHTTPMiddleware
from starlette.types import ASGIApp, Receive, Scope, Send


class SecurityHeadersMiddleware(BaseHTTPMiddleware):
    def __init__(self, app: ASGIApp):
        super().__init__(app)


    async def dispatch(self, request: Scope, 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

如果您的 FastAPI 应用程序需要处理来自不同来源的请求,则应配置跨源资源共享 (CORS)。

演示:配置 CORS

安装 fastapi-cors:

pip install fastapi-cors

更新 main.py 以配置 CORS:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware


app = FastAPI()


origins = [
    "http://localhost",
    "http://localhost:8000",
    "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:

pip install slowapi

创建一个 rate_limit.py 文件:

from slowapi import Limiter
from slowapi.util import get_remote_address


limiter = Limiter(key_func=get_remote_address)
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:使用任务队列执行后台作业

要处理后台任务,您可以使用带有 FastAPI 的 Celery 等任务队列。

演示:集成 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 应用程序已准备好投入生产,为您的用户提供可靠且安全的体验。除了设置服务器和反向代理之外,为生产环境配置 FastAPI 还涉及几个重要步骤。通过实施适当的日志记录、使用中间件确保安全、配置 CORS、添加速率限制和集成任务队列,您可以确保您的 FastAPI 应用程序安全、高效且可扩展。这些额外的演示提供了一种全面的方法,可帮助您为生产环境准备 FastAPI 应用程序。

写在最后:

  1. 生产环境和测试环境,最大的区别就是:测试环境面向内部,用户都是软件工程流程内的人,包括开发,测试,运维以及产品等,区别于生产环境面向客户。所以,在系统配置(硬件)、稳定性和安全等方面两套环境有很大的差异,生产环境如上所述,融入了很多稳定、安全等设置。特别是安全,博文中例子只是冰山一角,如之前博文所述,大多数公司其实是有安全团队做整体安全的把控的,代码质量或者安全配置只是其中的一小部分而已
  2. 本期博文主题:产线环境设置。还有一个大概念,我们未提及,就是合规。由于生产环境是面向客户,所以会产生大量的客户数据,按照法律法规要求这部分数据也是要做安全处理的,如:脱敏,加密防泄漏等,以后有机会,可以做个专栏,和大家共同探讨,当然,大家感兴趣的话,也可以自行查询相关资料

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表