fastapi mysql写一个后台管理系统代码示例
时间: 2024-01-31 18:45:22 浏览: 102
好的,以下是一个使用FastAPI和MySQL实现的后台管理系统代码示例:
```
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
import mysql.connector
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
class User(BaseModel):
name: str
age: int
email: str
@app.get("/", response_class=HTMLResponse)
def index(request):
return templates.TemplateResponse("index.html", {"request": request})
@app.post("/add_user/")
def add_user(user: User):
try:
conn = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="database_name"
)
cursor = conn.cursor()
query = "INSERT INTO users (name, age, email) VALUES (%s, %s, %s)"
values = (user.name, user.age, user.email)
cursor.execute(query, values)
conn.commit()
cursor.close()
conn.close()
return {"message": "User added successfully."}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/users/", response_class=HTMLResponse)
def get_users(request):
try:
conn = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="database_name"
)
cursor = conn.cursor()
query = "SELECT * FROM users"
cursor.execute(query)
users = cursor.fetchall()
cursor.close()
conn.close()
return templates.TemplateResponse("users.html", {"request": request, "users": users})
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
```
以上代码实现了两个接口:`/add_user/`用于添加用户,`/users/`用于获取用户列表。其中,数据保存在MySQL数据库中。在使用前请注意修改MySQL连接信息。
阅读全文