tachitomonn’s blog

IT技術関連の学習メモがメインでたまに趣味のこととか

Python の requestsモジュール

例によって公式ドキュメントでお勉強。というかほぼ写経なり。

Quickstart — Requests 2.0.0 documentation

人間のためのHTTPライブラリという触れ込みなので標準のurllib2より簡潔に処理を書くことができます。

インストールは pip で入れました。

リクエストをつくる

インポートして、

>>> import requests

ウェブページにGETリクエストします。

>>> r = requests.get('https://github.com/timeline.json')

rにはResponse objectが返ってくる。
シンプルななAPIなので、例えばPOSTリクエストも、

>>> r = requests.post("http://exsample.com/post")

他のHTTPリクエストタイプもシンプルです。

>>> r = requests.put("http://exsample.com/put")
>>> r = requests.delete("http://exsample.com/delete")
>>> r = requests.head("http://exsample.com/get")
>>> r = requests.options("http://exsample.com/get")

URLにおけるパラメータの受け渡し

paramsキーワード引数を使い辞書の形で渡せます。

>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.get("http://exsample.com/get", params=payload)

URLを表示してみる。

>>> print r.url
http://exsample.com/get?key2=value2&key1=value

レスポンスの中身

>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.text
u'[{"repository":{"open_issues":0,"url":"https://github.com/...

Requestsではレスポンスの内容を自動的にデコードしてくれる。
r.encodingプロパティで使われたエンコードの確認や変更が可能。

>>> r.encoding
'utf-8'
>>> r.encoding = 'ISO-8859-1'

バイナリ形式のレスポンスの中身

バイト列としてアクセスする。

>>> r.content
b'[{"repository":{"open_issues":0,"url":"https://github.com/...

例えばバイナリデータから画像をつくるコードは、

>>> from PIL import Image
>>> from StringIO import StringIO
>>> i = Image.open(StringIO(r.content))

JSON 形式のレスポンスの中身

>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...

Raw 形式のレスポンスの中身

>>> r = requests.get('https://github.com/timeline.json', stream=True)
>>> r.raw
<requests.packages.urllib3.response.HTTPResponse object at 0x101194810>
>>> r.raw.read(10)
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'

ヘッダのカスタマイズ

辞書の形式でheadersキーワード引数に渡す。

>>> import json
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> headers = {'content-type': 'application/json'}
>>> r = requests.post(url, data=json.dumps(payload), headers=headers)

より複雑なPOSTリクエス

HTMLのフォームにデータを送りたいような場合、シンプルにdataキーワード引数に辞書を渡すことができる。

>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("http://exsample.com/post", data=payload)
>>> print r.text
{
  ...
  "form": {
    "key2": "value2",
    "key1": "value1"
  },
  ...
}

form-encodedしたくない場合、辞書の代わりに string で渡せばデータを直接POSTできる。

>>> import json
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> r = requests.post(url, data=json.dumps(payload))

Multipart-EncodedファイルのPOST

シンプルにアップロードする。

>>> url = 'http://exsample.com/post'
>>> files = {'file': open('report.xls', 'rb')}
>>> r = requests.post(url, files=files)
>>> r.text
{
 ...
  "files": {
    "file": "<censored...binary...data>"
  },
  ...
}

ファイル名を明示する。

>>> url = 'http://exsample.com/post'
>>> files = {'file': ('report.xls', open('report.xls', 'rb'))}
>>> r = requests.post(url, files=files)
>>> r.text
{
  ...
  "files": {
    "file": "<censored...binary...data>"
  },
  ...
}

レスポンスのステータスコード

ステータスコードを確認する。

>>> r = requests.get('http://exsample.com/get')
>>> r.status_code
200

レスポンスのヘッダー

辞書の形で確認できる。

>>> r.headers
{
    'content-encoding': 'gzip',
    'transfer-encoding': 'chunked',
    'connection': 'close',
    'server': 'nginx/1.0.4',
    'x-runtime': '148ms',
    'etag': '"e1ca502697e5c9317743dc078f67693f"',
    'content-type': 'application/json'
}

クッキー

レスポンスがクッキーを含む場合、アクセスできる。

>>> url = 'http://example.com/some/cookie/setting/url'
>>> r = requests.get(url)
>>> r.cookies['example_cookie_name']
'example_cookie_value'

サーバーにクッキーを送る。

>>> url = 'http://example.com/cookies'
>>> cookies = dict(cookies_are='working')
>>> r = requests.get(url, cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'