我对Python编程相当陌生,也不知道下面所需的所有库。
我想使用Python来测试一些HTTP。我主要想使用OAuth并进行一些JSON调用。有关的API可以在:https://developers.trustpilot.com/authentication和generate链接上找到(我只能使用一个链接)。
我想对自己进行身份验证,然后在一个步骤中生成一个产品评审链接。到目前为止,我一直在使用Advanced客户端(ARC)单独进行这些调用。如果您认为.arc文件更容易,我也可以使用它。
这个想法是一次接一次地打这些电话。因此,这将是一些类似的东西:
1)进行认证呼叫。
HTTP方法如下所示:https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken方法Post:
标题授权:基本Base64encode(每个键:机密)内容-类型:application/x form-urlencoded
有效载荷: grant_type=password&username=user@mail.com&password=SomePass
基本上将此位转换为Python。
1.a)在调用中添加一个标头
头授权: base64encode散列内容-类型: application/x-www-form-urlencoded
1.b)在呼叫中添加有效载荷
有效载荷: grant_type=password&username
4)从步骤1中发出的呼叫接收令牌(结果为格式)
“访问令牌”:Auth_token
5)获取标记并使用它创建产品评审。
5.a)在标头中添加标记
标题:授权:无记名Auth_token
6.a)向步骤5中的调用添加一个JSON有效负载。
下面是我到目前为止掌握的代码:
Import requests
header = {'Authorization: Basic NnNrQUprTWRHTU5VSXJGYXBVRGxack1oT01oTUFRZHI6QTFvOGJjRUNDdUxBTmVqUQ==}','Content-Type: application/x-www-form-urlencoded'}
payload = {'grant_type=password&username=email@address.com&password=SomePassword'}
r = requests.post('https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken', headers=header, params=payload )理想情况下,我希望创建requests.post(url、头、有效负载),然后以JSON格式返回服务器响应的内容。我认为打印r.text将完成最后一部分。
下面是我编写的代码(现在起作用了):
import requests
import getpass
import json
from requests.auth import HTTPBasicAuth
header = {'grant_type':'password' , 'username':'mail@maildomain.com', 'password':'YourPassword'}
username= "YOURAPIKEY" #APIKey
password= "YOURSECRET" #Secret
res = requests.post(
'URL/v1/oauth/oauth-business-users-for-applications/accesstoken',
auth=HTTPBasicAuth(username, password), # basic authentication
data=header)
#print(res.content) #See content of the call result.
data = res.json() # get response as parsed json (will return a dict)
auth_token = data.get('access_token')发布于 2016-03-24 09:05:49
requests可以做你所要求的一切,而不需要你的角色做任何工作。
见身份验证,参数,json输出,json输入的文档
进行身份验证呼叫。
import requests
import getpass
from requests.auth import HTTPBasicAuth
username = raw_input('Username: ')
password = getpass.getpass('Password: ')
res = requests.post(
'https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken',
auth=HTTPBasicAuth(username, password), # basic authentication
params={ # url parameters
'grant_type': 'password',
'username': 'email@address.com',
'password': 'SomePassword'
})从步骤1中的调用接收令牌(结果是格式的)
# res = requests.post.....
data = res.json() # get response as parsed json (will return a dict)
auth_token = data.get('access token')获取标记并使用它创建产品评审。
request.post(
'.../product_review',
headers={
'Authorization': 'Bearer ' + auth_token
},
json={'my': 'payload'}) # send data as jsonhttps://stackoverflow.com/questions/36196171
复制相似问题