• Python 数据库基类封装


    目录

    1.BaseEntity

    2.t_user

    3.DAOBase

    4.UserDAO


    刚开始用Python做Api后端,记录下学习过程

    从数据库操作开始,定义实体,定义DAO层基类,及DAO业务类的使用

    写的不好,有好的设计建议欢迎大家提出,一起学习进步

    1.BaseEntity

    这部分是实体的基类,比较简单,就一个使用类名作为表名的方法

    1. from sqlalchemy import Column, Integer, DateTime, modifier
    2. from sqlalchemy.orm import InstrumentedAttribute, properties
    3. from sqlalchemy.sql import func
    4. from sqlalchemy.ext.declarative import as_declarative, declared_attr
    5. @as_declarative()
    6. class BaseEntity:
    7. @declared_attr
    8. def __tablename__(cls) -> str:
    9. # 如果没有指定__tablename__ 则默认使用model类名转换表名字
    10. return cls.__name__

    2.t_user

    用户数据表,实体定义,数据库操作的数据依据

    这部分我也写了一个自动生成Entity的小应用程序,欢迎大家下载使用

    https://download.csdn.net/download/rotion135/85124222

    1. from sqlalchemy import Column, Integer, String,Boolean,DateTime,Double,Float
    2. from Modules.db.BaseEntity import BaseEntity
    3. #t_user
    4. class t_user(BaseEntity):
    5. ID = Column(String(32), primary_key=True,nullable=False, comment="表ID")
    6. UserCode = Column(String(32), primary_key=False,nullable=False, comment="用户编码")
    7. UserName = Column(String(128), primary_key=False,nullable=False, comment="用户名称")
    8. LoginName = Column(String(128), primary_key=False,nullable=False, comment="登录名")
    9. Password = Column(String(255), primary_key=False,nullable=False, comment="登录密码")
    10. UserStatus = Column(Integer, primary_key=False,nullable=True, comment="用户状态 默认0:正常,1:禁用 可字典项配置")
    11. IsDelete = Column(Integer, primary_key=False,nullable=True, comment="删除为1,未删除为0,默认0")
    12. Nick = Column(String(128), primary_key=False,nullable=True, comment="昵称")
    13. Title = Column(String(128), primary_key=False,nullable=True, comment="职称")
    14. Sex = Column(Integer, primary_key=False,nullable=True, comment="性别 0:男;1:女")
    15. Birthday = Column(String(32), primary_key=False,nullable=True, comment="生日")
    16. IdentityCard = Column(String(128), primary_key=False,nullable=True, comment="身份证号码")
    17. Mobile = Column(String(32), primary_key=False,nullable=True, comment="手机号")
    18. Telephone = Column(String(32), primary_key=False,nullable=True, comment="电话号码")
    19. QQ = Column(String(32), primary_key=False,nullable=True, comment="QQ号")
    20. Email = Column(String(128), primary_key=False,nullable=True, comment="邮箱")
    21. Signature = Column(String(255), primary_key=False,nullable=True, comment="个性签名")
    22. IsAdmin = Column(Integer, primary_key=False,nullable=True, comment="是否管理员 0-非管理员 1-管理员")
    23. CreateTime = Column(DateTime, primary_key=False,nullable=True, comment="创建时间")
    24. CreateUserCode = Column(String(32), primary_key=False,nullable=True, comment="创建人的用户编码")
    25. ModifyTime = Column(DateTime, primary_key=False,nullable=True, comment="修改时间")
    26. ModifyUserCode = Column(String(32), primary_key=False,nullable=True, comment="修改人的用户编码,只保存最后一次修改人")
    27. Remark = Column(String, primary_key=False,nullable=True, comment="备注")
    28. Token = Column(String(32), primary_key=False,nullable=True, comment="访问令牌")
    29. TokenExTime = Column(DateTime, primary_key=False,nullable=True, comment="访问令牌过期时间")
    30. RefreshToken = Column(String(32), primary_key=False,nullable=True, comment="刷新令牌")
    31. RefreshExTime = Column(DateTime, primary_key=False,nullable=True, comment="刷新令牌过期时间")

    3.DAOBase

    接下来就是设计DAO层的基类

    数据链接 我用了Config.py作为配置文件,在下面一个代码块里边

    1. from sqlalchemy import create_engine, Column, Integer, String,Engine
    2. from sqlalchemy.ext.declarative import declarative_base
    3. from sqlalchemy.orm import sessionmaker,Session
    4. from Modules.SysFrame import Config
    5. class DAOBase():
    6. def __init__(self,db:Session=None):
    7. if(db==None):
    8. self.__InitEngine()
    9. else :
    10. self.session=db
    11. engine:Engine
    12. session:Session
    13. def __InitEngine(self):
    14. # 创建一个引擎来连接到 MySQL 数据库
    15. self.engine = create_engine(Config.MySQLConnection)
    16. # 创建一个会话类
    17. sm = sessionmaker(autocommit=False, autoflush=False, bind=self.engine)
    18. self.session = sm()
    1. cors_allowOrigins="*"
    2. #后台自定义的请求头参数
    3. cors_allowHeaders="Origin,Accept,Accept-Language,Authorization,Content-Type,UserCode,Timestamp,Nonce,Signature"
    4. #请求后台允许的方式
    5. cors_allowMethods="GET, POST, PUT, DELETE, OPTIONS"
    6. #登录限制时间,时间内登录次数超过设置值,则锁定
    7. LoginLimitMinutes=60
    8. #登录限制时间内的登陆错误次数限制
    9. LoginLimitCount=5
    10. #MySQL数据库连接字符串
    11. # 格式为:'数据库类型+数据库驱动名称://用户名:密码@主机地址:端口号/数据库名称'
    12. MySQLConnection="mysql+mysqlconnector://root:123qwe@127.0.0.1:3306/platform"

    4.UserDAO

    最后,展示用户操作类的视线

    BaseResult 是我自己定义的一个结果类,也放在下面代码块了

    1. from datetime import datetime
    2. from sqlalchemy import func,text
    3. from sqlalchemy.orm import sessionmaker
    4. from Modules.Models.BaseResult import BaseResult
    5. from Modules.db.DAOBase import DAOBase
    6. from Modules.db.Entity.t_user import t_user
    7. class UserDAO(DAOBase):
    8. def __init__(self, db: sessionmaker = None):
    9. super().__init__(db)
    10. # 根据用户编码获取用户数据
    11. def GetUserByUserCode(self,userCode:str)->t_user:
    12. sql = self.session.query(t_user).filter(t_user.UserCode==userCode).first()
    13. return sql;
    14. # 根据登录名获取用户数据
    15. def GetUserByLogin(self,loginName:str)->t_user:
    16. sql = self.session.query(t_user).filter(t_user.LoginName==loginName).first()
    17. return sql;
    18. # 新增前检测 true-正常,可新增 false-已存在相同数据
    19. def CheckBeforeInsert(self,userCode:str)->BaseResult:
    20. row_count = self.session.query(func.count(t_user.ID)).filter(t_user.UserCode==userCode).scalar()
    21. if(row_count <= 0):
    22. return BaseResult.Success
    23. else:
    24. return BaseResult.Failure
    25. # 新增用户
    26. def Insert(self,entity:t_user)->BaseResult:
    27. self.session.add(entity)
    28. self.session.commit()
    29. return BaseResult.Success
    30. # 更新用户
    31. def Update(self,entity:t_user,userCode:str)->BaseResult:
    32. user = self.session.query(t_user).filter(t_user.UserCode == entity.UserCode).first()
    33. user.UserName = entity.UserName;
    34. user.Birthday = entity.Birthday;
    35. user.IdentityCard = entity.IdentityCard;
    36. user.Email = entity.Email;
    37. user.Mobile = entity.Mobile;
    38. user.Nick = entity.Nick;
    39. user.QQ = entity.QQ;
    40. user.Sex = entity.Sex;
    41. user.Signature = entity.Signature;
    42. user.Telephone = entity.Telephone;
    43. user.Title = entity.Title;
    44. user.ModifyTime = datetime.now();
    45. user.ModifyUserCode = userCode;
    46. self.session.commit()
    47. return BaseResult.Success
    48. # 判断用户是否有此权限
    49. def JudgeUserPermit(self,type:str, method:str, userCode:str)->BaseResult:
    50. sql = text(f"select COUNT(1) FROM t_permission WHERE ResType='{type}' and ResMethod='{method}' and PermitCode in (SELECT PermitCode FROM t_rolepermission WHERE RoleCode in (SELECT RoleCode FROM t_userrole WHERE UserCode='{userCode}'))");
    51. result = self.engine.execute(sql)
    52. count = result.fetchone()[0]
    53. if(count > 0):
    54. return BaseResult.Success
    55. else:
    56. return BaseResult.Failure
    1. class BaseResult():
    2. def __init__(self,isSucessed:bool,message:str,mark=0,tag=None,total=0):
    3. self.IsSucessed=isSucessed
    4. self.Message=message
    5. self.Mark=mark
    6. self.Tag=tag
    7. self.Total=total
    8. IsSucessed:bool
    9. Message:str
    10. Mark:int
    11. Tag:any
    12. Total:int
    13. @staticmethod
    14. def Success():
    15. res=BaseResult(True,"Success")
    16. return res
    17. @staticmethod
    18. def Failure():
    19. res=BaseResult(True,"Failure")
    20. return res

  • 相关阅读:
    [附源码]java毕业设计网上花店系统
    亨元模式 结构型模式之六
    java发送邮件
    Symfony 简介
    新版软考高项试题分析精选(一)
    【wms平台化】一个简单的wms十表架构
    go语言基础---8
    JavaScript系列之内置对象set
    C++中的内存管理
    构建可视化工具选择策略
  • 原文地址:https://blog.csdn.net/rotion135/article/details/138160520