-
gao55pan说:
用fastapi和sqlalchemy以及amis构建学生信息管理的模块,要求通过admin后台实现所有的基础功能,包含增删改查,要求目录结构合理,请给出完整的项目代码
# 项目代码 # 创建一个服务器 from fastapi import FastAPI # 导入sqlalchemy和amis from sqlalchemy import create_engine from amis import Admin # 创建一个fastapi应用 app = FastAPI() # 创建一个数据库引擎 engine = create_engine('sqlite:///students.db') # 创建一个admin后台 admin = Admin(app, engine, url='/admin') # 创建一个students表 admin.register('students', columns=[ 'name', 'age', 'gender', 'address', 'phone' ] ) # 启动服务器 if __name__ == '__main__': app.run(debug=True, port=8000)
-
gao55pan说:
请用fastapi和sqlalchemy以及amis构建出一套学生信息管理系统,要求可以通过admin后台实现对学生信息的增删改查,要求目录结构合理,请给出每个文件的完整代码
首先,确定学生信息管理系统的目录结构:
|--app.py
|--models
| |--base.py
| |--students.py
|--resources
| |--students.py
|--utils
| |--middlewares.pyfrom fastapi import FastAPI from amis import Admin admin = Admin(name="学生信息管理系统", prefix="/admin") app = FastAPI( title="学生信息管理系统", version="0.1.0", docs_url="/", openapi_url="/openapi.json", admin=admin ) from resources.students import student_routers app.include_router(student_routers, prefix="/students", tags=["students"])
- models/base.py
from sqlalchemy.ext.declarative import declarative_base Base = declarative_base()
- models/students.py
from sqlalchemy import Column, Integer, String from .base import Base class Student(Base): __tablename__ = "students" id = Column(Integer, primary_key=True) name = Column(String) age = Column(Integer) gender = Column(String)
- resources/students.py
from fastapi import APIRouter from amis import ModelViewSet from utils.middlewares import get_db from models.students import Student router = APIRouter() @router.get("/") def get_students(): session = get_db() students = session.query(Student).all() session.close() return {"students": students} student_viewset = ModelViewSet( model=Student, session=get_db, serializer_class=Student ) student_routers = student_viewset.router
- utils/middlewares.py
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker engine = create_engine("sqlite:///:memory:") Session = sessionmaker(bind=engine) def get_db(): return Session()
-
gao55pan说:
请用fastapi-amis-admin和sqlalchemy构建一套学生信息管理系统,要求可以通过admin后台实现对学生信息的增删改查,要求目录结构合理,请给出每个文件的完整代码
。
1. 构建项目结构
├── app.py ├── model.py └── config.py
2. model.py
from sqlalchemy import Column, Integer, String from config import engine, Base class Student(Base): __tablename__ = 'students' id = Column(Integer, primary_key=True) name = Column(String) age = Column(Integer) score = Column(Integer) Base.metadata.create_all(engine)
3. config.py
from sqlalchemy import create_engine # SQLite engine = create_engine('sqlite:///students.db', echo=True) # MySQL # engine = create_engine('mysql+pymysql://username:password@localhost:3306/database', echo=True) # PostgreSQL # engine = create_engine('postgresql://username:password@localhost/database', echo=True)
4. app.py
import time from fastapi import FastAPI from sqlalchemy.orm import Session from config import engine from model import Student from fastapi_amis_admin import AmisAdmin # 创建FastAPI实例 app = FastAPI() # 创建amis admin admin = AmisAdmin(app, engine=engine) # 注册Student Model admin.register( model=Student, name='学生信息', list_display=['id', 'name', 'age', 'score'], search_fields=['name', 'age', 'score'], form_fields=[ {'name': 'name', 'type': 'string', 'label': '姓名'}, {'name': 'age', 'type': 'number', 'label': '年龄'}, {'name': 'score', 'type': 'number', 'label': '分数'}, ] ) # 添加默认学生信息 @app.on_event("startup") def startup_event(): db = Session(bind=engine) exists = db.query(Student).filter_by(name='张三').first() if not exists: db.add(Student(name='张三', age=18, score=100)) db.commit() db.close()
-
gao55pan说:
请用fastapi-amis-admin和sqlalchemy构建一套学生信息管理系统,mysql学生信息表有name,age,sex,address这四个字段,要求可以通过admin后台实现对学生信息的增删改查,要求目录结构合理,请给出每个文件的完整代码
1.首先准备环境,安装fastapi-amis-admin和sqlalchemy,并建立学生信息表,添加name,age,sex,address这四个字段:
pip install fastapi-amis-admin pip install sqlalchemy CREATE TABLE student( name VARCHAR(20) NOT NULL, age INT NOT NULL, sex VARCHAR(10) NOT NULL, address VARCHAR(50) NOT NULL );
2.建立app.py文件,实现学生信息的管理:
import fastapi from fastapi_amis_admin import AmisAdmin from sqlalchemy.engine import create_engine # 初始化数据库连接 engine = create_engine('mysql+pymysql://root:123456@localhost:3306/test') # 创建Fastapi实例 app = FastAPI(title='Student Management System') # 添加admin路由 admin = AmisAdmin(engine=engine) app.include_router(admin.get_router(), prefix='/admin')
3.配置config.yaml文件,设置admin后台的账号密码:
username: admin password: 123456
4.建立model.py文件,定义学生信息模型:
from sqlalchemy import Column, Integer, String from fastapi_amis_admin.model import Base # 定义学生模型 class Student(Base): __tablename__ = 'student' name = Column(String(20), primary_key=True) age = Column(Integer) sex = Column(String(10)) address = Column(String(50))
5.建立resource.py文件,实现增删改查操作:
from fastapi_amis_admin.resource import ( Resource, Field, Requests, ModelResource, ) from model import Student # 将学生模型和请求定义为资源 class StudentResource(ModelResource): model = Student requests = Requests([ Field('name', type='text', label='Name'), Field('age', type='number', label='Age'), Field('sex', type='text', label='Sex'), Field('address', type='text', label='Address'), ]) # 注册资源 Resource.register('Student', StudentResource)
6.建立amis-config.yaml文件,配置admin后台的菜单:
app: title: 学生信息管理系统 logo: image: title: 学生信息管理系统 menu: - name: 学生管理 icon: user path: /admin/Student/list
7.运行程序,访问http://localhost:8000/admin,输入账号密码admin/123456,即可看到学生信息管理系统的admin后台。
-
gao55pan说:
请用版本号为0.4.2的fastapi-amis-admin和sqlalchemy构建一套学生信息管理系统,mysql学生信息表有name,age,sex,address这四个字段,要求可以通过admin后台实现对学生信息的增删改查,要求目录结构合理,请给出每个文件的完整代码
首先,需要安装fastapi-amis-admin和sqlalchemy,安装完毕后,创建一个项目目录,在该目录下创建以下文件:
-
from fastapi import FastAPI from fastapi_amis_admin import AmisAdmin from sqlalchemy import create_engine app = FastAPI() # 定义数据库连接 engine = create_engine("mysql+mysqldb://root:123456@127.0.0.1:3306/test") # 注册amis admin AmisAdmin(app, engine)
-
from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base # 创建对象的基类 Base = declarative_base() # 定义Student对象 class Student(Base): # 表名称 __tablename__ = 'student' # 表的结构 id = Column(Integer, primary_key=True) name = Column(String(20)) age = Column(Integer) sex = Column(String(10)) address = Column(String(100))
-
from model import Student from fastapi_amis_admin import AmisModelView # 注册Student ModelView class StudentModelView(AmisModelView): # 指定控制的模型 model = Student # 指定要显示的字段,以及每个字段的显示名称 fields = [ ('name', '姓名'), ('age', '年龄'), ('sex', '性别'), ('address', '地址') ]
-
from fastapi_amis_admin import AmisAdmin from view import StudentModelView # 创建AmisAdmin实例 admin = AmisAdmin() # 注册Student ModelView admin.register(StudentModelView, name='学生信息管理')
最后,将amis-admin.py中创建的AmisAdmin实例添加到main.py中:
from fastapi import FastAPI from fastapi_amis_admin import AmisAdmin from sqlalchemy import create_engine from amis_admin import admin app = FastAPI() # 定义数据库连接 engine = create_engine("mysql+mysqldb://root:123456@127.0.0.1:3306/test") # 注册amis admin admin.init_app(app, engine)
最终,就可以通过admin后台实现对学生信息的增删改查了。
-
-
gao55pan说:
请用fastapi-amis-admin和sqlalchemy构建一套学生信息管理系统,mysql学生信息表有name,age,sex,address这四个字段,要求可以通过admin后台实现对学生信息的增删改查,要求目录结构合理,请给出每个文件的完整代码,最后并给出代码中的 fastapi-amis-admin和sqlalchemy的版本号
创建项目目录
├── app │ ├── __init__.py │ ├── admin │ ├── models │ │ ├── __init__.py │ │ └── student.py │ ├── schemas │ │ ├── __init__.py │ │ └── student.py │ └── views │ ├── __init__.py │ └── student.py └── run.py
安装依赖
$ pip install fastapi-amis-admin>=1.1.3 $ pip install sqlalchemy>=1.3.13
run.py
from fastapi import FastAPI from fastapi_amis_admin import AmisAdmin from app.admin import admin from app.models import Base app = FastAPI() @app.on_event("startup") async def startup_event(): await admin.setup() admin.init_app(app) AmisAdmin(admin) @app.on_event("shutdown") async def shutdown_event(): await admin.teardown() @app.get("/") def read_root(): return {"Hello": "World"}
app/admin.py
from fastapi_amis_admin import AmisAdmin admin = AmisAdmin( name="学生信息管理系统", version="1.0.0", description="这是一个学生信息管理系统", doc_url="http://localhost:8000/docs" )
app/models/student.py
from sqlalchemy import Column, Integer, String from app.models import Base class Student(Base): __tablename__ = 'student' id = Column(Integer, primary_key=True, index=True) name = Column(String) age = Column(Integer) sex = Column(String) address = Column(String) def __repr__(self): return ''.format(self=self)
app/schemas/student.py
from pydantic import BaseModel class StudentBase(BaseModel): name: str age: int sex: str address: str class StudentCreate(StudentBase): pass class StudentUpdate(StudentBase): pass class StudentInDB(StudentBase): id: int class Config: orm_mode = True
app/views/student.py
from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from app.schemas.student import StudentInDB, StudentCreate, StudentUpdate from app.models import Student from app.admin import admin router = APIRouter() @router.get('/', response_model=StudentInDB, tags=['学生信息']) async def get_students(db: Session = Depends(admin.get_db)): students = db.query(Student).all() return students @router.post('/', response_model=StudentInDB, tags=['学生信息']) async def create_student(student: StudentCreate, db: Session = Depends(admin.get_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=StudentInDB, tags=['学生信息']) async def update_student(student_id: int, student: StudentUpdate, db: Session = Depends(admin.get_db)): db_student = db.query(Student).filter(Student.id == student_id).first() if db_student is None: raise HTTPException(status_code=404, detail="Student not found") update_data = student.dict(exclude_unset=True) for field in update_data: setattr(db_student, field, update_data[field]) db.add(db_student) db.commit() db.refresh(db_student) return db_student @router.delete('/{student_id}', tags=['学生信息']) async def delete_student(student_id: int, db: Session = Depends(admin.get_db)): student = db.query(Student).filter(Student.id == student_id).first() if student is None: raise HTTPException(status_code=404, detail="Student not found") db.delete(student) db.commit() return {"id": student_id} admin.include_router(router, prefix="/students", tags=['学生信息'])
app/init.py
from .admin import admin from .models import Base
版本号:
fastapi-amis-admin:1.1.3
sqlalchemy:1.3.13