python实战fastapi(三) 创建ORM
1 安装sqlalchemy
pip install sqlalchemy==1.4.18
2 安装pymysql
pip install pymysql==1.0.2
3 创建models
from database import Base
from sqlalchemy import Column, String, Integer, Float, DateTime, ForeignKey
from sqlalchemy.orm import relationship
import datetime
# 导入数据库基类
# 导入常用字段,类型,外键
# 导入关系
# 作者表
class Author(Base):
__tablename__ = "author"
id = Column(Integer, primary_key=True, index=True)
username = Column(String(32), index=True)
email = Column(String(32))
# relation反向查找,这里相当于通过author查book,所以这里是用class name "Book",而不是表名,这是orm的功能
author_to_book = relationship("Book", backref="book_to_author")
class Book(Base):
__tablename__ = "book"
id = Column(Integer, primary_key=True, index=True)
title = Column(String(32))
price = Column(Float)
publish_date = Column(DateTime, default=datetime.datetime.now())
# 外键关联
auth_id = Column(Integer, ForeignKey("author.id"))
class Publish(Base):
__tablename__ = "publish"
id = Column(Integer, primary_key=True, index=True)
name = Column(String(32))
publish_to_book = relationship("Book", backref="book_to_publish", secondary="math")
class Match(Base):
__tablename__ = "match"
id = Column(Integer, primary_key=True, index=True)
publish_id = Column(Integer, ForeignKey("publish.id"))
book_id = Column(Integer, ForeignKey("book.id"))
4 创建数据库连接
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.engine import create_engine
# 数据库基类
Base = declarative_base()
DATABASE_URL = "mysql+pymysql://root:damon123@8.134.213.73:3308/fastapi-db"
engine = create_engine(DATABASE_URL, encoding="utf8", echo=True)
# SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False)
5 引入main
from fastapi import FastAPI
import uvicorn
from database import engine
import models
models.Base.metadata.create_all(bind=engine)
app = FastAPI()
@app.get("/")
async def home():
return {"username": "hello world!"}
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
uvicorn.run(app=app, host="127.0.0.1", port=8030)
# See PyCharm help at https://www.jetbrains.com/help/pycharm/