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

相关推荐
嘻嘻嘻开心1 天前
Collection接口
linux·windows·python
IT 行者1 天前
Spring Security 7.0 新特性详解
java·后端·spring
rebekk1 天前
什么时候会用到python -m
python
华仔啊1 天前
Java 的金额计算用 long 还是 BigDecimal?资深程序员这样选
java·后端
是喵斯特ya1 天前
python开发web暴力破解工具(进阶篇 包含验证码识别和token的处理)
开发语言·python·web安全
长安牧笛1 天前
职业技能学习路径规划工具,用户输入目标岗位,如AI工程师,结合现有技能水平,推荐分阶段学习资源(课程/书籍/项目),设置学习进度提醒。
python
长安牧笛1 天前
智能衣柜—穿搭助手,内置温湿度传感器,潮湿天气启动除湿功能,防止衣服发霉,APP还能记录衣服穿着频率,推荐久没穿的衣服,避免穿搭重复。
python
free-elcmacom1 天前
机器学习高阶教程<8>分布式训练三大核心策略拆解
人工智能·分布式·python·机器学习
12344521 天前
【MCP入门篇】从0到1教你搭建MCP服务
后端·mcp
okseekw1 天前
Java多线程开发实战:解锁线程安全与性能优化的关键技术
java·后端