您的位置:首页 > 房产 > 家装 > 手机怎么做图纸设计_网页设计素材分析_深圳关键词首页排名_站长网站大全

手机怎么做图纸设计_网页设计素材分析_深圳关键词首页排名_站长网站大全

2025/1/11 17:54:24 来源:https://blog.csdn.net/cxl0406/article/details/144252017  浏览:    关键词:手机怎么做图纸设计_网页设计素材分析_深圳关键词首页排名_站长网站大全
手机怎么做图纸设计_网页设计素材分析_深圳关键词首页排名_站长网站大全

1. 创建项目结构

首先,设计一个合理的项目结构。这里以三个Apps为例:users、items 和 orders。

2. 项目结构

my_fastapi_project/
├── main.py
├── app/
│   ├── __init__.py
│   ├── users/
│   │   ├── __init__.py
│   │   ├── models.py
│   │   ├── schemas.py
│   │   ├── crud.py
│   │   └── routes.py
│   ├── items/
│   │   ├── __init__.py
│   │   ├── models.py
│   │   ├── schemas.py
│   │   ├── crud.py
│   │   └── routes.py
│   ├── orders/
│   │   ├── __init__.py
│   │   ├── models.py
│   │   ├── schemas.py
│   │   ├── crud.py
│   │   └── routes.py
├── database.py
└── config.py

3. 配置数据库连接 (database.py)

from databases import Database
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, MetaDataDATABASE_URL = "sqlite:///./test.db"  # 使用SQLite作为示例数据库# 初始化数据库连接
database = Database(DATABASE_URL)
metadata = MetaData()
engine = create_engine(DATABASE_URL)Base = declarative_base()async def init_db():async with engine.begin() as conn:await conn.run_sync(Base.metadata.create_all)# 在实际部署中应更加谨慎地处理这一点
import asyncio
asyncio.run(init_db())

4. 定义配置 (config.py)

class Settings:openai_api_key: str = "your-openai-api-key"# 其他配置项...settings = Settings()

5. 每个App的具体实现

app/users/models.py - 用户模型定义

from sqlalchemy import Column, Integer, String
from ..database import Baseclass User(Base):__tablename__ = "users"id = Column(Integer, primary_key=True, index=True)username = Column(String, unique=True, index=True)email = Column(String, unique=True, index=True)

6. app/users/schemas.py - 用户Pydantic模式定义

from pydantic import BaseModelclass UserCreate(BaseModel):username: stremail: strclass UserSchema(UserCreate):id: intclass Config:orm_mode = True

7. app/users/crud.py - 用户CRUD操作

from sqlalchemy.orm import Session
from .models import User as UserModel
from .schemas import UserCreateasync def get_user(db: Session, user_id: int):return db.query(UserModel).filter(UserModel.id == user_id).first()async def create_user(db: Session, user: UserCreate):db_user = UserModel(**user.dict())db.add(db_user)await db.commit()await db.refresh(db_user)return db_user

8. app/users/routes.py - 用户路由定义

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from ..database import get_db_session
from .crud import get_user, create_user
from .schemas import UserCreate, UserSchemarouter = APIRouter()@router.get("/users/{user_id}", response_model=UserSchema)
async def read_user(user_id: int, db: Session = Depends(get_db_session)):db_user = await get_user(db, user_id=user_id)if db_user is None:raise HTTPException(status_code=404, detail="User not found")return db_user@router.post("/users/", response_model=UserSchema)
async def create_new_user(user: UserCreate, db: Session = Depends(get_db_session)):return await create_user(db=db, user=user)

9. 将所有路由注册到主应用 (main.py)

from fastapi import FastAPI
from app.users.routes import router as users_router
from app.items.routes import router as items_router
from app.orders.routes import router as orders_router
from database import databaseapp = FastAPI()# 包含来自不同Apps的路由
app.include_router(users_router, prefix="/users", tags=["users"])
app.include_router(items_router, prefix="/items", tags=["items"])
app.include_router(orders_router, prefix="/orders", tags=["orders"])@app.on_event("startup")
async def startup():await database.connect()@app.on_event("shutdown")
async def shutdown():await database.disconnect()

9. 启动应用程序

使用uvicorn启动应用程序:

uvicorn main:app --reload

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com