やってみる

アウトプットすべく己を導くためのブログ。その試行錯誤すらたれ流す。

PythonでHTTP通信する方法について調べてみた

BatchをやめてPythonでGitHubAPIを使った自動化ツールを作りたい。そこで、PythonでHTTP通信する方法について調べてみた。

ライブラリ

PythonでHTTP通信するときは以下のライブラリを使うらしい。

requestsのほうが使いやすいとか。

また、こちらを参考にするとfurlというライブラリも便利そう。

ライセンス

Software License 参考
Python 3.4.4 PSF License (Python Software Foundation License) 参考
requests Apache License 2.0 参考
furl Unlicense 参考

Pythonの標準ライブラリをimportするのはとくに問題なさそう。

requestsApache License 2.0requestsを含むコードを配布するときは、以下ような文言とリンクが必要か。

このアプリは Apache License, Version 2.0 のライセンスで配布されている成果物を含んでいます。

urllib2

urllib2で、リポジトリ一覧(30件)を取得する。

事前準備

  • Python 2.7.10で実行する
  • 事前にGitHubのアカウントを作成し、AccessTokenを作成しておく

ソースコード

from urllib2 import urlopen, Request
url = "https://api.github.com/user/repos"
token = "0123456789012345678901234567890123456789"

request = Request(url)
request.add_header('Authorization', 'token %s' % token)
response = urlopen(request)

f_obj = open('GitHub.username.Repositories.json', 'w')
print >> f_obj , response.read()

GitHub API 補足

https://api.github.com/user/repos?type=owner&sort=created&direction=desc&per_page=1000とすると、作成日時の降順で、30*1000=30000件まで取得できるはず。

requests

インストール

  1. コンソールを起動する
  2. pip install requestsコマンドを実行する

以下のエラー発生。Python2.7.10であることが原因かもしれない。Python3.xをインストールしてみる。

Active code page: 65001
$ pip install requests
Traceback (most recent call last):
  File "C:\Python27\lib\runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "C:\Python27\lib\runpy.py", line 72, in _run_code
    exec code in run_globals
  File "C:\Python27\Scripts\pip.exe\__main__.py", line 5, in <module>
  File "C:\Python27\lib\site-packages\pip\__init__.py", line 15, in <module>
    from pip.vcs import git, mercurial, subversion, bazaar  # noqa
  File "C:\Python27\lib\site-packages\pip\vcs\mercurial.py", line 10, in <module>
    from pip.download import path_to_url
  File "C:\Python27\lib\site-packages\pip\download.py", line 35, in <module>
    from pip.utils.ui import DownloadProgressBar, DownloadProgressSpinner
  File "C:\Python27\lib\site-packages\pip\utils\ui.py", line 51, in <module>
    _BaseBar = _select_progress_class(IncrementalBar, Bar)
  File "C:\Python27\lib\site-packages\pip\utils\ui.py", line 44, in _select_progress_class
    six.text_type().join(characters).encode(encoding)
LookupError: unknown encoding: cp65001
exit status 1

Python

Python 3のページをみると、

Windows XP サポートを必要とする場合は、Python 3.4 をインストールしてください。

とある。Python 3.4 Release Scheduleをみると、この記事の投稿時点では3.4.5が最新。ただし、Windows x86 MSI installerが存在するのは3.4.4。ということで、3.4.4Windows x86 MSI installerをインストールする。

確認

既存の2.7.10は環境変数のPathに追加してあるため、以下のようにパスを省略して打てる。

$ python
Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.

今回新しく導入した3.4.4は環境変数のPathに追加していないためか、フルパスを入力しないと打てない。

$ C:/python34/python
Python 3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 19:28:18) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.

install (2回目)

$ C:\Python34\Scripts\pip.exe install requests
Collecting requests
  Downloading requests-2.11.1-py2.py3-none-any.whl (514kB)
    100% |████████████████████████████████| 516kB 119kB/s
Installing collected packages: requests
Successfully installed requests-2.11.1
You are using pip version 7.1.2, however version 9.0.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

3.4.4のpipで再試行すると成功した。 pipのバージョンが古いらしいが、Windows XPで動作するかわからないのでアップグレードはしない。

ついでに、furlもインストールした。

$ C:\Python34\Scripts\pip.exe install furl
Collecting furl
  Downloading furl-0.5.6.tar.gz
Collecting six>=1.8.0 (from furl)
  Downloading six-1.10.0-py2.py3-none-any.whl
Collecting orderedmultidict>=0.7.8 (from furl)
  Downloading orderedmultidict-0.7.11.tar.gz
Installing collected packages: six, orderedmultidict, furl
  Running setup.py install for orderedmultidict
  Running setup.py install for furl
Successfully installed furl-0.5.6 orderedmultidict-0.7.11 six-1.10.0
You are using pip version 7.1.2, however version 9.0.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

ソースコード

#!python3
#encoding:utf-8

import requests

url = "https://api.github.com/user/repos"
#token = "0123456789012345678901234567890123456789"
token = "46b88e89d6cd47f2f278ecde5b83ba21504349f1"
headers = {'Authorization': 'token ' + token}
res = requests.get(url, headers=headers)
print(res.text)

Pythonで学習したこと

キーワード 意味
#!python3 Python3で実行すべきコードのときファイルの先頭に記載する(Python2との使い分け)
#encoding:utf-8 ソースコード文字コードを宣言するために記載する
import 外部ライブラリの読み込み。
from 呼出時にモジュール名を省略できる。
変数宣言 変数名 = 値の形で宣言する。型は不要。
ディクショナリ型 jsonに見える{'Authorization': 'token ' + token}の部分。
コメント #を行の先頭に入れる。複数行コメントはできない。
標準出力 print(文字列)

所感

これでPythonからWebAPIを叩けそう。

HTTP通信はWindows/Batch/curlで実装するより、Python/requestsで実装するほうが遥かに楽。可読性も高い。応用も利く。PythonはWebAPIクライアントとしても使えそう。

今更だがはてなブログのシンタックスハイライトを知ったので使ってみた。