使用 Gunicorn + Nginx 部署 FastApi 專案實戰
阿新 • • 發佈:2022-01-16
專案比較簡單,登入、註冊生成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 importBoolean, 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請求
願你走出半生,歸來仍是少年!