Skip to content

Instantly share code, notes, and snippets.

@manxisuo
Created June 5, 2015 14:54
Show Gist options
  • Save manxisuo/4d7909d9171be9dd320f to your computer and use it in GitHub Desktop.
Save manxisuo/4d7909d9171be9dd320f to your computer and use it in GitHub Desktop.
create a gist in github
#coding:utf-8
import requests
import json
import os.path
def create_gist(file_path, name = None, desc = '', public = True):
TOKEN = '[your token]'
URL = 'https://api.github.com/gists'
headers = {'Authorization': 'token {0}'.format(TOKEN)}
# 读取代码
with open(file_path, 'r') as f:
file_content = f.read()
if not name:
name = os.path.basename(file_path)
# 构造请求体
payload = {
"description": desc,
"public": "true" if public else "false",
"files": {
name: {
"content": file_content
}
}
}
# 发送创建请求,返回gist的URL
r = requests.post(URL, data = json.dumps(payload), headers = headers)
if r.status_code == 201:
j = r.json()
return j['html_url']
else:
return None
if __name__ == '__main__':
r = create_gist('/home/su/python/gists/create_gist.py', desc = 'create a gist in github')
print r
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment