Skip to content

Instantly share code, notes, and snippets.

@ri0day
Created December 20, 2011 07:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ri0day/1500628 to your computer and use it in GitHub Desktop.
Save ri0day/1500628 to your computer and use it in GitHub Desktop.
memcache http api
#/usr/bin/python
import pylibmc
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import cgi
import logging
class example():
host = ""
server = ""
def __init__(self, host='10.10.93.16',port=11211):
self.host = "%s:%s"%(host, port)
self.server = pylibmc.Client([self.host])
def set(self, key, vaule, expiry=0):
return self.server.set(key, vaule, expiry)
def get(self, key):
return self.server.get(key)
def delete(self,key):
return self.server.delete(key)
def stats(self):
return self.server.get_stats()
def flush_all(self):
return self.server.flush_all()
class CacheHandler(BaseHTTPRequestHandler):
# """test:
# curl -F "authkey=aaa" -F "action=delete" -F "cachekey=wumin" http://10.10.93.16:801
# debug:
# remove top of try ,and except"
# """
def address_string(self):
return "%s:%s"%self.client_address[:2]
def do_GET(self):
pass
def do_POST(self):
try:
ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
if ctype == 'multipart/form-data' :
fs = cgi.FieldStorage(fp = self.rfile,headers = self.headers,environ={ 'REQUEST_METHOD':'POST' })
try:
fs_expire = fs.getlist('expire')[0]
except:
fs_expire = 0
authkey = fs.getlist('authkey')[0]
action = fs.getlist('action')[0]
fs_key = fs.getlist('cachekey')[0]
# print authkey,action,fs_key,fs_vaule,fs_expire
authgroup={'aaa':['10.10.93.16',11211],'bbb':['172.18.18.15',11211]}
if authgroup.get(authkey,'FAIL') != 'FAIL':
c_host,c_port =authgroup.get(authkey)
print "c_host: %s, c_port: %s" %(c_host,c_port)
Cache= example(host=c_host,port=int(c_port))
else:
self.send_error(500,'invaild key not allowed')
raise Exception("invaild key")
if action == "add" and fs_key is not None:
fs_vaule = fs.getlist('vaule')[0]
Cache.set(fs_key,fs_vaule,int(fs_expire))
self.send_response(200)
self.end_headers()
self.wfile.write("True")
elif action == "delete" and fs_key is not None:
Cache.delete(fs_key)
self.send_response(200)
self.end_headers()
self.wfile.write("True")
elif action == "flush_all":
Cache.flush_all()
self.send_response(200)
self.end_headers()
self.wfile.write("True")
elif action == "get" and fs_key is not None:
context=Cache.get(fs_key)
self.send_response(200)
self.end_headers()
self.wfile.write(context)
else:
self.send_error(500,'not this action')
except Exception:
print "POST ERROR"
def main():
try:
server = HTTPServer(('', 801), CacheHandler)
print 'started httpserver...'
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down server'
server.socket.close()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment