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

相关推荐
扫地僧985几秒前
一个基于 PyTorch 手语翻译模型Xuanmen_Net
人工智能·pytorch·python
zyl837211 分钟前
Python 函数、模块、异常处理 超详细入门教程
开发语言·windows·python
知彼解己6 分钟前
SQLite 核心实战:后端工程师视角
后端·golang·ai编程
IT_陈寒9 分钟前
被Vite的HMR坑惨了,原来这样配置才能用对!
前端·人工智能·后端
凌览18 分钟前
为什么我不推荐一人公司用PostgreSQL
前端·后端·node.js
白狐_79822 分钟前
从功能开发到开源维护:一个 Python 可视化项目的 Git 分支、维护文件与 PR 流程实践
git·python·开源
我是一颗柠檬25 分钟前
【Java后端技术亮点】Feed流三级缓存设计,从10秒到100毫秒的优化实战
java·开发语言·后端·缓存
俊哥工具27 分钟前
不用打开文件也能预览!支持压缩包、PDF、音视频
python·智能手机·django·pdf·计算机外设·virtualenv
JaguarJack29 分钟前
PHP 应用 security.txt 漏洞披露实践
后端·php
码语智行31 分钟前
操作日志注解模块
java·前端·python