如何使用Python中的Oauth2将http请求发布到API

2024-04-26 05:03:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在试图弄清楚如何使用ouath2 library在API(在本例中是Goodreads)中进行POST,但由于输出总是一条错误消息,所以我一直在跌入死胡同。你知道吗

我参考this stackoverflow question中的答案。你知道吗

Below是我目前正在编写的Goodread的API文档。你知道吗

Follow an author
Make the signed-in user follow an author using OAuth. You'll need to register your app (required). URL: https://www.goodreads.com/author_followings?id=AUTHOR_ID&format=xml
HTTP method: 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)

我的第二次尝试:(error msg:request()得到一个意外的关键字参数'force\u auth\u 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)

我只能做到目前为止,一直在尝试后,但还没有找到任何代码,甚至一次工作。我需要一个启示。。你知道吗


Tags: keyclientnonehttpurlsecretconsumerparse
1条回答
网友
1楼 · 发布于 2024-04-26 05:03:03

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


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

相关问题 更多 >