sqlalchemy 在 flask 中使用 保证 session 不过期

重点在函数中建 engine

在外部声明基类和模型

python 复制代码
Base = declarative_base()

class User(Base):
    __tablename__='users'  # 数据库的表名
    id = Column(Integer,primary_key=True,autoincrement=True) # 主键;自增(默认就是True)
    name = Column(String(32),nullable=False)  # 不为空
    email = Column(String(32),unique=True)  # 唯一
    ctime = Column(DateTime,default=datetime.datetime.now) # 默认值
    extra = Column(Text) # 大文本
python 复制代码
def create_table():
    engine = create_engine(
        'mysql+pymysql://root:root@127.0.0.1:3306/test?charset=utf8',
        max_overflow=0,
        pool_size=5,
        pool_timeout=30,
        pool_recycle=-1
    )
    Base.metadata.create_all(engine) # 通过engine对象创建
python 复制代码
作者:Py应用领域
链接:https://www.zhihu.com/question/42240205/answer/2335079369
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

import datetime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import  Column,Integer,String,Text,ForeignKey,DateTime,UniqueConstraint,Index
from sqlalchemy import create_engine

#1.创建一个类作为所有模型类的基类
Base = declarative_base()

class User(Base):
    __tablename__='users'  # 数据库的表名
    id = Column(Integer,primary_key=True,autoincrement=True) # 主键;自增(默认就是True)
    name = Column(String(32),nullable=False)  # 不为空
    email = Column(String(32),unique=True)  # 唯一
    ctime = Column(DateTime,default=datetime.datetime.now) # 默认值
    extra = Column(Text) # 大文本

#2.创建表
def create_table():
    engine = create_engine(
        'mysql+pymysql://root:root@127.0.0.1:3306/test?charset=utf8',
        max_overflow=0,
        pool_size=5,
        pool_timeout=30,
        pool_recycle=-1
    )
    Base.metadata.create_all(engine) # 通过engine对象创建表,只要是继承Base的类,都会被创建出来表

#3.删除表
def drop_table():
    engine = create_engine(
        'mysql+pymysql://root:root@127.0.0.1:3306/test?charset=utf8',
        max_overflow=0,
        pool_size=5,
        pool_timeout=30,
        pool_recycle=-1
    )
    Base.metadata.drop_all(engine) # 通过engine对象删除表,只要是Base管理的表,都会被删除

if __name__ == '__main__':
    # create_table()
    drop_table()

#存在问题:sqlachemy不支持创建数据库和修改表字段

参考
https://www.zhihu.com/question/42240205

相关推荐
站大爷IP40 分钟前
Python的浅拷贝把我坑惨了,原来copy()和deepcopy()的区别这么大
后端
爱吃苹果的梨叔41 分钟前
2026年指挥中心分布式坐席怎么选?清虹创智让多系统、多坐席和大屏真正协同
python
起予者汝也1 小时前
Python 数据结构
开发语言·数据结构·python
LadenKiller1 小时前
2026年量化工具增量,放回回测模拟实盘阶段判断
人工智能·python
石一峰6991 小时前
驱动:私有数据为什么要在三个地方各挂一遍?
数据库·python·算法
2601_956319881 小时前
最新量化软件怎么选,先按能力短板匹配工具类型
人工智能·python
卷无止境1 小时前
Apache Ossie:打破数据孤岛的语义互操作标准
后端·数据分析
晓杰在写后端1 小时前
从0到1实现Balatro游戏后端(11):商店商品池与运行时商品实例生成
后端·游戏开发
Tbisnic2 小时前
26.AI大模型:RNN、LSTM、GRU
人工智能·python·rnn·gru·大模型·llm·lstm
七夜zippoe2 小时前
OpenClaw 实战:智能文档助手——从问答到生成的完整方案
人工智能·python·机器学习·openclaw·智能文档