falsk中sqlalchemy使用
1、安装sqlalchemy模块
pip install pymysql
pip install SQLAlchemy
2、配置引擎
from sqlalchemy.engine import create_engine
HOSTNAME = '127.0.0.1'
PORT = '3306'
DATABASE = 'my_sql_db'
USERNAME = 'root'
PASSWORD = 'admin@123'
DB_URI = 'mysql+mysqldb://{}:{}@{}:{}/{}'.format(USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE)
# 创建数据库引擎
engine = create_engine(DB_URI, encoding='utf-8', echo=True)
3、申明ORM基类(这个基类的子类会自动和数据库表进行关联)
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base(bind=engine)
4、创建模型表
# 导入列和数据类型
from sqlalchemy import Column
from sqlalchemy.types import Integer, String, Date, DateTime, Float, Text
class User(Base):
# 设置数据库表名
__tablename__ = 'user_info'
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(10), unique=True, nullable=False, verbose_name='用户名')
nick_name = Column(String(32), verbose_name='昵称')
user_mail = Column(String(32), verbose_name='邮箱')
user_phone = Column(String(20), verbose_name='手机号')
signature = Column(String(128), verbose_name='签名')
avatar = Column(String(200), verbose_name='头像')
roles = Column(String(20), verbose_name='角色', default=1)
5、创建session会话
DBSession = sessionmaker(bind=engine)
session = DBSession()
6、工程参考目录