-
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
-
gao55pan说:
fastapi-amis-admin怎么安装1.1.3版本
要安装fastapi-amis-admin 1.1.3 版本,可以通过以下步骤来实现:
- 安装 Node.js 和 npm:
首先,确保您的系统上安装有Node.js和npm,这是fastapi-amis-admin应用的运行所必需的,它们可以从Node.js官网上轻松获取。
- 安装fastapi-amis-admin:
使用以下npm命令安装fastapi-amis-admin 1.1.3 版本:
npm install fastapi-amis-admin@1.1.3
- 启动应用:
通过以下npm命令启动应用程序:
npm start
-
gao55pan说:
请用python中版本号为0.4.2的fastapi-amis-admin和版本号为1.4.41的sqlalchemy构建一套学生信息管理系统,mysql学生信息表有name,age,sex,address这四个字段,要求可以通过admin后台实现对学生信息的增删改查,要求目录结构合理,请给出每个文件的完整代码
安装相关依赖
pip install fastapi-amis-admin==0.4.2
pip install sqlalchemy==1.4.41创建目录
mkdir student-management-system
cd student-management-system创建文件
touch main.py
touch model.py
touch admin.pymain.py文件
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddlewarefrom admin import admin
from model import Studentapp = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=[""],
allow_credentials=True,
allow_methods=[""],
allow_headers=["*"]
)app.include_router(admin.router, prefix='/admin')
@app.on_event('startup')
async def startup():
await Student.create_table()@app.on_event('shutdown')
async def shutdown():
await Student.drop_table()model.py文件
from sqlalchemy import Column, String, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmakerBase = declarative_base()
class Student(Base):
tablename = 'students'
name = Column(String(50), primary_key=True)
age = Column(Integer)
sex = Column(String(20))
address = Column(String(100))@classmethod async def create_table(cls): engine = create_engine('mysql+pymysql://username:password@host:3306/db_name') Base.metadata.create_all(engine) @classmethod async def drop_table(cls): engine = create_engine('mysql+pymysql://username:password@host:3306/db_name') Base.metadata.drop_all(engine)
admin.py文件
from fastapi_amis_admin import AmisAdmin
from model import Studentadmin = AmisAdmin(
name='Students Management',
version='v1.0.0'
)@admin.register_crud(
name='students',
model=Student
)
def students_crud():
pass -
gao55pan说:
用python的fastapi框架和vue构建一套学生信息管理系统,mysql学生信息表有name,age,sex,address这四个字段,要求可以通过admin后台实现对学生信息的增删改查,要求目录结构合理,请给出每个文件的完整代码
一、完整的文件目录结构
├── api # api接口文件夹 │ ├── app.py # 后端app入口文件 │ ├── database.py # 数据库操作文件 │ └── routers.py # api接口文件 ├── vue # vue前端文件夹 │ ├── components # vue组件 │ │ ├── admin # 后台管理组件 │ │ │ ├── add.vue # 添加学生信息组件 │ │ │ ├── delete.vue # 删除学生信息组件 │ │ │ ├── update.vue # 修改学生信息组件 │ │ │ └── view.vue # 查看学生信息组件 │ │ └── App.vue # 入口组件 │ ├── main.js # vue入口文件 │ ├── router.js # vue路由文件 │ ├── store.js # vue状态管理文件 │ └── views # 视图文件 │ └── index.vue # 首页 ├── .gitignore # git忽略文件 └── README.md # 项目说明文件
二、每个文件的完整代码
from fastapi import FastAPI from routers import student_router app = FastAPI() app.include_router( student_router, prefix="/students", tags=["students"] )
# -*- coding: utf-8 -*- import pymysql # mysql数据库连接 def connect_mysql(): conn = pymysql.connect( host='127.0.0.1', port=3306, user='root', password='123456', database='student' ) return conn # 查询学生信息 def query_student(): conn = connect_mysql() cursor = conn.cursor() sql = "select * from student" cursor.execute(sql) res = cursor.fetchall() cursor.close() conn.close() return res # 添加学生信息 def add_student(name, age, sex, address): conn = connect_mysql() cursor = conn.cursor() sql = "insert into student values('%s', '%s', '%s', '%s')" % (name, age, sex, address) cursor.execute(sql) conn.commit() cursor.close() conn.close() # 删除学生信息 def delete_student(name): conn = connect_mysql() cursor = conn.cursor() sql = "delete from student where name='%s'" % name cursor.execute(sql) conn.commit() cursor.close() conn.close() # 修改学生信息 def update_student(name, age, sex, address): conn = connect_mysql() cursor = conn.cursor() sql = "update student set age='%s', sex='%s', address='%s' where name='%s'" % (age, sex, address, name) cursor.execute(sql) conn.commit() cursor.close() conn.close()
# -*- coding: utf-8 -*- from fastapi import APIRouter from database import query_student, add_student, delete_student, update_student student_router = APIRouter() # 获取学生信息 @student_router.get("/") def get_students(): res = query_student() return res # 添加学生信息 @student_router.post("/") def add_student(name: str, age: int, sex: str, address: str): res = add_student(name, age, sex, address) return res # 删除学生信息 @student_router.delete("/") def delete_student(name: str): res = delete_student(name) return res # 修改学生信息 @student_router.put("/") def update_student(name: str, age: int, sex: str, address: str): res = update_student(name, age, sex, address) return res
- add.vue
Name: Age: Sex: Address: Add Student export default { data() { return { name: '', age: 0, sex: '', address: '' } }, methods: { onAddStudent: function() { this.$axios.post('/students/', { name: this.name, age: this.age, sex: this.sex, address: this.address }).then(() => { alert('添加成功!') this.$router.push({ path: '/' }) }).catch((err) => { alert(err) }) } } }
- delete.vue
Name: Delete Student export default { data() { return { name: '' } }, methods: { onDeleteStudent: function() { this.$axios.delete('/students/', { params: { name: this.name } }).then(() => { alert('删除成功!') this.$router.push({ path: '/' }) }).catch((err) => { alert(err) }) } } }
- update.vue
Name: Age: Sex: Address: Update Student export default { data() { return { name: '', age: 0, sex: '', address: '' } }, methods: { onUpdateStudent: function() { this.$axios.put('/students/', { name: this.name, age: this.age, sex: this.sex, address: this.address }).then(() => { alert('修改成功!') this.$router.push({ path: '/' }) }).catch((err) => { alert(err) }) } } }
- view.vue
Name Age Sex Address {{ item.name }} {{ item.age }} {{ item.sex }} {{ item.address }} export default { data() { return { students: [] } }, mounted() { this.$axios.get('/students/').then((res) => { this.students = res.data }).catch((err) => { alert(err) }) } }
- App.vue
export default { data() { return { } } }
- main.js
import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' Vue.config.productionTip = false new Vue({ router, store, render: h => h(App) }).$mount('#app')
- router.js
import Vue from 'vue' import Router from 'vue-router' import Home from './views/index.vue' import Add from './components/admin/add.vue' import Delete from './components/admin/delete.vue' import Update from './components/admin/update.vue' import View from './components/admin/view.vue' Vue.use(Router) export default new Router({ mode: 'history', base: process.env.BASE_URL, routes: [ { path: '/', name: 'home', component: Home }, {
-
gao55pan说:
用python的fastapi框架构建一套学生信息管理系统,mysql学生信息表有name,age,sex,address这四个字段,要求可以通过admin后台实现对学生信息的增删改查,要求目录结构合理,请给出每个文件的完整代码
from fastapi import FastAPI app = FastAPI() @app.get("/") def root(): return {"message": "Hello World!"}
routers/admin.py
from fastapi import APIRouter from ..model.student import Student router = APIRouter() @router.get("/students") def list_students(): return Student.objects.all() @router.post("/students") def add_student(student: Student): student.save() return student @router.put("/students/{student_id}") def update_student(student_id: int, student: Student): student_update = Student.objects.get(id=student_id) student_update.name = student.name student_update.age = student.age student_update.sex = student.sex student_update.address = student.address student_update.save() return student_update @router.delete("/students/{student_id}") def delete_student(student_id: int): student = Student.objects.get(id=student_id) student.delete() return {"message": "删除成功!"}
model/student.py
from mongoengine import Document, StringField, IntField class Student(Document): name = StringField(required=True) age = IntField(required=True) sex = StringField(required=True) address = StringField(required=True)
from fastapi import FastAPI from routers.admin import router app = FastAPI() app.include_router(router)
-
gao55pan说:
用python的fastapi框架构建一套学生信息管理系统,mysql学生信息表有name,age,sex,address这四个字段,要求可以通过admin后台管理界面实现对学生信息的增删改查,要求目录结构合理,请给出每个文件的完整代码
1. 项目初始化
# 创建项目 mkdir student_info_system cd student_info_system # 创建虚拟环境 python -m venv venv # 激活虚拟环境 source venv/bin/activate # 安装依赖 pip install fastapi pydantic # 创建目录结构 mkdir app touch app/main.py touch app/__init__.py mkdir app/admin touch app/admin/__init__.py touch app/admin/routes.py # 创建数据库 # 这里以mysql为例 # 创建表 CREATE TABLE student_info ( name varchar(20) NOT NULL, age int(4) NOT NULL, sex varchar(2) NOT NULL, address varchar(50) NOT NULL ); # 插入一些测试数据 INSERT INTO student_info (name, age, sex, address) VALUES ('张三', 20, '男', '北京市朝阳区');
2. 创建Model
# app/admin/models.py from pydantic import BaseModel class StudentModel(BaseModel): name: str age: int sex: str address: str
3. 创建路由
# app/admin/routes.py from fastapi import APIRouter from app.admin.models import StudentModel router = APIRouter() @router.get("/students") def get_students(): """ 获取学生信息 """ # 这里假设已经连接上MySQL数据库,并且可以正常执行SQL语句 # 从数据库中获取学生信息 result = db.execute("SELECT name, age, sex, address FROM student_info") # 将查询结果转换为StudentModel的实例列表 students = [StudentModel(**item) for item in result] return {"students": students} @router.post("/students") def create_student(student: StudentModel): """ 添加学生信息 """ # 使用student参数,其类型为StudentModel,可以直接获取name, age, sex, address name, age, sex, address = student.name, student.age, student.sex, student.address # 执行SQL语句,将数据插入到数据库 db.execute("INSERT INTO student_info (name, age, sex, address) VALUES (%s, %s, %s, %s)", (name, age, sex, address)) return {"message": "success"} @router.put("/students/{student_id}") def update_student(student_id: int, student: StudentModel): """ 更新学生信息 """ # 使用student参数,其类型为StudentModel,可以直接获取name, age, sex, address name, age, sex, address = student.name, student.age, student.sex, student.address # 执行SQL语句,更新学生信息 db.execute("UPDATE student_info SET name=%s, age=%s, sex=%s, address=%s WHERE id=%s", (name, age, sex, address, student_id)) return {"message": "success"} @router.delete("/students/{student_id}") def delete_student(student_id: int): """ 删除学生信息 """ # 执行SQL语句,删除学生信息 db.execute("DELETE FROM student_info WHERE id=%s", student_id) return {"message": "success"}
4. 创建入口
# app/main.py from fastapi import FastAPI from app.admin.routes import router as admin_router app = FastAPI() # 添加管理员路由 app.include_router(admin_router, prefix="/admin")
5. 运行服务
# 运行服务 uvicorn app.main:app --reload