Python 字典或JSON模拟数据库的增删改查

本文主要想法是通过模拟数据库操作,减少服务后端开发起步阶段的工作量,用于API测试。
首先通过python字典类型作为数据表,并在运行中对其进行动态更改。
首先,在单独一个文件中创建字典。

#文件名:fake_database.py
fake_users_table={
     "johndoe": {
        "username": "johndoe",
        "full_name": "John Doe",
        "email": "johndoe@example.com",
        "hashed_password": "fakehashedsecret",
        "disabled": False,
    },
    "alice": {
        "username": "alice",
        "full_name": "Alice Wonderson",
        "email": "alice@example.com",
        "hashed_password": "fakehashedsecret2",
        "disabled": True,
    },
}

然后再另一个文件中创建一个类,引用这个字典。

class fake_db_connect():
    from fake_database import fake_user_table
    def __init__(self):
        pass
    
    def get(self,primaryKey:str)->dict:
    	#查数据,直接按主键查找。
        return self.fake_user_table.get(primaryKey)

    def insert(self,info:dict):
    	#增加数据
        primaryKey=info['username']
        self.fake_user_table[primaryKey]=info

    def delete(self,primaryKey:str):
    	#删除数据
        del self.fake_user_table[primaryKey]
        
    def commit(self):
    	#提交数据更改,将改变内容写入文件
        with open('fake_database.py',mode='w',encoding='utf-8') as f:
            print("fake_user_table=",self.fake_user_table,sep=None,file=f)
            print("插入新信息成功")

下面进行一下测试。


if __name__=="__main__":
    #模拟连接数据库
    table=fake_db_connect()

    #模拟查数据
    user01=table.get('johndoe')
    print(user01)

    #模拟新增数据
    newuser={
        "username": "lihua",
        "full_name": "Li Hua",
        "email": "lihua@example.com",
        "hashed_password": "fakehashedmima",
        "disabled": True,
    }
    table.insert(newuser)
    table.commit()#提交更改


    username=input("要查询的人名:")#输入"lihua",可以查询到信息
    user02=table.get(username)
    print(user02)

还可以利用JSON文件替代数据库

{
  "johndoe": {
    "username": "johndoe",
    "full_name": "John Doe",
    "email": "johndoe@example.com",
    "hashed_password": "fakehashedsecret",
    "disabled": false
  },
  "alice": {
    "username": "alice",
    "full_name": "Alice Wonderson",
    "email": "alice@example.com",
    "hashed_password": "fakehashedsecret2",
    "disabled": true
  },
}

类的写法稍加改变

class fake_db_connect():
    import json
    def __init__(self,filename:str):
        self.filename=filename
        with open(filename, 'r',encoding='utf-8') as f:
            self.fake_user_table = self.json.load(f)
    
    def get(self,primaryKey:str)->dict:
        return self.fake_user_table.get(primaryKey)

    def insert(self,info:dict):
        primaryKey=info['username']
        self.fake_user_table[primaryKey]=info

    def commit(self):
        with open(self.filename, 'w',encoding='utf-8') as f:
            self.json.dump(self.fake_user_table, f, ensure_ascii=False,indent=2)
    
    def delete(self,primaryKey:str):
        del self.fake_user_table[primaryKey]

测试时,对象的初始化带上文件名参数。

    table=fake_db_connect("JSON文件的文件名")
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

高堂明镜悲白发

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值