猿问

在python中更新访问令牌

这是我的第一个问题,请耐心等待。我正在使用一个 API,该 API 使用在 15 分钟后过期的访问令牌进行身份验证,没有刷新令牌可以代替重新登录。到目前为止,我已经能够获取访问令牌并将其插入到requests.get调用中,但我似乎无法让它更新并且不知道如何更新。使用这个 API 完成的所有工作,一般来说,都是使用 Python 完成的,所以我希望将它保留在 Python 中并在同一个文件中。


40115 分钟结束后,我会收到一个消息代码,200如果成功,我会收到代码。到目前为止,我唯一的想法是将它放在一个计时器上进行更新,但我无法对 stackoverflow 帖子或有关这样做的文档进行正面或反面,让登录在单独的脚本中运行,然后该脚本调用另一个作为当前标头变量(但这仍然需要一个计时器),或者让它在遇到response.status_code != 200.


获取访问令牌的示例脚本


import requests, os, json, time, csv

def login (url, payload):

    #this will log into API and get an access token

    auth = requests.post(url, data=payload).json()

    sessionToken = auth["token"]

    sessionTimer = auth["validFor"]

    headers = {'Access-Token': sessionToken}

    return headers

#calling the function to generate the token

if __name__ == '__main__':

    url = "url inserted here"

    u = input("Enter your username: ")

    p = input("Enter your password: ")

    t = input("Enter your tenancy name: ")

    payload = {'username': u, 'password': p, 'tenant': t}

    print("Logging in")

    headers = login(url, payload)

#the actual work as pulled from a csv file

valuables = input("CSV file with filepath: ")

file = open(valuables, 'r', encoding='utf-8')

csvin = csv.reader(file)

for row in csvin:

    try:

        uuidUrl = row[0]

        output_file = row[1]

        response = requests.get(uuidUrl, headers=headers)

        print(response.status_code)

        with open(output_file, 'wb') as fd:

            for chunk in response.iter_content(chunk_size=128):

                fd.write(chunk)

        fd.close()

    except requests.exceptions.RequestException:

        print(output_file,"may have failed")

        login(url, payload)

        continue

我无法成功识别 aif response.status_code != 200:作为回调 login() 的方式。我似乎也无法让它退出while True:循环。


很抱歉,我无法提供有关访问 API 供其他人试用的更多详细信息。它是非公开的


蝴蝶不菲
浏览 159回答 1
1回答

holdtom

最终,我能够找出自己问题的答案。为以后的用户发布此信息。更新的片段如下。故事的简短版本: requests.status_code 发送回一个整数,但我错误地假设它是一个字符串,因此我的内部比较不好。for row in csvin:    try:        uuidUrl = row[0]        xip_file = row[1]        response = requests.get(uuidUrl, headers=headers)        status = response.status_code        print(status)        if status == 401:            print(xip_file, "may have failed, loggin back in")            login(url, payload)            headers = login(url, payload)            response = requests.get(uuidUrl, headers=headers)            with open(xip_file, 'wb') as fd:                for chunk in response.iter_content(chunk_size=128):                    fd.write(chunk)            fd.close()        else:            with open(xip_file, 'wb') as fd:                for chunk in response.iter_content(chunk_size=128):                    fd.write(chunk)            fd.close()    except requests.exceptions.RequestException:        print(xip_file,"may have failed")        headers = login(url, payload)        continue
随时随地看视频慕课网APP

相关分类

Python
我要回答