首页 > 数据库 >python FastAPI sqlalchemy 数据库模型基类通用模型

python FastAPI sqlalchemy 数据库模型基类通用模型

时间:2023-03-08 17:59:04浏览次数:36  
标签:account sqlalchemy python 模型 db Column dict import self

作用

用于所有表都需要使用的字段或者方法

实现代码

base.py

#!/usr/bin/python
# -*- coding: utf-8 -*-
# @time    : 2023/2/13 17:43 
# @author  : pugongying
# @description :
from sqlalchemy import Column, Integer, String, func, DateTime
from sqlalchemy.orm import Session

from app.dbs.database import Base


class BaseModel(Base):
    __abstract__ = True  #设置为可继承的基础模型,不创建表
    id = Column(Integer, primary_key=True, autoincrement=True, comment='id')
    date_created = Column(DateTime(timezone=True), default=func.now(), comment='创建时间')
    last_updated = Column(DateTime(timezone=True), default=func.now(), onupdate=func.now(), comment='修改时间')

    def to_dict(self):
        model_dict = dict(self.__dict__)
        del model_dict['_sa_instance_state']
        return model_dict

    Base.to_dict = to_dict  # 注意:这个跟使用flask_sqlalchemy的有区别

    # 单个对象方法2
    def single_to_dict(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}

    # 多个对象
    def dobule_to_dict(self):
        result = {}
        for key in self.__mapper__.c.keys():
            if getattr(self, key) is not None:
                result[key] = str(getattr(self, key))
            else:
                result[key] = getattr(self, key)
        return result

    # 配合多个对象使用的函数
    @staticmethod
    def to_json(all_vendors):
        v = [ven.dobule_to_dict() for ven in all_vendors]
        return v

    @staticmethod
    def bulks_update(db: Session, modelclass, listdict):
        """
        modelclass: 模型名称
        listdict: list[dict]
        """
        # print(db, modelclass, listdict)
        db.bulk_update_mappings(modelclass, listdict)
        db.commit()

    @staticmethod
    def bulks_insert(db: Session, modelclass, listdict):
        """
        modelclass: 模型名称
        listdict: list[dict]
        """
        db.bulk_insert_mappings(modelclass, listdict)
        db.commit()

user_schemas.py

#!/usr/bin/python
# -*- coding: utf-8 -*-
# @time    : 2023/2/3 17:46 
# @author  : pugongying
# @description : 数据验证模型
from typing import List

from pydantic import BaseModel



class UserTaskAccount(BaseModel):
    username: str
    password: str
    account_ids: List

user.py

#!/usr/bin/python
# -*- coding: utf-8 -*-
# @time    : 2023/3/6 15:49 
# @author  : pugongying
# @description :
from typing import List

from sqlalchemy import Boolean, Column, Integer, String, DateTime, func
from sqlalchemy.orm import Session

from app.models.base import BaseModel
from app.schemas.user_schemas import UserTaskAccount


class UserAccount(BaseModel):
    __tablename__ = "table_ssssss"  # 表名

    account_id = Column(String(100), nullable=False, comment='xxxx')
    username = Column(String(100), nullable=False, comment='xxxx')
    password = Column(String(100), nullable=False, comment='xxxx')
    account_type = Column(Integer, default=1, nullable=False, comment='xxxx')
    deleted = Column(Boolean, default=True, nullable=False, comment='xxxx')
     
    # 定义模型方法,直接调用返回需要的数据
    @staticmethod
    def query_task_account(db: Session, username: int) -> List[UserTaskAccount]:
        result_list = db \
            .query(UserAccount.username,
                   func.min(UserAccount.password),
                   func.array_agg(UserAccount.account_id)) \
            .filter(UserAccount.deleted == False,
                    UserAccount.account_type == account_type) \
            .group_by(UserAccount.username) \
            .all()
        return [UserTaskAccount(username=item[0], password=item[1], account_ids=item[2]) for item in result_list]

标签:account,sqlalchemy,python,模型,db,Column,dict,import,self
From: https://www.cnblogs.com/pgyLang/p/17195544.html

相关文章

  • python 通过API操作阿里云oss
    catpython_oss.py#!/usr/bin/python#-*-coding:utf-8-*-#@time:2023/2/2314:29#@author:pugongying#@description:#pipinstallalibabacloud_os......
  • python 生成器
    生成器生成器是用来生成数据的一个办法yield关键字yield相当于是return,当函数运行到这里之后会暂停,并且返回后面的变量给调用的位置yield是没有返回值的,所以num=yie......
  • 在使用vue2项目中运行 npm install gyp verb check python checking for Python execu
    这个错误是因为在运行npminstall命令时,需要安装某些Node.js模块的本机代码(NativeCode)并编译它们,而这些模块的编译需要使用Python2。解决这个问题的方法是:确认你......
  • python创建线程传参误区记录
    创建线程可以使用threading模块中的Thread方法;其中Thread方法允许的参数如下:(self,group=None,target=None,name=None,args=(),kwargs=None,*,daemon=None)这个构......
  • python基础
    1、type()语句 通过type()语句来得到数据的类型,能查看变量中存储的数据类型。 查看的是:变量储存的数据的类型。因为,变量无类型,但是它存储的数据有。 语法:type(被查......
  • 【流畅的Python0101】Python数据模型
    1.特殊方法示例:一摞Python风格的纸牌importcollectionsCard=collections.namedtuple('Card',['rank','suit'])classFrenchDeck:#Python2中要写成FrenchDeck(......
  • python学习-第三方库综合程序设计实验报告
    目录实验四: Python综合程序设计实验名称:Python综合程序设计              指导教师:      实验日期:2022年 12 月 5 日......
  • 面试官:什么是双亲委派模型?
    本文已经收录进JavaGuide(「Java学习+面试指南」一份涵盖大部分Java程序员所需要掌握的核心知识。)参加过校招面试的同学,应该对这个问题不陌生。一般提问JVM知识点的......
  • linux检测程序运行时间和内存峰值 Python脚本
    #!/usr/bin/envpython3#-*-encoding:utf-8-*-importsubprocessasspimportsysimporttimedefget_mem(pid):c=sp.Popen(['ps','-aux'],stdout=sp......
  • Python学习笔记:str.zfill补全位数
    一、介绍zfill函数用于在字符串的开头添加零,直到达到指定的长度。如果len参数的值小于字符串的长度,则不执行填充。具体使用语法为:str.zfill(len)如果是整型、浮点......