在python中请求需要oauth令牌的API调用

时间:2019-05-09 17:27:37

标签: python json oauth python-requests python-requests-html

所以我正在编写一个程序,将数据发布到url并得到响应。在邮递员中,需要令牌。因此,当我尝试在python中制作时,它给了我一个响应[401]。

我遇到的问题是尝试先获取令牌,然后将其传递给我的post_data方法。

出于隐私考虑,我将在URL,用户名和密码中加上***。

import requests
import json
import pprint
import urllib

def get_token():
    tokenurl='***'
    data={
            'grant_type':'password',
            'username':'***',
            'password':'***'
            }
    token=requests.post(tokenurl,data=data)
    print(token)    
get_token()

def post_data():
    url1='***'
    data={"***"
      }

    data_json = json.dumps(data)
    headers = {'Content-type': 'application/json'}
    response = requests.post(url, data=data_json, headers=headers)
    pprint.pprint(response.json())

1 个答案:

答案 0 :(得分:1)

在post_data()函数中,您可以将生成的令牌添加到标题中

headers = {'Content-type': 'application/json','Authorization': 'token ***'}

***是您生成的令牌