本文主要想法是通过模拟数据库操作,减少服务后端开发起步阶段的工作量,用于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文件的文件名")