自动生成访问令牌

时间:2020-01-21 16:25:14

标签: python api python-requests

为了从私有API提取数据,我需要使用我的身份验证密钥和凭据生成访问令牌。我当前的代码分为两部分。第一个生成访问令牌:

import requests

 url = "https://api.abcdef.com/AuthorizationServer/Token"

 payload = "{\r\n    \"grant_type\" : \"password\",\r\n    \"username\" : \"user@aldfh.com\",\r\n  \"password\" : \"kajshdgfkuyb\",\r\n    \"scope\" : \"API\"\r\n}"

 headers = {
   'Content-Type': 'application/json',
   'Authorization': 'Basic VGFibGVhdV9DaW94QFRhYmxlYXVfQ2lveDo0Ix '
 }

 response = requests.request("POST", url, headers=headers, data = payload)

 print(response.text.encode('utf8'))

响应如下:

    {"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpY0JVSWQiOjQ1OTg0MjEsIm5hbWUiOiJyYW15YS5nb3RldHlAY2lveGhlYWx0aC5jb20iLCJpc3MiOiJodHRwczovL2FwaS5pbmNvbnRhY3QuY29tIiwic3ViIjoidXNlcjoxNTMyMDI2MiIsImF1ZCI6IlRhYmxlYXVfQ2lveEBUYWJsZWF1X0Npb3giLCJleHAiOjE1Nzk2Mjg1NzcsImlhdCI6MTU3OTYyNDk3OCwiaWNTY29wZSI6IjgiLCJpY0NsdXN0ZXJJZCI6IkMzMSIsImljQWdlbnRJZCI6MTUzMjAyNjIsImljU1BJZCI6MTQ5NiwibmJmIjoxNTc5NjI0OTc4fQ.rEZiMHPsE1inwuWFME1oV_oD54TqkU00-uml3NjCkClW3R-_bVC7A3PxI4zGlJms1rvsZkgO3XX8-1coeV6_jtI-l3nCHixVk2nboepqAspoxT3o9w4vhBhZzvs-TAsqyk4fCrSwwHFXwn8xOMdfrqZqknXHLlVtKlGJg_Uy3bmwEiioocMN3BRZE_269_v5Ez4b94_juUHLPDWye7kS5-8cs4Izsk7HePn-Sm_-FLEqEeb2C09NUGWU8SdyA3EtQhMAiHkU-wN8uQ8wKcWoUfO7WtrSO4zbicFZHgA9Cw",
"token_type":"bearer",
"expires_in":3600,
"refresh_token":"pDYllH2UsVIYq3Pn3Dg==",
"scope":"Api",
"resource_server_base_uri":"https://api-c31.it.com/itAPI/",
"refresh_token_server_uri":"https://api-c31.it.com/AuthorizationServer/Token",
"agent_id":162,
"team_id":24355,
"bus_no":4421}'

访问令牌是输出的一部分,我将其粘贴到以下代码中以生成响应:

def getPerformance():

# api-endpoint 
#Give the specified url ,accessToken
    BASEURL = 'https://api-c31.ict.com/tAPI/'
    accessToken = "{eyJ0eXAiOiJKV1QiLCJhbGciSUzI1NiJ9.eyJpY0JVSWQiOjQ1OTgyYW15YS5nb3RldHlAY2lveGhlYWx0aC5jb20iLCJpc3MiOiJodHRwczovL2FwaS5pbmNvbnRhY3QuY29tIiwic3ViIjoidXNlcjoxNTMyMDI2MiIsImF1ZCI6IlRhYmxlYXVfQ2lveEBUYWJsZWF1X0Npb3giLCJleHAiOjE1Nzk1NjA0MjYsImlhdCI6MTU3OTU1NjgyNywiaWNTY29wZSI6IjgiLCJpY0NsdXN0ZXJJZCI6IkMzMSIsImljQWdlbnRJZCI6MTUzMjAyNjIsImljU1BJZCI6MTQ5NiwibmJmIjoxNTc5NTU2ODI2fQ.JIzsPLK8kg8Zqq_uITeNp6b24xuglcmtjVbD9Ll-ooq943gIILvr_SQ8cTKNl50YMyiX_mu48pupf-D0b-Ntbmb7hYOTNY7tjp8skM8uBDmuSzG1GnVQh3ZotdlofhiEDU9_U4sQsovqdDtXyi5inaoJ95TeBS_YQp_3LSv3pjfXQNWdt1bcn7arHWdIdl6qD5qXm0DhXQArhTr35mViZn-ZxITW4nvEi-gwZz6DdLWuWcW5kTbbzvucroVUPM-dZvzNJvMEruJvriUGl3Y2DSlB5qTLo3JqbLwujsoZfhaxfJ1eAFKd13t6mMenQ5TOwVV3Rg_yp7DfeBbnWcmwtA}"

#Check if accessToken is empty or null
if accessToken != "":

#Give necessary parameters for http request
    payload={'startDate':'1/1/2020', 
    'endDate':'1/6/2020',
    'fields':'"teamId","calls"'}

#add all necessary headers
    header_param = {'Authorization': 'bearer ' + '{accessToken}','content-Type': 'application/x-www-form-urlencoded','Accept': 'application/json, text/javascript, */*'}

# Make get http request
    answer = requests.get(BASEURL + 'services/{version}/g/h' , headers = header_param, params=payload) 


#print response appropriately
    print (answer)

else: print('error')

我的问题是我需要能够合并两个脚本才能使流程自动化。

2 个答案:

答案 0 :(得分:1)

尝试将以下更改添加到代码的第一部分,然后将访问令牌放在底部,将其传递到getPerformance()函数中:

#Added json import here

import json
import requests


url = "https://api.abcdef.com/AuthorizationServer/Token"

payload = "{\r\n    \"grant_type\" : \"password\",\r\n    \"username\" : \"user@aldfh.com\",\r\n  \"password\" : \"kajshdgfkuyb\",\r\n    \"scope\" : \"API\"\r\n}"

headers = {
     'Content-Type': 'application/json',
     'Authorization': 'Basic VGFibGVhdV9DaW94QFRhYmxlYXVfQ2lveDo0Ix '
     }

response = requests.request("POST", url, headers=headers, data = payload)

#Note the changes here

json = response.read()
data = json.loads(json)


accessToken = data['access_token']

然后,无论您在哪里叫getPerformanceFunction(),都想将其更改为getPerformance(accessToken)。您还需要将函数定义更改为此。

答案 1 :(得分:0)

基于上述@Cutter的回复,进行以下更改对我有用:

import requests
import json

 url = "https://api.abcdef.com/AuthorizationServer/Token"

 payload = "{\r\n    \"grant_type\" : \"password\",\r\n    \"username\" : \"user@aldfh.com\",\r\n  \"password\" : \"kajshdgfkuyb\",\r\n    \"scope\" : \"API\"\r\n}"

 headers = {
   'Content-Type': 'application/json',
   'Authorization': 'Basic VGFibGVhdV9DaW94QFRhYmxlYXVfQ2lveDo0Ix '
 }

 response = requests.request("POST", url, headers=headers, data = payload)
 testresp = response.text
 data = json.loads(testresp)

#将函数定义更改为:

def getPerformance(data):

# api-endpoint 
#Give the specified url ,accessToken
# =============================================================================
    BASEURL = 'https://api-c31.ict.com/API/'
    accessToken = (data["access_token"])