已有資料庫情況下使用Python進行ORM操作

2021-12-31 測試遊記
現狀

在實際測試中發現,需要插入大量的測試數據或者有依賴關係的數據 來達到測試的目的,這時我們可以使用python來簡化和規範化該操作。

採用 peewee 來將SQL代碼轉化為Python代碼實現ORM

peewee 是一個輕量級的 python ORM 庫。內建對 SQLite、MySQL 和 PostgreSQL 的支持

peewee文檔地址:

http://docs.peewee-orm.com/en/latest/

中文版文檔:

https://www.osgeo.cn/peewee/

生成數據模型

在安裝peewee後可以在命令行中輸入指令,快速的將已有的資料庫轉化成數據模型

python -m pwiz -e 資料庫類型 -p 埠 -u 帳號 -H IP位址 --password 密碼 -o -i 庫名 > 生成的py文件名.py

例如

python -m pwiz -e mysql -p 3306 -u doctor_core -H 資料庫ip --password 資料庫密碼 -o -i 資料庫帳號 > 導出的文件.py

查看doctor_info表

-- auto-generated definition
create table doctor_info
(
    id                      bigint(22) unsigned auto_increment comment '主鍵'
        primary key,
    user_id                 bigint unsigned                not null comment '用戶編號',
    login_id                varchar(128)                   null comment '登錄名',
    mobile_no               varchar(11)                    null comment '手機號碼',
    telephone_no            varchar(50)                    null comment '醫生固話',
    title_name              varchar(200)                   null comment '行政職稱名',
    dept_uuid               varchar(40)                    null comment '科室uuid',
    dept_name               varchar(100)                   null comment '科室名稱',
    hospital_uuid           varchar(40)                    null comment '醫院uuid',
    hospital_name           varchar(100)                   null comment '醫院名稱',
    property                tinyint(1) unsigned            null comment '醫院性質',
    expert_uuid             varchar(45)                    null comment '專家uuid',
    expert_name             varchar(40)                    null comment '專家姓名',
    favorite_dept           varchar(1000)                  null comment '醫生擅長科室,多個以英文逗號分隔',
    job_number              varchar(40)                    null comment '醫院端醫生工號',
    canal_online            tinyint(1) unsigned default 1  null comment '渠道:1為線上,0為線下,2為兼職,3為贈險註冊',
    source                  bigint(11) unsigned            null comment '應用來源',
    reg_type                tinyint(2) unsigned            not null comment '註冊來源: ',
    state                   tinyint(4) unsigned default 0  not null comment '狀態,0:未認證,1:已認證',
    is_close                tinyint(1) unsigned default 1  not null comment ' 0,關閉,1,開通',
    is_deleted              tinyint unsigned    default 0  not null comment '是否刪除',
    gmt_created             datetime                       not null comment '創建時間',
    gmt_modified            datetime                       not null comment '修改時間',
    project_source_id       int                            null comment '對應項目來源表的外鍵',
    source_group_id         bigint                         null comment '來源分組',
    source_group_name       varchar(200)                   null comment '來源分組名稱',
    role_id                 varchar(100)                   null comment '醫生關聯角色',
    grade                   tinyint(3)          default 0  null comment '醫生資質等級',
    is_special              tinyint(2)          default 0  null comment '是否特批醫生',
    relation_state          tinyint(4) unsigned            null comment '關聯狀態',
    relation_remark         varchar(256)                   null comment '關聯備註',
    gmt_relation            datetime                       null comment '關聯時間',
    is_auto_relation        tinyint(1) unsigned            null comment '是否自動關聯',
    supervise_record_status tinyint(2) unsigned default 0  not null comment '監管備案狀態',
    supervise_record_remark varchar(255)        default '' not null comment '監管備案失敗原因',
    constraint uniq_user_id
        unique (user_id)
)
    comment '醫生信息表' charset = utf8;

create index idx_expert_name
    on doctor_info (expert_name);

create index idx_expert_uuid
    on doctor_info (expert_uuid);

create index idx_gmtCreated
    on doctor_info (gmt_created);

create index idx_gmtModified
    on doctor_info (gmt_modified);

create index idx_hospital_uuid_job_number
    on doctor_info (hospital_uuid, job_number);

create index idx_job_number
    on doctor_info (job_number);

create index idx_loginId
    on doctor_info (login_id);

create index idx_mobile_no
    on doctor_info (mobile_no);

查看它轉換後的代碼為:

class DoctorInfo(BaseModel):
    id = BigAutoField()
    user_id = BigIntegerField(unique=True)
    login_id = CharField(index=True, null=True)
    mobile_no = CharField(index=True, null=True)
    telephone_no = CharField(null=True)
    title_name = CharField(null=True)
    dept_uuid = CharField(null=True)
    dept_name = CharField(null=True)
    hospital_uuid = CharField(null=True)
    hospital_name = CharField(null=True)
    property = IntegerField(null=True)
    expert_uuid = CharField(index=True, null=True)
    expert_name = CharField(index=True, null=True)
    favorite_dept = CharField(null=True)
    job_number = CharField(index=True, null=True)
    canal_online = IntegerField(constraints=[SQL("DEFAULT 1")], null=True)
    source = BigIntegerField(null=True)
    reg_type = IntegerField()
    state = IntegerField(constraints=[SQL("DEFAULT 0")])
    is_close = IntegerField(constraints=[SQL("DEFAULT 1")])
    is_deleted = IntegerField(constraints=[SQL("DEFAULT 0")])
    gmt_created = DateTimeField(index=True)
    gmt_modified = DateTimeField(index=True)
    project_source_id = IntegerField(null=True)
    source_group_id = BigIntegerField(null=True)
    source_group_name = CharField(null=True)
    role_id = CharField(null=True)
    grade = IntegerField(constraints=[SQL("DEFAULT 0")], null=True)
    is_special = IntegerField(constraints=[SQL("DEFAULT 0")], null=True)
    relation_state = IntegerField(null=True)
    relation_remark = CharField(null=True)
    gmt_relation = DateTimeField(null=True)
    is_auto_relation = IntegerField(null=True)
    supervise_record_status = IntegerField(constraints=[SQL("DEFAULT 0")])
    supervise_record_remark = CharField(constraints=[SQL("DEFAULT ''")])

    class Meta:
        table_name = 'doctor_info'
        indexes = (
            (('hospital_uuid', 'job_number'), False),
        )

我們使用這段代碼來完成一次CRUD操作

DoctorInfo(user_id=xx,login_id=xx,....).save()

DoctorInfo.delete().where(DoctorInfo.expert_name == '張三').execute()

DoctorInfo.expert_name = '李四'
DoctorInfo.save()

# 方法一
DoctorInfo.get(expert_name='張三')
# 方法二
DoctorInfo.select().where(DoctorInfo.expert_name == '張三').get()

更多操作可以參考官方文檔

相關焦點

  • Python資料庫ORM工具sqlalchemy的學習筆記
    SQLAlchemy是python的一個資料庫ORM工具,提供了強大的對象模型間的轉換,可以滿足絕大多數資料庫操作的需求,並且支持多種資料庫引擎(sqlite,mysql,postgres, mongodb等),在這裡記錄基本用法和學習筆記
  • 如何修復使用 Python ORM 工具 SQLAlchemy 時的常見陷阱 | Linux 中國
    對象關係映射Object-relational mapping(ORM)使應用程式開發人員的工作更輕鬆,在很大程度是因為它允許你使用你可能知道的語言(例如 Python)與資料庫交互,而不是使用原始 SQL 語句查詢。SQLAlchemy 是一個 Python ORM 工具包,它提供使用 Python 訪問 SQL 資料庫的功能。
  • python對mysql資料庫的操作(一)
    本文章介紹python對mysql資料庫的基本操作,以及編寫一個模擬用戶的註冊。
  • Python 資料庫騷操作 -- MySQL
    ,前面兩篇分別是:《Python 資料庫騷操作 -- MongoDB》《Python 資料庫騷操作 -- Redis》,這篇主要介紹 MySQL 的 orm 庫 SQLAlchemy 。那什麼是 orm 呢?Object Relational Mapper,描述程序中對象和資料庫中數據記錄之間的映射關係的統稱。介紹完了,那就走起唄!MySQL GUI 工具首先介紹一款 MySQL 的 GUI 工具 Navicat for MySQL,初學 MySQL 用這個來查看數據真的很爽。可以即時看到數據的增刪改查,不用操作命令行來查看。
  • Python 操作MySQL資料庫
    Python 使用操作MySQL第一步:
  • Python數據科學實踐 | 資料庫1
    資料庫永遠是數據管理上最值得使用的工具。而把所收集的大量數據放入資料庫之後再處理是數據科學實踐項目中必不可少的一步。通過前面章節的學習,我們已經掌握了利用Python分析數據的眾多模塊,特別地也展示了如何利用爬蟲技術爬取本書中最常使用的火鍋團購數據的全過程。本章假設的分析場景是火鍋團購數據被爬取後,由於數據量過大已經進入資料庫保存。
  • 使用Python操作SQL Server資料庫
    先說一下SQL Server如果有條件可以使用遠程連接或者TeamViewer等工具,操作帶GUI的資料庫管理器,實施起來可以很省心。可以直接查看結果,模板化查詢甚至提示語句錯誤等。如果是使用linux本地或者ssh訪問SQL Server資料庫的,稍微麻煩點。可以使用sqlcmd作為替代工具。後面會介紹。
  • Python操作Redis
    Part1前言前面我們都是使用 Redis 客戶端對 Redis 進行使用的,但是實際工作中,我們大多數情況下都是通過代碼來使用 Redis 的,由於小編對 Python 比較熟悉,所以我們今天就一起來學習下如何使用 Python 來操作 Redis。Part2環境準備Python 安裝好(建議使用 Python3)。
  • 使用python連接MySQL資料庫
    第二階段介紹將爬去的數據寫入MySQL資料庫的過程。1,使用python抓取並提取數據第一階段介紹數據爬取過程,首先導入所需的庫文件,主要包括requests,re和pandas三個庫。具體作用在注釋中進行了說明,這裡不再贅述。
  • Python的輕量級ORM框架peewee
    在前文中,我介紹了使用metaclass自己編寫ORM框架的思路。當然python庫中這類框架非常多,我們並沒有必要自己去實現。ORM框架使用最廣泛的就是SQLAlchemy和Django自帶的ORM框架,但是SQLAlchemy的語法顯然相對Django的ORM框架麻煩一點。而Django本身是一個web框架,比較重量級,僅僅為了使用Django的ORM框架的功能,而安裝Django有點導致系統臃腫。
  • 用 Python 連接 MySQL 的幾種姿勢
    作者:劉志軍,6年+Python使用經驗, 高級開發工程師,目前在網際網路醫療行業從事Web系統構架工作個人公眾號:Python
  • python操作Power Point:使用演示文稿
    上節簡單介紹了PPT的python大法,這節開始詳細介紹如何在python裡調用打開和使用PPT文檔。python操作Power Point:使用演示文稿使用演示文稿python-pptx允許您創建新的演示文稿以及對現有演示文稿進行更改。實際上,它只允許您更改現有演示文稿; 只是如果你從一個沒有任何幻燈片的演示文稿開始,它首先感覺就像你從頭開始創建一個幻燈片。
  • SQLAlchemy 1.3.8 發布,Python ORM 框架
    SQLAlchemy 是一個 Python 的 SQL 工具包以及資料庫對象映射(ORM)框架。它包含整套企業級持久化模式,專門用於高效和高性能的資料庫訪問。新版本包含對新的 psycopg2 「執行值」性能的修復,以適應由編譯器掛鈎修改的 INSERT 語句。
  • 樹莓派使用 Python + SQLite 建立溫度資料庫
    本文使用Python向SQLite資料庫中插入樹莓派溫度數據,SQLite資料庫中包含一張只包含三個欄位的記錄表——參數名稱,時間和溫度值。本文重點解釋Python操作SQlite的具體方法,由於網上資料眾多,重複部分不再複述只做到具體情況具體分析。
  • 我的實戰經驗分享:深入淺出Python資料庫操作
    使用模式基本上離不開這3步:· 連接資料庫· 操作數據· 斷開資料庫我們這裡演示只演示把數據存入sqlite資料庫文件的話,也不外乎是這3步,只是其中多了一個叫「遊標(Cursor)」的東東。遊標就像「指針」,增刪改查都靠它!
  • 如何用Python操作資料庫
    'localhost'參數port:連接的mysql主機的埠,默認是3306參數db:資料庫的名稱參數user:連接的用戶名參數password:連接的密碼參數charset:通信採用的編碼方式,默認是'gb2312',要求與資料庫創建時指定的編碼一致,否則中文會亂碼3.對象的方法 Cursor對象
  • 你的第一份Python庫源碼閱讀:records
    基本介紹records是kennethreitz的for Humans系列,使用原生sql去操作大多數的關係型資料庫(Postgresql, MySQL, SQLite, Oracle和 MS-SQL),並且支持多種格式輸出,如csv、excel
  • 如何使用PyMySQL操作mysql資料庫?
    ,比如MySQL,這裡我來分享下簡單的Python操作MySQL的庫pymysql。適用環境python版本 >=2.6或3.3mysql版本>=4.1安裝可以使用pip安裝也可以手動下載安裝。
  • Python 實現 Redis ORM
    我們希望在我們的應用程式中具有以下能力:存儲問題列表並檢索根據 id 檢索問題存儲選項關聯問題與選項列表將問題與選項取消關聯檢索一個問題的所有選項跟蹤一個選項的投票數我們希望將 Redis 作為我們的資料庫使用。
  • Django ORM 簡介
    Django 的一個強大的功能是它的對象關係映射Object-Relational Mapper(ORM),它允許你就像使用 SQL 一樣去和你的資料庫交互。事實上,Django 的 ORM 就是創建 SQL 去查詢和操作資料庫的一個 Python 式方式,並且獲得 Python 風格的結果。