hd1

hd1/githubSearchWithinUnits

hd1
Nov 22nd, 2015
529
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.93 KB | None | 0 0
  1. def compression(data):
  2.     ret = json.dumps(data, indent=4)
  3.     if web.input().has_key('compression'):
  4.         web.header('Content-Encoding', 'gzip')
  5.         gzip_buffer = StringIO.StringIO()
  6.         gzip_file = gzip.GzipFile(mode='wb',
  7.                                   fileobj=gzip_buffer)
  8.         gzip_file.write(ret)
  9.         gzip_file.close()
  10.         ret = gzip_buffer.getvalue()
  11.     return ret
  12.  
  13.  
  14. class Error(web.HTTPError):
  15.     '''HTTP errors.'''
  16.  
  17.     headers = {'Content-Type': 'application/json'}
  18.  
  19.     def __init__(self, note, headers=None, status='404 Not Found'):
  20.         message = json.dumps([{'error': note}])
  21.         web.HTTPError.__init__(self, status, headers or self.headers,
  22.                                unicode(message))
  23.  
  24.  
  25. class Github:
  26.     def GET(self, query):
  27.         params = web.input()
  28.         if not params.has_key('repo'):
  29.             raise Error('Repository must be specified with the repo parameter', status='422 Unprocessable Entity')
  30.         if not params.has_key('lang'):
  31.             language = ''
  32.         else:
  33.             language = 'language:{0}'.format(params.get('lang'))
  34.         repo = 'repo:{0}'.format(params.get('repo'))
  35.         where = '{0}+in:file'.format(query)
  36.         query_to_github = ' '.join([query, language, repo])
  37.         response = requests.get('https://api.github.com/search/code', params={'q': query_to_github}).json()
  38.         ret = []
  39.         for repo in response['items']:
  40.             value = {'name': repo['name'], 'path': repo['path']}
  41.             value['content'] = requests.get(repo['git_url']).content
  42.             if value['content'].index('API rate limit exceeded for'):
  43.                 value.pop('content', None)
  44.             logging.debug(repo.keys())
  45.             location = 'https://github.com/{0}/raw/master/{1}'.format(repo['repository']['full_name'], value['path'])
  46.             value['url'] = location
  47.             ret.append(value)
  48.         return compression(ret)
Advertisement
Add Comment
Please, Sign In to add comment