当前位置:网站首页>Sqlalchemy creating MySQL_ Table
Sqlalchemy creating MySQL_ Table
2022-07-01 07:52:00 【Lord pickup】
python Call the third-party package frequently used by the database
Here is how to create a database
First of all, the key is declarative_base, Suppose the declarative base class .
Representation This is a class defined by myself , You can write some methods according to the requirements , After data model inheritance , Continuous development does not need to write redundant code repeatedly .
to_dict In order to replace an object with a dictionary , That is, data encapsulation
table_args Is table configuration , The engine can be configured , code , Table annotation
Refer to the official website : 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:
""" turn Python Dictionaries :return: Python Dictionary type database data """
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):
""" Convert the time format into :param dict_: A dictionary for time conversion :return: Dictionaries """
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': ' Test user table '
}
id = Column(BIGINT, name="id", comment=" Primary key ", primary_key=True)
name = Column(VARCHAR(32), nullable=False, name="name", comment=" full name ")
update_time = Column(DATETIME, default=func.now(), name="update_time", comment=" Update time , Default present time ")
if __name__ == '__main__':
from sqlalchemy import create_engine
engine = create_engine(DATABASE_AUTH_CONF_ORIGIN_STR)
Base.metadata.create_all(engine)
边栏推荐
- 2022 mobile crane driver test exercises and online simulation test
- 力扣每日一题-第31天-202.快乐数
- 【mysql学习笔记28】存储函数
- [MySQL learning notes 28] storage function
- How to make the two financial transactions faster
- Implementation and encapsulation of go universal dynamic retry mechanism
- 关系数据库如何工作
- Array: question brushing record
- LSTM of RNN
- [R language] age sex frequency matching select samples for case-control study, and perform frequency matching on age and sex
猜你喜欢

Gui Gui programming (XV) - use scale to control font size changes

Illusory and simple screen raindrop post-processing effect

The triode is a great invention

【批处理DOS-CMD命令-汇总和小结】-Cmd窗口中常用操作符(<、<<、&<、>、>>、&>、&、&&、||、|、()、;、@)

2022电工(中级)复训题库及答案

Thesis learning -- Analysis and Research on similarity query of hydrological time series

Introduction to kubernetes resource objects and common commands (II)

I bet on performance and won the CTO of the company. I want to build Devops platform!

2022 mobile crane driver test exercises and online simulation test

kubernetes资源对象介绍及常用命令(二)
随机推荐
【批处理DOS-CMD-汇总】扩展变量-延迟变量cmd /v:on、cmd /v:off、setlocal enabledelayedexpansion、DisableDelayedExpansion
Apple账号密码自动填充
Illusory and simple screen raindrop post-processing effect
Subclasses call methods and properties of the parent class with the same name
How outlook puts together messages with the same discussion
继妹变继母,儿子与自己断绝关系,世界首富马斯克,为何这么惨?
Li Kou daily question - day 31 -1790 Can a string exchange be performed only once to make two strings equal
H5 页面设置了字体的粗细样式,但是在华为手机里微信打开访问样式不生效?
Alibaba OSS postman invalid according to policy: policy condition failed: ["starts with", "key", "test/"]
Conscience Amway universal wheel SolidWorks model material website
base64
【微服务|openfeign】Feign的日志记录
Li Kou daily question - day 31 -202 Happy number
论文学习——水文时间序列相似性查询的分析与研究
MySQL and redis consistency solution
良心安利万向轮 SolidWorks模型素材网站
【mysql学习笔记27】存储过程
[skill] create Bat quick open web page
[batch dos-cmd command - summary and summary] - Common operators in the CMD window (<, < <, & <,>, > >, & >, & >, & &, ||, (),;, @)
Li Kou daily question - day 31 -1502 Judge whether an arithmetic sequence can be formed