-
guest说:
hi
ervan is dat de schoonheid van je huid gedurende de dag toeneemt. In de ochtend heb je een frisse en stralende huid. In de avond ben je klaar om de nacht in te gaan met een gezonde en glanzende huid. De ingrediënten in deze crème helpen ook bij het verminderen van fijne lijntjes en rimpels, het verbeteren van de algemene teint en het verminderen van oneffenheden zoals acne en littekens. De crème is ook vrij van parabenen, sulfaten, phthalaten en kunstmatige kleur- en geurstoffen. Het is een goede keuze voor mensen met een gevoelige huid.
-
guest说:
hi
-tech manufacturer of small-scale equipment for the printing industry.
We are a leading manufacturer of small-scale printing equipment for the printing industry. Our products are designed to help businesses maximize their productivity and efficiency. We specialize in providing high-quality, reliable, and cost-effective solutions for the printing industry. Our products are engineered to the highest standards and are made to last. We strive to provide our customers with superior customer service and the latest printing technology for their particular needs. We offer a range of products from professional grade high-end presses to entry-level desktop machines. We also offer a variety of consumables, such as inks, toners, and paper, to ensure that our customers have all the necessary materials needed for their printing needs.
-
guest说:
生成一个纯后端的API接口,用于学生信息管理,用FastAPI+mysql+sqlalchemy+pydantic+logging,用到yield db,要求项目结构中有Models目录,Routers目录,Schemas目录,Logs目录,Config目录,Tests目录,并给出每个文件详细的代码编写
Project Structure
- models
- init.py
- student.py
- routers
- init.py
- studentRouter.py
- schemas
- init.py
- studentSchema.py
- logs
- init.py
- studentLogger.py
- config
- init.py
- config.py
- tests
- init.py
- studentTests.py
- main.py
models/init.py
from .student import Student
models/student.py
from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Student(Base): __tablename__ = 'students' id = Column(Integer, primary_key=True) name = Column(String) age = Column(Integer) gender = Column(String) address = Column(String) major = Column(String)
routers/init.py
from .studentRouter import student_router
routers/studentRouter.py
from fastapi import APIRouter student_router = APIRouter() @student_router.get('/students') def get_all_students(): # get all students logic pass @student_router.post('/students') def create_student(): # create student logic pass @student_router.put('/students/{student_id}') def update_student(student_id: int): # update student logic pass @student_router.delete('/students/{student_id}') def delete_student(student_id: int): # delete student logic pass
schemas/init.py
from .studentSchema import StudentSchema
schemas/studentSchema.py
from pydantic import BaseModel class StudentSchema(BaseModel): id: int name: str age: int gender: str address: str major: str
logs/init.py
from .studentLogger import student_logger
logs/studentLogger.py
import logging student_logger = logging.getLogger('studentLogger') student_logger.setLevel(logging.INFO) # create file handler handler = logging.FileHandler('student.log') handler.setLevel(logging.INFO) # create a logging format formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) # add the handlers to the logger student_logger.addHandler(handler)
config/init.py
from .config import *
config/config.py
from pydantic import BaseSettings class Settings(BaseSettings): sqlalchemy_url: str settings = Settings()
tests/init.py
from .studentTests import *
tests/studentTests.py
import unittest class StudentTests(unittest.TestCase): def test_get_all_students(self): # test get all students logic pass def test_create_student(self): # test create student logic pass def test_update_student(self): # test update student logic pass def test_delete_student(self): # test delete student logic pass
main.py
from fastapi import FastAPI from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from config import settings from routers import student_router from logs import student_logger app = FastAPI() engine = create_engine(settings.sqlalchemy_url) Session = sessionmaker(bind=engine) def get_db(): try: db = Session() yield db finally: db.close() app.include_router(student_router) @app.get('/') def index(): student_logger.info('This is a student info management API') return 'This is a student info management API'
- models
-
guest说:
生成一个纯后端的API接口,用于学生信息管理,用FastAPI+mysql+sqlalchemy+pydantic+logging,用到yield db,要求项目结构中有Models目录,Routers目录,Schemas目录,Logs目录,Config目录,Tests目录,并给出每个文件详细的代码编写,
实现学生信息管理的全部功能
一、项目结构
Project ├───Models // ORM 模型 │ └───model.py ├───Routers // 路由 │ └───router.py ├───Schemas // 数据模型 │ └───schema.py ├───Logs // 日志 │ └───log.py ├───Config // 配置文件 │ └───config.py └───Tests // 测试 └───test.py
二、模型文件(Models/model.py)
# 导入相关模块 from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base # 创建基类 Base = declarative_base() # 创建学生表 class Student(Base): __tablename__ = 'student' # 创建表字段 id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String(50), nullable=False) age = Column(Integer) gender = Column(String(10))
三、路由文件(Routers/router.py)
# 导入相关模块 from typing import List from fastapi import APIRouter, Depends from sqlalchemy.orm import Session from sqlalchemy import create_engine from . import models, schemas # 创建路由 router = APIRouter() # 连接数据库 engine = create_engine('mysql+pymysql://root:123456@localhost:3306/student_info') # 获取session def get_db(): db = Session(bind=engine) try: yield db finally: db.close() # 获取所有学生信息 @router.get('/get_all_student', response_model=List[schemas.Student]) def get_all_student(db: Session=Depends(get_db)): students = db.query(models.Student).all() return students # 添加学生信息 @router.post('/add_student', response_model=schemas.Student) def add_student(student: schemas.Student, db: Session=Depends(get_db)): student_model = models.Student(name=student.name, age=student.age, gender=student.gender) db.add(student_model) db.commit() db.refresh(student_model) return student_model # 修改学生信息 @router.put('/update_student/{student_id}', response_model=schemas.Student) def update_student(student_id: int, student: schemas.Student, db: Session=Depends(get_db)): student_model = db.query(models.Student).filter(models.Student.id == student_id).first() student_model.name = student.name student_model.age = student.age student_model.gender = student.gender db.commit() db.refresh(student_model) return student_model # 删除学生信息 @router.delete('/delete_student/{student_id}', response_model=schemas.Student) def delete_student(student_id: int, db: Session=Depends(get_db)): student_model = db.query(models.Student).filter(models.Student.id == student_id).first() db.delete(student_model) db.commit() return student_model
四、模型文件(Schemas/schema.py)
# 导入相关模块 from pydantic import BaseModel # 创建学生信息模型 class Student(BaseModel): name: str age: int gender: str
五、日志文件(Logs/log.py)
# 导入相关模块 import logging # 设置日志等级、格式、文件名 logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', filename='logs/student_info.log')
六、配置文件(Config/config.py)
# 数据库连接配置 DATABASE_CONFIG = { 'host': 'localhost', 'user': 'root', 'password': '123456', 'db': 'student_info' }
七、测试文件(Tests/test.py)
# 导入相关模块 import json import unittest from fastapi.testclient import TestClient from routers import router # 测试类 class TestStudent(unittest.TestCase): # 测试初始化 def setUp(self): self.client = TestClient(router) # 测试获取所有学生信息 def test_get_all_student(self): response = self.client.get('/get_all_student') self.assertEqual(response.status_code, 200) # 测试添加学生信息 def test_add_student(self): data = { 'name': '张三', 'age': 18, 'gender': '男' } response = self.client.post('/add_student', data=json.dumps(data)) self.assertEqual(response.status_code, 200) # 测试修改学生信息 def test_update_student(self): data = { 'name': '李四', 'age': 18, 'gender': '男' } response = self.client.put('/update_student/1', data=json.dumps(data)) self.assertEqual(response.status_code, 200) # 测试删除学生信息 def test_delete_student(self): response = self.client.delete('/delete_student/2') self.assertEqual(response.status_code, 200) # 执行测试 if __name__ == '__main__': unittest.main()
-
guest说:
生成一个纯后端的API接口,用于学生信息管理,用FastAPI+mysql+sqlalchemy+pydantic+logging,用到yield db,要求目录结构合理,包含Models目录,routers目录,schemas目录,logs目录,config目录,Tests目录,并给出每个文件详细的代码编写,
路由如下:
- API - Models - student.py - routers - student.py - schemas - student.py - logs - student.log - config - config.py - Tests - test_student.py - main.py
Models/student.py
from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Student(Base): __tablename__ = 'student' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String(20)) age = Column(Integer) gender = Column(String(10)) student_id = Column(String(20)) school = Column(String(50)) major = Column(String(20))
schemas/student.py
from pydantic import BaseModel class Student(BaseModel): name: str age: int gender: str student_id: str school: str major: str
routers/student.py
from fastapi import APIRouter, Depends from sqlalchemy.orm import Session from .. import models, schemas from ..database import SessionLocal router = APIRouter() # Dependency def get_db(): db = SessionLocal() try: yield db finally: db.close() @router.get("/") async def get_all_student(db: Session = Depends(get_db)): student = db.query(models.Student).all() return student @router.post("/") async def create_student(student: schemas.Student, db: Session = Depends(get_db)): db_student = models.Student(**student.dict()) db.add(db_student) db.commit() db.refresh(db_student) return db_student @router.get("/{student_id}") async def get_student(student_id: int, db: Session = Depends(get_db)): student = db.query(models.Student).filter(models.Student.id == student_id).first() return student @router.put("/{student_id}") async def update_student(student_id: int, student: schemas.Student, db: Session = Depends(get_db)): db_student = db.query(models.Student).filter(models.Student.id == student_id).first() update_data = student.dict(exclude_unset=True) for key, value in update_data.items(): setattr(db_student, key, value) db.commit() return db_student @router.delete("/{student_id}") async def delete_student(student_id: int, db: Session = Depends(get_db)): student = db.query(models.Student).filter(models.Student.id == student_id).delete() db.commit() return student
config/config.py
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://:@/'
Tests/test_student.py
from fastapi.testclient import TestClient import pytest from main import app client = TestClient(app) def test_get_all_student(): response = client.get('/student/') assert response.status_code == 200 def test_create_student(): data = { 'name': 'test', 'age': 18, 'gender': 'male', 'student_id': '123456', 'school': 'test school', 'major': 'test major' } response = client.post('/student/', json=data) assert response.status_code == 200 def test_get_student(): response = client.get('/student/1') assert response.status_code == 200 def test_update_student(): data = { 'name': 'test1', 'age': 20, } response = client.put('/student/1', json=data) assert response.status_code == 200 def test_delete_student(): response = client.delete('/student/1') assert response.status_code == 200
from fastapi import FastAPI from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from loguru import logger from .config import SQLALCHEMY_DATABASE_URI from .routers import student # Initialize the FastAPI app app = FastAPI() # Initialize the database engine = create_engine(SQLALCHEMY_DATABASE_URI) Base = declarative_base() SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) # Configure the logging logger.add("logs/student.log") # Add the routers app.include_router(student.router, prefix='/student')
-
guest说:
生成一个纯后端的API接口,用于学生信息管理,用FastAPI框架+mysql+sqlalchemy+pydantic+logging,要求目录结构合理,包含Models目录,routers目录,schemas目录,logs目录,config目录,Tests目录,并给出每个文件详细的代码编写,并且用到yield db
.commit()
├── config
│ ├── config.py
│ └── logging.conf
├── logs
│ ├── logfile.log
│ └── log_data.log
├── main.py
├── models
│ ├── init.py
│ └── student.py
├── routers
│ └── student_api.py
├── schemas
│ ├── init.py
│ └── student_schema.py
└── tests
└── student_test.pyconfig/config.py
import os
DATABASE_URI = os.environ.get('DATABASE_URI', 'mysql+pymysql://root:xxxx@127.0.0.1:3306/student_db')
config/logging.conf
[loggers]
keys=root[handlers]
keys=consoleHandler[formatters]
keys=simpleFormatter[logger_root]
level=DEBUG
handlers=consoleHandler[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout, )[formatter_simpleFormatter]
format=%(asctime)s [%(levelname)s] [%(name)s] %(message)smain.py
from fastapi import FastAPI
from starlette.requests import Request
from starlette.responses import Response
from starlette.middleware.cors import CORSMiddleware
from starlette.config import Config
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmakerimport logging
读取配置文件
config = Config('.env')
设置日志
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("app")设置数据库
engine = create_engine(config("DATABASE_URI"))
Base = declarative_base()
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
db = SessionLocal()初始化app
app = FastAPI(debug=True)
允许跨域
app.add_middleware(
CORSMiddleware,
allow_origins=[""],
allow_credentials=True,
allow_methods=[""],
allow_headers=["*"],
)注册路由
from .routers import student_api
app.include_router(student_api.router, prefix="/students")
models/student.py
from sqlalchemy import Column, Integer, String
from . import Baseclass Student(Base):
tablename = 'students'id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String(64), nullable=False) age = Column(Integer, nullable=False) gender = Column(String(64), nullable=False) address = Column(String(128), nullable=False)
schemas/student_schema.py
from pydantic import BaseModel
class StudentSchema(BaseModel):
id: int
name: str
age: int
gender: str
address: strrouters/student_api.py
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from ..models.student import Student
from ..schemas.student_schema import StudentSchemarouter = APIRouter()
@router.get("/", response_model=StudentSchema(many=True))
def get_students(db: Session = Depends(db)):
students = db.query(Student).all()
return students@router.post("/", response_model=StudentSchema())
def create_student(student: StudentSchema, db: Session = Depends(db)):
db_student = Student(**student.dict())
db.add(db_student)
db.commit()
db.refresh(db_student)
return db_student@router.put("/{student_id}", response_model=StudentSchema())
def update_student(student_id: int, student: StudentSchema, db: Session = Depends(db)):
db_student = db.query(Student).filter(Student.id == student_id).first()
db_student.name = student.name
db_student.age = student.age
db_student.gender = student.gender
db_student.address = student.address
db.add(db_student)
db.commit()
db.refresh(db_student)
return db_student@router.delete("/{student_id}", response_model=StudentSchema())
def delete_student(student_id: int, db: Session = Depends(db)):
db_student = db.query(Student).filter(Student.id == student_id).first()
db.delete(db_student)
db.commit()
return db_studenttests/student_test.py
from fastapi.testclient import TestClient
from . main import appclient = TestClient(app)
def test_get_students():
response = client.get("/students/")
assert response.status_code == 200
assert response.json() == []def test_create_student():
response = client.post("/students/", json={
"name": "John",
"age": 23,
"gender": "Male",
"address": "New York"
})
assert response.status_code == 200
assert response.json() == {
"id": 1,
"name": "John",
"age": 23,
"gender": "Male",
"address": "New York"
}def test_update_student():
response = client.put("/students/1", json={
"name": "John Doe",
"age": 24,
"gender": "Male",
"address": "New York"
})
assert response.status_code == 200
assert response.json() == {
"id": 1,
"name": "John Doe",
"age": 24,
"gender": "Male",
"address": "New York"
}def test_delete_student():
response = client.delete("/students/1")
assert response.status_code == 200
assert response.json() == {
"id": 1,
"name": "John Doe",
"age": 24,
"gender": "Male",
"address": "New York"
}