Skip to content

Instantly share code, notes, and snippets.

@Preetam
Last active January 1, 2016 04:09
Show Gist options
  • Save Preetam/8089942 to your computer and use it in GitHub Desktop.
Save Preetam/8089942 to your computer and use it in GitHub Desktop.
This is a small Python class to communicate with a Fickle instance: https://github.com/PreetamJinka/fickle
import socket
'''
There's probably a better way to do these.
'''
def int_to_uint16(num):
return chr(num & 255)+chr((num>>8) & 255)
def chars_to_int(c1, c2):
return ord(c2) + ord(c1)<<8
'''
This doesn't have any range operations yet.
'''
class FickleMap:
def __init__(self, address, port):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((address, port))
def __setitem__(self, key, value):
self.sock.send('\x14')
self.sock.send('\x01')
self.sock.send(int_to_uint16(key.__len__()))
self.sock.send(int_to_uint16(value.__len__()))
self.sock.send(key)
self.sock.send(value)
data = ord(self.sock.recv(1))
def __getitem__(self, key):
self.sock.send('\x14')
self.sock.send('\x00')
self.sock.send(int_to_uint16(key.__len__()))
self.sock.send(int_to_uint16(0))
self.sock.send(key)
data = ord(self.sock.recv(1))
if data != 0:
return ""
else:
data = self.sock.recv(2)
length = chars_to_int(data[0], data[1])
data = self.sock.recv(length)
return data
def __delitem__(self, key):
self.sock.send('\x14')
self.sock.send('\x02')
self.sock.send(int_to_uint16(key.__len__()))
self.sock.send(int_to_uint16(0))
self.sock.send(key)
data = ord(self.sock.recv(1))
def run():
m = FickleMap('127.0.0.1', 8080)
m['foo'] = 'bar'
print('foo => '+m['foo'])
if __name__ == '__main__':
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment