当前位置:网站首页>sqlalchemy创建MySQL_Table
sqlalchemy创建MySQL_Table
2022-07-01 07:48:00 【皮卡大人】
python调用数据库经常使用到的第三方包
这里来说一下怎么创建数据库
首先比较关键的是 declarative_base,假定声明性基类。
Representation这个是我自己定义的一个类,是里面可以自己看着需求写好一些方法,数据模型继承后,续开发不需要重复写冗余的代码。
to_dict是为了可以把一个对象装换成字典,也就是数据封装
table_args 是表配置,可以配置引擎,编码,表注释
参考官网: https://www.osgeo.cn/sqlalchemy/orm/declarative_tables.html
from datetime import datetime, date,time
from sqlalchemy import Column, VARCHAR, BIGINT, DATETIME, func
from sqlalchemy.orm import declarative_base
from sqlalchemy import inspect
from etc.common import DATETIME_FORMAT, DATE_FORMAT, TIME_FORMAT
from etc.database import DATABASE_AUTH_CONF_ORIGIN_STR
class Representation(object):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def __repr__(self):
return str(self.to_dict())
def __str__(self):
return str(self.to_dict())
def to_dict(self) -> dict:
""" 转Python字典 :return: Python字典类型的数据库数据 """
dict_ = self.__dict__.copy()
if '_sa_instance_state' in dict_:
del dict_['_sa_instance_state']
if '_updatable' in dict_:
del dict_['_updatable']
dict_ = self.to_format(dict_)
return dict_
def to_format(self, dict_: dict):
""" 把时间格式转换成 :param dict_: 进行时间转换的字典 :return: 字典 """
for item in dict_:
if isinstance(dict_[item], datetime):
dict_[item] = dict_[item].strftime(DATETIME_FORMAT)
elif isinstance(dict_[item], date):
dict_[item] = dict_[item].strftime(DATE_FORMAT)
elif isinstance(dict_[item], time):
dict_[item] = dict_[item].strftime(TIME_FORMAT)
return dict_
@classmethod
def get_attr(cls):
""" :return: """
key_values = [(k, v) for k, v in inspect(cls).c.items()]
return [{
"label": item[0], "prop": item[1].comment} for item in key_values]
Base = declarative_base()
class User(Base, Representation):
__tablename__ = 'user'
__table_args__ = {
'mysql_engine': 'InnoDB',
'mysql_charset': 'utf8mb4',
'mysql_comment': '测试用户表'
}
id = Column(BIGINT, name="id", comment="主键", primary_key=True)
name = Column(VARCHAR(32), nullable=False, name="name", comment="姓名")
update_time = Column(DATETIME, default=func.now(), name="update_time", comment="更新时间,默认现在时间")
if __name__ == '__main__':
from sqlalchemy import create_engine
engine = create_engine(DATABASE_AUTH_CONF_ORIGIN_STR)
Base.metadata.create_all(engine)
边栏推荐
- 关系数据库如何工作
- 三极管是一项伟大的发明
- Why some people earn nearly 10billion a year, while others earn 3000 a month: the details you ignore actually make the most money
- Mysql与Redis一致性解决方案
- Discussion on several research hotspots of cvpr2022
- 【R语言】年龄性别频数匹配 挑选样本 病例对照研究,对年龄性别进行频数匹配
- redisson使用全解——redisson官方文档+注释(中篇)
- C # read and write customized config file
- [Shenzhen IO] precise Food Scale (some understanding of assembly language)
- 微软宣布开源 (GODEL) 语言模型聊天机器人
猜你喜欢

热烈祝贺五行和合酒成功挂牌

Discussion on several research hotspots of cvpr2022

2022茶艺师(初级)操作证考试题库及模拟考试

Stepsister becomes stepmother, son breaks off relationship with himself, and musk, the world's richest man, why is it so miserable?

Introduction to kubernetes resource objects and common commands (II)

2022年流动式起重机司机考试练习题及在线模拟考试

Redisson uses the complete solution - redisson official documents + Notes (Part 1)

How relational databases work
![[target detection] yolov5, the shoulder of target detection (detailed principle + Training Guide)](/img/47/80d2e92ea7347cc5c7410194d5bf2e.png)
[target detection] yolov5, the shoulder of target detection (detailed principle + Training Guide)
![[programming compulsory training 3] find the longest consecutive number string in the string + the number that appears more than half of the times in the array](/img/5e/068268857b8c7c2065ba552fd23dbb.png)
[programming compulsory training 3] find the longest consecutive number string in the string + the number that appears more than half of the times in the array
随机推荐
Caesar
[Shenzhen IO] precise Food Scale (some understanding of assembly language)
[kv260] generate chip temperature curve with xadc
LSTM of RNN
Caesar
Kickback -- find the first palindrome character in a group of characters
[software] phantomjs screenshot
【无标题】
MySQL and redis consistency solution
Subclasses call methods and properties of the parent class with the same name
源代码加密的意义和措施
漏刻有时API接口实战开发系列(14):身份证实名鉴权验证
Atguigu---- scaffold --02- use scaffold (2)
Custom events of components ①
TodoList经典案例①
Do securities account opening affect the security of account opening
vscode 根据 ESLint 规范自动格式化代码
如何使用layui将数据库中的数据以表格的形式展现出来
【目标检测】目标检测界的扛把子YOLOv5(原理详解+修炼指南)
Array: question brushing record