如何在Python中实际令牌过期后在Get请求中使用刷新令牌

wmomyfyw  于 2023-06-25  发布在  Python
关注(0)|答案(1)|浏览(152)

我有一个场景,我需要连接onedrive并获取所有文件夹和内部文件信息,因此我在azure中注册了应用程序以获取tenat id和客户端id等。
我成功登录并能够获取文件夹和文件信息,但我有大约8 k+文件夹和内部文件,因此我在1到2小时后获得令牌过期时间,获得错误,我还刷新了令牌,但不确定如何在GET请求中使用该令牌
这里我粘贴的代码可以任何人请建议如何使用它,在我的代码中,我创建的bin文件中,既有access_token和refresh_token

TENANT_ID = '111*********f5d4'
CLIENT_ID = '7c0*************5517'

AUTHORITY = 'https://login.microsoftonline.com/' + TENANT_ID
ENDPOINT = 'https://graph.microsoft.com/v1.0'
base_url = 'https://graph.microsoft.com/v1.0/'
SCOPES = [
    'Files.ReadWrite.All',
    'Sites.ReadWrite.All',
    'User.Read',
    'User.ReadBasic.All'
]

cache = msal.SerializableTokenCache()

if os.path.exists('token_cache.bin'):
    cache.deserialize(open('token_cache.bin', 'r').read())

atexit.register(lambda: open('token_cache.bin', 'w').write(cache.serialize()) if cache.has_state_changed else None)

app = msal.PublicClientApplication(CLIENT_ID, authority=AUTHORITY, token_cache=cache)

accounts = app.get_accounts()
result = None
if len(accounts) > 0:
    result = app.acquire_token_silent(SCOPES, account=accounts[0])

if result is None:
    flow = app.initiate_device_flow(scopes=SCOPES)
    if 'user_code' not in flow:
        raise Exception('Failed to create device flow')

    print(flow['message'])

    result = app.acquire_token_by_device_flow(flow)

if 'access_token' in result:
    parent = base_url +'/drives/!FJ9b********************BnEOcC-mq/root:/Box_Migration/Product Images - SHARE'
    link = parent+":/children"
    while True:
        rGetCh = requests.get(link, headers={'Authorization': 'Bearer ' + result['access_token']})
        data=rGetCh.json()['value']
        for itemm in data:
            file_id =itemm['name']
            print(file_id)
            endpoint=base_url + f'/drives/b!FJ9b********************BnEOcC-mq/root:/Box_Migration/****uct I888ages - SHARE/{file_id}:/children'
            response_data= requests.get(endpoint,headers={'Authorization': 'Bearer ' + result['access_token']})
            print(response_data)
            json_data =response_data.json()
            #print(json_data)
       
            with open('new_Refresh_token.json', 'a+') as fout:
                fout.write(json.dumps(json_data,indent = 4,default=str))
                fout.write(',\n')
                fout.close()       
        for ch in rGetCh.json()["value"]:
            # Looping through the current list of children
            chName = urllib.parse.quote(ch["name"].encode('utf8'))
            chPath = parent + "/" + chName

        if "@odata.nextLink" in rGetCh.json():  # if this is in the response, there are more children
            link =  rGetCh.json()["@odata.nextLink"]
        else:
           break

else:
    raise Exception('no access token in result')

这里有两个GET请求,一个用于获取文件夹信息,另一个用于获取文件信息
请这是非常高的优先级可以任何一个建议/帮助/想法

anauzrmj

anauzrmj1#

如果令牌已过期。然后取一个文件夹列表,一半时间,另一半时间存储一个变量并运行

相关问题