1. 程式人生 > >python實現簡單redis客戶端(2)重構

python實現簡單redis客戶端(2)重構

將客戶端劃分為通訊模組和客戶端模組進行重構

from socket import *
class Connection:
    def __init__(self, host="localhost", port=6379):
        self.host = host
        self.port = port
        self.client=socket(AF_INET, SOCK_STREAM)
    def connect(self):
        self.client.connect((self.host,self.port))

    def write
(self,data):
self.client.send(data.encode('utf8')) def read(self): data=self.client.recv(1024) return data class Client: def __init__(self, host="localhost", port=6379, password=None, db=None): self.connection = Connection(host=host, port=port) self.password = password self.db = db or
0 self.connection.connect() def format_command(self,*tokens, **kwargs): cmds = [] for t in tokens: cmds.append("$%s\r\n%s\r\n" % (len(t), t)) return "*%s\r\n%s" % (len(tokens), "".join(cmds)) def execute_command(self,cmd,*args,**kwargs): command = self.format_command(cmd,*args,**kwargs) self.connection.write(command) data = self.connection.read() return
data def set(self,key,value): result = self.execute_command("SET",key,value) return result def get(self,key): value = self.execute_command("GET",key) return value if __name__ == '__main__': client=Client() client.set('dog','love') value = client.get('dog') print(value)

效果:
這裡寫圖片描述