Created
December 28, 2013 02:27
-
-
Save olooney/8155384 to your computer and use it in GitHub Desktop.
simple gist API wrapper with requests module
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python | |
""" | |
Simple wrapper around Github's gist HTTP API. | |
""" | |
import argparse | |
import logging | |
import requests | |
import json | |
from getpass import getuser, getpass | |
# static initialization | |
api = 'https://api.github.com' | |
parser = argparse.ArgumentParser(description='fetches, publishes, and updates gists') | |
parser.add_argument('filenames', nargs='+', metavar='FILE') | |
parser.add_argument('-i', '-g', '--id', '--gist', dest='id', help='gist ID', metavar='ID', default=None) | |
parser.add_argument('-m', '-d', '--description', help='gist description', default=None) | |
parser.add_argument('-v', '--verbose', help='turn on verbose logging', action='store_true', default=False) | |
logger = logging.getLogger('gist') | |
logger.setLevel('WARNING') | |
logger.addHandler(logging.StreamHandler()) | |
def gist(args, auth): | |
"""creates or updates a gist from the given files.""" | |
logger.debug('username: ' + auth[0]) | |
logger.debug(repr(args)) | |
description = args.description or args.filenames[0] | |
files = {} | |
# github expects a "files" objected keyed off of filename | |
for filename in args.filenames: | |
with open(filename, 'rb') as file: | |
content = file.read() | |
files[filename] = { "content": content } | |
# prepare the full JSON object that github wants | |
gist = json.dumps(dict(description=description, public=True, files=files), indent=4) | |
logger.debug(gist) | |
if args.id: # update existing gist | |
url = api+'/gists/'+args.id | |
logger.debug("PATCH TO " + url) | |
response = requests.patch(url, data=gist, auth=auth) | |
else: # create new gist | |
url = api+'/gists' | |
logger.debug("POST TO " + url) | |
response = requests.post(url, data=gist, auth=auth) | |
print_response(response) | |
def print_response(response): | |
"""print the URL of successfully updates gists or the full error message""" | |
if response.status_code == 201: | |
print response.headers['Location'] | |
elif response.ok: | |
print response.json()['url'] | |
else: | |
for key, value in response.headers.iteritems(): | |
print '{key}: {value}'.format(**locals()) | |
try: | |
print json.dumps(response.json(), indent=4) | |
except ValueError: | |
print response.text | |
if __name__ == '__main__': | |
args = parser.parse_args() | |
if args.verbose: | |
logger.setLevel('DEBUG') | |
auth = (getuser(), getpass()) | |
gist(args, auth) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This utility was used to post itself. META!