1
from oauth_hook import OAuthHook
import requests, json
OAuthHook.consumer_key = "KEYHERE" 
OAuthHook.consumer_secret = "SECRET HERE"
oauth_hook = OAuthHook("TOKEN_KEY_HERE", "TOKEN_SECRET_HERE", header_auth=True)
headers = {'content-type': 'application/json'}
client = requests.session(hooks={'pre_request': oauth_hook}, headers=headers)
payload = {"title":"album title"}
r = client.post("http://api.imgur.com/2/account/albums.json",payload)
print r.text

これにより、タイトル付きのアルバムが作成され、album title代わりに戻り文字列が

{
    "albums": {
        "id": "IMGURID",
        "title": "",
        "description": "",
        "privacy": "public",
        "cover": "",
        "order": 0,
        "layout": "blog",
        "datetime": "2012-12-05 15:48:21",
        "link": "IMGUR LINK",
        "anonymous_link": "ANONYLINK"
    }
}

リクエストを使用してアルバムのタイトルを設定するソリューションはありますか?

imgur API ドキュメントへのリンクは次のとおりですhttp://api.imgur.com/resources_auth

4

1 に答える 1

2

JSON データを投稿していません。代わりに、URL エンコードされたデータに変換されます。requestsコンテンツ タイプを に設定しても、自動 JSON エンコーディングは提供されませんapplication/json

モジュールを使用しjsonてエンコードします。

import json

r = client.post("http://api.imgur.com/2/account/albums.json", json.dumps(payload))

http://httpbin/postPOST エコー サービスを使用すると、次のように表示されます。

>>> import json, requests, pprint
>>> headers = {'content-type': 'application/json'}
>>> payload = {"title":"album title"}
>>> pprint.pprint(requests.post('http://httpbin.org/post', payload, headers=headers).json)
{u'args': {},
 u'data': u'title=album+title',
 u'files': {},
 u'form': {},
 u'headers': {u'Accept': u'*/*',
              u'Accept-Encoding': u'gzip, deflate, compress',
              u'Connection': u'keep-alive',
              u'Content-Length': u'17',
              u'Content-Type': u'application/json',
              u'Host': u'httpbin.org',
              u'User-Agent': u'python-requests/0.14.2 CPython/2.7.3 Darwin/11.4.2'},
 u'json': None,
 u'origin': u'xx.xx.xx.xx',
 u'url': u'http://httpbin.org/post'}
>>> pprint.pprint(requests.post('http://httpbin.org/post', json.dumps(payload), headers=headers).json)
{u'args': {},
 u'data': u'{"title": "album title"}',
 u'files': {},
 u'form': {},
 u'headers': {u'Accept': u'*/*',
              u'Accept-Encoding': u'gzip, deflate, compress',
              u'Connection': u'keep-alive',
              u'Content-Length': u'24',
              u'Content-Type': u'application/json',
              u'Host': u'httpbin.org',
              u'User-Agent': u'python-requests/0.14.2 CPython/2.7.3 Darwin/11.4.2'},
 u'json': {u'title': u'album title'},
 u'origin': u'xx.xx.xx.xx',
 u'url': u'http://httpbin.org/post'}

requestsバージョン 2.4.2 以降を使用している場合は、エンコーディングをライブラリに任せることができます。ペイロードをjsonキーワード引数として渡すだけです。ちなみに、その場合は正しい Content-Type ヘッダーも設定されます。

r = client.post("http://api.imgur.com/2/account/albums.json", json=payload)
于 2012-12-05T15:54:13.543 に答える