Fastapi教程三:项目妹子图(2)-数据库搭建

in fastapi with 1 comment

一、数据库构建
首先安装sqlalchemy和mysqlconnector(pymysql也可)
创建core/database.py:

import uuid

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

SQLALCHEMY_DATABASE_URL = "mysql+mysqlconnector://用户名:密码@127.0.0.1:3306/数据库名?charset=utf8mb4"
# 注意,如果你用pymysql连接的话,mysql+mysqlconnector:改成mysql+pymsql:

engine = create_engine( SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

#这个返回UUID字符函数,用来给模型默认UUID字段的
def generate_uuid():
    return str(uuid.uuid4())

#创建数据库连接池,注意python3.7以上支持异步,如果是3.6还要安装async-exit-stack和async-generator库
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

二、创建数据库模型.
创建apps/users/models.py:

from datetime import datetime
import binascii

from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, Text, DateTime
from sqlalchemy.sql import func


from core.database import Base, generate_uuid
from extensions.fastapi_password  import set_password, check_password
#这里是自己编写的brcypt的加密密码和比如密码的函数,暂时不管他,后面贴出来。


class User(Base):

    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    uuid = Column(String(100), name="uuid", default=generate_uuid, unique=True)
    username = Column(String(30), unique=True, index=True)
    password = Column(String(200))

    email = Column(String(30), unique=True, index=True)
    name = Column(String(30),  index=True)
    address = Column(Text() )
    company = Column(String(130),  nullable=True)
    department = Column(String(120),  nullable=True)

    last_session_key = Column(String(200),  nullable=True)
                            
    is_active = Column(Boolean, default=True)
    is_super =Column(Boolean, default=False) 

    def to_dict(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}
    
    #保存密码使用set_password,加密密码
    def set_password(self, password):
        self.password = set_password(password)
    
    #check_password比对密码,返回True or False
    def check_password(self,  password):
        return  check_password(self.password, password)

创建表:
在main.py中加入:

import uvicorn
from core import get_app
+from core.database import engine

+from apps.users import models as users_model



app = get_app()

+users_model.Base.metadata.create_all(bind=engine)


if __name__ == "__main__":
    uvicorn.run(app="main:app", host="0.0.0.0", port=3200, reload=True, debug=True)

再次执行python main.py,数据库表就创建成功了!
下一节,我们继续讲user模型的增删改查以的API创建。

Comments are closed.