Last active
August 29, 2015 14:13
-
-
Save nrtkbb/bc4a766c57285c501bcb to your computer and use it in GitHub Desktop.
github apiでmaya.cmdsを検索した結果からリポジトリをリストアップして、スター数でソートしようとしたら、github apiでは全体検索がサポートされてなかったw
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
#coding:utf-8 | |
import urllib | |
import urllib2 | |
import cookielib | |
import json | |
# python :: urllib2 でhttps通信したときのめも - ichirin2501の日記 | |
# http://d.hatena.ne.jp/ichirin2501/20110428/1303924574 | |
# | |
# ssl通信を行う場合に必要。 | |
# urllib2の中身を変更するコード | |
opener = urllib2.build_opener(urllib2.HTTPSHandler(debuglevel=1), | |
urllib2.HTTPCookieProcessor(cookielib.CookieJar())) | |
urllib2.install_opener(opener) | |
# github apiを叩くurl文字列を構築してる | |
query = 'maya.cmds' | |
lang = 'python' | |
# url = 'https://api.github.com/search/repositories?' \ | |
url = 'https://api.github.com/search/code?' \ | |
'q=%s+in:file+language:%s&per_page=100' % (query, lang) | |
# github apiはGETで取得、POSTで生成をするようデザインされているので | |
# urllib2.Request(url, data, headers)は使えない(POSTになるから) | |
req = urllib2.Request(url) | |
# このヘッダーを追加するとファイル内のテキストにマッチングしてくれる | |
req.add_header('Accept', 'application/vnd.github.v3.text-match+json') | |
# User-Agentは好みで変えてみただけ。 | |
req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)') | |
try: | |
# 組み立てたリクエストを使ってオープンする | |
res = urllib2.urlopen(req) | |
except urllib2.HTTPError as inst: | |
print '===== HTTPError headers start =====' | |
# エラーの時のヘッダー情報をプリント | |
print inst.hdrs | |
print '===== HTTPError body json start =====' | |
# エラーの時のレスポンス本体(JSON)をプリント | |
errorJson = json.load(inst.fp) | |
print json.dumps(errorJson, sort_keys=True, indent=4) | |
print '===== HTTPError end =====' | |
# 正常時のレスポンス(JSON)(多分エラーになる) | |
jsonData = json.load(res) | |
# とりあえず表示するだけ(多分到達しない) | |
print '===== Valid data start =====' | |
print json.dumps(jsonData, sort_keys=True, indent=4) | |
print '===== Valid data end =====' |
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
{ | |
"documentation_url": "https://developer.github.com/v3/search/#search-code", | |
"errors": [ | |
{ | |
"code": "invalid", | |
"field": "q", | |
"message": "Must include at least one user, organization, or repository", | |
"resource": "Search" | |
} | |
], | |
"message": "Validation Failed" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment