从0开始写key-value数据库(Python语言)
数据库内核
"""
"""
import socket
import pickle
_cache = {}
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
host = "127.0.0.1"
port = 58624
s.bind((host, port))
s.listen(5)
# 数据库引擎
while True:
# TODO 缺少日志功能
print("开始等待连接.......{}".format((host, port)))
sock, address = s.accept()
print("连接成功{address}......".format(address=address))
while True:
"""等待发送者发送数据"""
recv_value = sock.recv(1024)
try:
"""将发送者发送的数据反序列化成字典对象"""
recv_dict = pickle.loads(recv_value)
except:
# TODO 抛出准确的异常信息
print(
"反序列化失败, revc_dict={recv_dict}".format(recv_dict=recv_dict))
continue
try:
if recv_dict['method'] == "get":
"""获取数据"""
result = _cache.get(recv_dict['data'])
result = pickle.dumps(result)
print("获取到数据 : {key}:{value}".format(
key=recv_dict['data'],
value=_cache.get(recv_dict['data'])))
sock.send(result)
elif recv_dict['method'] == "set":
"""插入数据"""
result = recv_dict['data']
result = result.split(":")
print("已插入数据: {}".format(result))
_cache[result[0]] = result[1]
elif recv_dict['method'] == "delete":
"""删除数据"""
result = recv_dict['data']
print("已删除数据, key={}, value={}".format(
result, _cache[result]))
del _cache[result]
elif recv_dict['method'] == "command":
if recv_dict['data'] == "close":
"""关闭连接"""
sock.close()
break
if recv_dict['data'] == "size":
"""获取长度"""
result = len(_cache)
print("获取长度 : {}".format(result))
result = pickle.dumps(result)
sock.send(result)
if recv_dict['data'] == 'dict_all':
"""获取所有数据"""
result = pickle.dumps(_cache)
print("获取所有数据: {}".format(_cache))
sock.send(result)
else:
print(
"查询参数有误, revc_dict={recv_dict}".format(
recv_dict=recv_dict))
except:
# TODO 抛出准确的异常
print(
"查询参数异常, revc_dict={recv_dict}".format(recv_dict=recv_dict))
continue
数据库驱动
import socket
import pickle
"""
obj.get("key") value 驱动层面对其反序列化后返回给调用者
obj.set("key : value") 有错返回异常字符串
obj.delete("key")
obj.commnd("size") 返回总的数据长度
obj.command("close")
obj.commnd("dict_all") 返回所有数据的字典形式
{
"data": ....,
"method": "get" or "set" or "delete or" "commnd"
}
"""
class KVDBDrive:
"""
数据库驱动
"""
def __init__(self, host="127.0.0.1", port=9090):
try:
self.s = socket.socket()
self.s.connect((host, port))
except:
print("socket建立失败. {}".format((host, port)))
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
return True
def get(self, key):
"""
将key序列化后发送给数据库引擎
接收到数据库引擎返回值后反序列化,并返回给调用者
"""
if key:
query = {"method": "get", "data": key}
query = pickle.dumps(query)
self.s.send(query)
result = self.s.recv(1024)
result = pickle.loads(result)
if result:
return result
def set(self, statement):
# statement = statement.split(":")
if statement:
query = {"method": "set", "data": statement}
query = pickle.dumps(query)
self.s.send(query)
# result = self.s.recv(1024)
# result = pickle.loads(result)
# return result
def close(self):
query = {"method": "command", "data": "close"}
query = pickle.dumps(query)
self.s.send(query)
相关文章