【问题标题】:How to do http request's POST to an API with Oauth2 in Python如何在 Python 中使用 Oauth2 将 http 请求的 POST 发送到 API
【发布时间】:2020-02-02 22:47:30
【问题描述】:

我一直试图弄清楚如何使用ouath2 library 在 API(在本例中为 Goodreads)中进行 POST,但由于输出始终是错误消息,因此我一直跌跌撞撞地陷入死胡同。

我参考this stackoverflow question中的答案。

Below 是我目前正在处理的 Goodread 的 API 文档。

关注作者
让登录用户使用 OAuth 关注作者。您需要注册您的应用程序(必需)。网址: https://www.goodreads.com/author_followings?id=AUTHOR_ID&format=xml
HTTP方法:POST

以下是我的第一次 POST 尝试:(错误消息:不是有效的非字符串序列或映射对象

import oauth2 as oauth
import urllib.parse

url = 'https://www.goodreads.com/author_followings?'
parameters = {'id' : '1077326',
              'format' : 'xml',
             }
echo_base_url = url + urllib.parse.urlencode(parameters)

consumer = oauth.Consumer(key ='J9l5Jsn...........', secret='N8cWf4Da...bynGVQ..........')
client = oauth.Client(consumer)

resp, content = client.request(
                echo_base_url,
                method = "POST",
                body= urllib.parse.urlencode(None),
                headers= None,
                force_auth_header=True,
                )
print (resp, content)

我的第二次尝试:(错误消息:request() 得到了意外的关键字参数“force_auth_header”

import oauth2 as oauth, urllib.parse

def oauth_req(url, key, secret, http_method="POST", post_body=None, http_headers=None):
    CONSUMER_KEY = key
    CONSUMER_SECRET = secret
    consumer = oauth.Consumer(key=CONSUMER_KEY, secret=CONSUMER_SECRET)
    #token = oauth.Token(key=key, secret=secret)
    client = oauth.Client(consumer)
    resp, content = client.request(
        url,
        method=http_method,
        body=urllib.parse.urlencode({'status': post_body}),
        headers=http_headers,
        force_auth_header=True,
    )
    return content

oauth_req('https://www.goodreads.com/author_followings?id=1077326&format=xml', 'J9l5.......', 'N8........QYIg70ru.......FVoYc', http_method="POST", post_body=None, http_headers=None)

到目前为止,我只能执行 GET,并且一直在尝试 POST,但还没有找到任何可以运行的代码。这里需要一个启发..

【问题讨论】:

    标签: python api post oauth authorization


    【解决方案1】:

    使用 API 工具并首先从中获取结果:Curl、SOAPUI 等... 在获得正确的 POST 请求结果后,将这些数据移动到您的代码中。


    对于第一条错误消息,其中一个数组的格式不正确 - 参数、请求或响应。​​

    【讨论】:

      猜你喜欢
      • 2018-10-29
      • 1970-01-01
      • 2010-12-21
      • 2017-06-01
      • 1970-01-01
      • 2022-12-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-19
      相关资源
      最近更新 更多