Mercurial > pybugzilla
view bugzilla @ 3:85016bf54034
Added JsonBlobCache class
author | Atul Varma <avarma@mozilla.com> |
---|---|
date | Mon, 12 Apr 2010 23:58:15 -0700 |
parents | 04f5ad537f36 |
children | 4e31f7aeb1b8 |
line wrap: on
line source
#! /usr/bin/env python import httplib import urllib from urlparse import urlparse try: import json except ImportError: import simplejson as json def json_request(method, url, query_args=None, body=None): if query_args is None: query_args = {} headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} urlparts = urlparse(url) if urlparts.scheme == 'https': connclass = httplib.HTTPSConnection elif urlparts.scheme == 'http': connclass = httplib.HTTPConnection else: raise ValueError('unknown scheme "%s"' % urlparts.scheme) conn = connclass(urlparts.netloc) path = urlparts.path if query_args: path += '?%s' % urllib.urlencode(query_args) if body is not None: body = json.dumps(body) conn.request(method, path, body, headers) response = conn.getresponse() status, reason = response.status, response.reason mimetype = response.msg.gettype() data = response.read() conn.close() if mimetype == 'application/json': data = json.loads(data) return {'status': response.status, 'reason': response.reason, 'content_type': mimetype, 'body': data} def make_caching_json_request(cache, json_request=json_request): from hashlib import sha1 as hashfunc def caching_json_request(method, url, query_args=None, body=None): key = hashfunc(repr((method, url, query_args, body))).hexdigest() if not key in cache: cache[key] = json_request(method=method, url=url, query_args=query_args, body=body) return cache[key] return caching_json_request class JsonBlobCache(object): def __init__(self, cachedir): self.cachedir = cachedir def __pathforkey(self, key): if not isinstance(key, basestring): raise ValueError('key must be a string') return os.path.join(self.cachedir, '%s.json' % key) def __getitem__(self, key): if not key in self: raise KeyError(key) return json.loads(open(self.__pathforkey(key)).read()) def __setitem__(self, key, value): open(self.__pathforkey(key), 'w').write(json.dumps(value)) def __contains__(self, key): return os.path.exists(self.__pathforkey(key)) def main(config, json_request=json_request): print json_request('GET', '%s/attachment/436897' % config['api_server'], query_args={'attachmentdata': 1}) if __name__ == '__main__': import os import sys mypath = __import__('__main__').__file__ mydir = os.path.dirname(mypath) configfile = os.path.join(mydir, 'bugzilla-config.json') config = json.loads(open(configfile).read()) if 'username' in config and 'password' not in config: from getpass import getpass try: config['password'] = getpass('Enter password for %s: ' % config['username']) except KeyboardInterrupt: config['password'] = None if not config['password']: print "Aborted." sys.exit(1) cache = JsonBlobCache(os.path.join(mydir, 'cache')) main(config=config, json_request=make_caching_json_request(cache))