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

相关推荐
用户214118326360221 分钟前
Gemini 3 Pro 来了!一句话生成完整网站,AI编程能力断层领先
后端
码事漫谈1 小时前
Linux开发到底指什么?是什么岗位?做什么的?
后端
码事漫谈1 小时前
Windows开发:一场与指针的共舞,亦是超越它的征程
后端
sanggou1 小时前
【Python爬虫】手把手教你从零开始写爬虫,小白也能轻松学会!(附完整源码)
开发语言·爬虫·python
f***45321 小时前
基于SpringBoot和PostGIS的各省与地级市空间距离分析
android·前端·后端
geng_zhaoying2 小时前
在VPython中使用向量计算3D物体移动
python·3d·vpython
Felix_XXXXL2 小时前
mysql查看binlog日志
java·后端
leonardee2 小时前
Plugin ‘mysql_native_password‘ is not loaded`
java·后端
半tour费2 小时前
TextCNN-NPU移植与性能优化实战
python·深度学习·分类·cnn·华为云
普通网友2 小时前
使用Flask快速搭建轻量级Web应用
jvm·数据库·python