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 分钟前
AI 生成 PPTX:11 页课件编译出 429 个形状
javascript·python·pptx·ai生成ppt·ooxml
leisoo80973 分钟前
股票筹码分布怎么用获利比例成本区间与集中度实战 IG50免费开源股票数据API接口
开发语言·jvm·数据库·python·开源
ControlM4 分钟前
从官方 CDN 里扒出 TRAE (TraeCode) 历史版本安装包
python·逆向·trae
tianyuanwo6 分钟前
Python 属性查找陷阱:从 `AttributeError: ‘X‘ object has no attribute ‘_children‘` 说起
python
程序猿阿森13 分钟前
混合精度详解:FP16 vs BF16,Loss Scaling 与 PyTorch 实战
人工智能·pytorch·python
benchmark_cc15 分钟前
A股、港股、美股日K如何拼接?处理不同交易日造成的时间轴错位
大数据·python·pandas·量化交易·股票数据·quantdash
行者全栈架构师20 分钟前
从 55% 到 6%:一个快餐营养规划器的算法迭代实录
后端·算法·架构
龙腾-虎跃25 分钟前
AI-Vue3-python-flask-Blog 全栈博客项目深度解析:从零搭建你的 AI 博客
人工智能·python·flask
余槐i26 分钟前
无慢查询 RT 却飙升:cProfile 定位 FastAPI 事件循环阻塞
后端·python·性能优化·fastapi·asyncio
AINative软件工程34 分钟前
LLM 应用的 Adaptive Batching 工程实践:动态合批把吞吐提升 3 倍,但延迟的坑你踩过吗
后端·llm·ai编程