FastAPI之连接数据库

1.databases.py

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
SQLALCHEMY_DATABASE_URL = 'mysql+pymysql://username:password@localhost/fastapi_demo'
# 数据库链接:mysql+pymysql://用户名:密码@ip/库名
engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base(

2.models.py

from sqlalchemy import Column, Integer, String, Boolean, DateTime, ForeignKey, Text, Float
from database import Base, engine


class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    username = Column(String(100), unique=True, nullable=False)
    password = Column(String(100), nullable=False)

3.main.py

from database import engine
import models
models.Base.metadata.create_all(engine)
posted on 2023-09-05 16:47  zhangbinn  阅读(8)  评论(0编辑  收藏  举报