-
guest说:
我要做一个纯后端的API接口项目,学生信息管理,用的是FastAPI框架,使用的模块有sqlalchemy+pydantic+schemas+logging,请帮我列出合理的目录结构及代码文件,并给出每个文件详细的代码编写
:
目录结构:
- src
- app
- models.py # 定义数据库模型
- schemas.py # 定义学生信息数据结构
- views.py # 定义API接口
- config
- settings.py # 配置文件
- main.py # 入口文件
- app
from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Students(Base): __tablename__ = 'students' id = Column(Integer, primary_key=True) name = Column(String) age = Column(Integer) gender = Column(String) address = Column(String)
from pydantic import BaseModel class StudentSchema(BaseModel): name: str age: int gender: str address: str
from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from app.models import Students from app.schemas import StudentSchema from config.settings import SessionLocal router = APIRouter() # 查询学生信息 @router.get("/students/{student_id}") def get_student_info(student_id: int, db: Session = Depends(SessionLocal)): student = db.query(Students).filter(Students.id == student_id).first() if student is None: raise HTTPException(status_code=404, detail="Student not found") return student # 添加学生信息 @router.post("/students") def add_student_info(student: StudentSchema, db: Session = Depends(SessionLocal)): db_student = Students(name=student.name, age=student.age, gender=student.gender, address=student.address) db.add(db_student) db.commit() db.refresh(db_student) return db_student # 更新学生信息 @router.put("/students/{student_id}") def update_student_info(student_id: int, student: StudentSchema, db: Session = Depends(SessionLocal)): student_record = db.query(Students).filter(Students.id == student_id).first() if student_record is None: raise HTTPException(status_code=404, detail="Student not found") student_record.name = student.name student_record.age = student.age student_record.gender = student.gender student_record.address = student.address db.commit() return student_record # 删除学生信息 @router.delete("/students/{student_id}") def remove_student_info(student_id: int, db: Session = Depends(SessionLocal)): student_record = db.query(Students).filter(Students.id == student_id).first() if student_record is None: raise HTTPException(status_code=404, detail="Student not found") db.delete(student_record) db.commit() return student_record
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker # 数据库连接参数 DB_CONFIG = { 'user': 'root', 'password': '123456', 'host': 'localhost', 'port': '3306', 'database': 'students_info' } # 生成sqlalchemy引擎 SQLALCHEMY_DATABASE_URL = f"mysql://{DB_CONFIG['user']}:{DB_CONFIG['password']}@{DB_CONFIG['host']}:{DB_CONFIG['port']}/{DB_CONFIG['database']}" engine = create_engine(SQLALCHEMY_DATABASE_URL) # 创建会话 SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) # 创建基类 Base = declarative_base()
from fastapi import FastAPI from src.app.views import router app = FastAPI() app.include_router(router)
- src
-
guest说:
我要做一个纯后端的API接口项目,留言板管理系统,用的是FastAPI框架,要求使用mysql、sqlalchemy、pydantic、logging,请帮我列出合理的目录结构,并给出每个文件详细的代码编写
要求。
目录结构:
- README.md
- .env
- requirements.txt
- config.py
- app.py
- models
- init.py
- model.py
- services
- init.py
- service.py
- routes
- init.py
- route.py
README.md:项目介绍文件,包括简介、技术框架、环境搭建、项目运行及测试等信息。
.env:环境变量文件,用于存放数据库连接等信息。
requirements.txt:项目所需依赖包文件,用于记录项目所需要的第三方依赖包。
config.py:配置文件,用于存放项目相关的配置信息,如数据库链接、logging配置等。
app.py:主文件,用于创建FastAPI的实例,绑定路由、数据库以及日志等。
models/init.py:models初始化文件,用于记录模块内容。
models/model.py:模型文件,用于创建数据库模型,使用pydantic和sqlalchemy。
services/init.py:services初始化文件,用于记录模块内容。
services/service.py:服务文件,用于处理业务逻辑,调用model文件中的数据库模型进行数据库操作。
routes/init.py:routes初始化文件,用于记录模块内容。
routes/route.py:路由文件,用于定义API接口,调用services文件中的service进行处理。
config.py文件编写要求:
import os # 数据库链接 DATABASE_URL = os.getenv('DATABASE_URL') # 日志配置 LOG_LEVEL = os.getenv('LOG_LEVEL', 'INFO') LOG_FORMAT = os.getenv('LOG_FORMAT', '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
app.py文件编写要求:
import logging from fastapi import FastAPI from starlette.middleware.cors import CORSMiddleware from config import LOG_LEVEL, LOG_FORMAT from models import Base from routes import router from services import Services # 设置日志配置 logging.basicConfig(level=LOG_LEVEL, format=LOG_FORMAT) # 创建 FastAPI 实例 app = FastAPI() # 设置跨域 app.add_middleware( CORSMiddleware, allow_origins=['*'], allow_credentials=True, allow_methods=['*'], allow_headers=['*'], ) # 绑定路由 app.include_router(router, prefix='/api') # 绑定数据库 Base.metadata.bind = app.state.db # 绑定服务 app.state.services = Services()
models/model.py文件编写要求:
from sqlalchemy import Column, Integer, String from pydantic import BaseModel from models import Base class Message(BaseModel): title: str content: str class MessageModel(Base): __tablename__ = 'message' id = Column(Integer, primary_key=True, autoincrement=True) title = Column(String(100), nullable=False) content = Column(String(255), nullable=False)
services/service.py文件编写要求:
from sqlalchemy.orm import Session from models.model import MessageModel from services import Services class MessageService(Services): def __init__(self, db: Session): self.db = db super().__init__(db) def create_message(self, message: MessageModel): self.add(message) def get_message(self, message_id: int): return self.get(MessageModel, message_id)
routes/route.py文件编写要求:
from typing import Optional from fastapi import APIRouter, Depends from pydantic import BaseModel from models.model import Message from services.service import MessageService router = APIRouter() @router.post("/message/") def create_message(message: Message, message_service: MessageService = Depends()): message_service.create_message(message) @router.get("/message/{message_id}") def get_message(message_id: int, message_service: MessageService = Depends()): return message_service.get_message(message_id)