FastAPI 结合 SQLAlchemy 操作 MySQL 数据库
生活随笔
收集整理的這篇文章主要介紹了
FastAPI 结合 SQLAlchemy 操作 MySQL 数据库
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1. 安裝 SQLAlchemy
- 2. 創(chuàng)建數據庫
- 3. SQLAlchemy 連接 MySQL
- 4. 創(chuàng)建數據模型
- 5. 創(chuàng)建 Pydantic 模型
- 6. crud 工具
- 7. main函數
learning from 《python web開發(fā)從入門到精通》
1. 安裝 SQLAlchemy
- pip install sqlalchemy
2. 創(chuàng)建數據庫
- mysql -u root -p 命令行登錄 MySQL
創(chuàng)建數據庫 fastapi_db
mysql> create database fastapi_db default charset utf8mb4 collate utf8mb4_unicode_ci; Query OK, 1 row affected (0.04 sec)3. SQLAlchemy 連接 MySQL
- database.py
4. 創(chuàng)建數據模型
- models.py
relationship 還不懂,有待學習 SQLAlchemy
5. 創(chuàng)建 Pydantic 模型
- schemas.py
6. crud 工具
- crud.py
7. main函數
from typing import Listfrom fastapi import Depends, FastAPI, HTTPException from sqlalchemy.orm import Sessionfrom . import crud, models, schemas from .database import SessionLocal, enginemodels.Base.metadata.create_all(bind=engine)app = FastAPI()# 依賴 def get_db():try:db = SessionLocal()yield dbfinally:db.close()@app.post("/users/", response_model=schemas.User) def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):# 根據email查找用戶db_user = crud.get_user_by_email(db, email=user.email)# 如果用戶存在,提示該郵箱已經被注冊if db_user:raise HTTPException(status_code=400, detail="Email already registered")# 返回創(chuàng)建的user對象return crud.create_user(db=db, user=user)@app.get("/users/", response_model=List[schemas.User]) def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):# 讀取指定數量用戶users = crud.get_users(db, skip=skip, limit=limit)return users@app.get("/users/{user_id}", response_model=schemas.User) def read_user(user_id: int, db: Session = Depends(get_db)):# 獲取當前id的用戶信息db_user = crud.get_user(db, user_id=user_id)# 如果沒有信息,提示用戶不存在if db_user is None:raise HTTPException(status_code=404, detail="User not found")return db_user@app.post("/users/{user_id}/items/", response_model=schemas.Item) def create_item_for_user(user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) ):# 創(chuàng)建該用戶的itemsreturn crud.create_user_item(db=db, item=item, user_id=user_id)@app.get("/items/", response_model=List[schemas.Item]) def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):# 獲取所有itemsitems = crud.get_items(db, skip=skip, limit=limit)return items (pt19) D:\web_python_dev>uvicorn fastapi_mysql.main:app --reload INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) INFO: Started reloader process [6988] using watchgod INFO: Started server process [2112] INFO: Waiting for application startup. INFO: Application startup complete. mysql> use fastapi_db Database changed mysql> show tables; +----------------------+ | Tables_in_fastapi_db | +----------------------+ | items | | users | +----------------------+ 2 rows in set (0.00 sec)
在網頁里發(fā)送一個 post 請求后,查詢 sql
總結
以上是生活随笔為你收集整理的FastAPI 结合 SQLAlchemy 操作 MySQL 数据库的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 天池 在线编程 有序队列
- 下一篇: LeetCode 1954. 收集足够苹