使用 Gunicorn + Nginx 部署 FastApi 项目实战
项目比较简单,登录、注册生成token,redis设置有效期保存,后续操作依赖headers中的token进行认证
项目目录
api目录 接口
conf目录 配置
public目录 异常类、字段验证、token生成
sql_app目录 数据库操作
dependencies.py token验证
gunicorn.py gunicorn配置文件
main.py 项目主文件
使用UUID
import uuid def get_id(): return uuid.uuid4().hex
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, Text, DateTime from sqlalchemy.orm import relationship from datetime import datetime from sql_app.database import Base from public.public import get_id class User(Base): __tablename__ = "users" id = Column(String(32), default=get_id, primary_key=True, index=True) # 使用uuid name = Column(String(20), index=True) zh_name = Column(String(20), default=None) email = Column(String(50), default=None) hashed_password = Column(String(100)) is_active = Column(Boolean, default=True) is_superuser = Column(Boolean, default=False) is_delete = Column(Boolean, default=False) description = Column(Text, default=None) last_login = Column(DateTime, default=datetime.now, onupdate=datetime.now) create_date = Column(DateTime, default=datetime.now) project = relationship("Project", back_populates="users")
relationship查询
class Project(Base): __tablename__ = "project" id = Column(String(32), default=get_id, primary_key=True, index=True) name = Column(String(20), index=True) description = Column(Text, default=None) is_delete = Column(Boolean, default=False) update_date = Column(DateTime, default=datetime.now, onupdate=datetime.now) create_date = Column(DateTime, default=datetime.now) users_id = Column(String(32), ForeignKey("users.id")) # 设置外键 sign_id = Column(String(32), ForeignKey("sign.id")) sign = relationship("Sign", back_populates="project") users = relationship("User", back_populates="project") # relationship 关联
效果
redis
from aioredis import Redis, create_redis_pool # aioredis 版本需要是1.3.1,不能为2.0以上 async def get_redis_pool() -> Redis: redis = await create_redis_pool(f"redis://:@127.0.0.1:6379/0", encoding="utf-8") return redis @app.on_event("startup") async def startup_event(): app.state.redis = await get_redis_pool() @app.on_event("shutdown") async def shutdown_event(): app.state.redis.close() await app.state.redis.wait_closed()
部署到服务器
1.阿里云和宝塔开放使用端口
2.Gunicorn 启动命令:gunicorn -c gunicorn.py main:app -k uvicorn.workers.UvicornWorker
3.配置Nginx
PostMan请求
愿你走出半生,归来仍是少年!