Token expires before file upload

I am using a request session with oauth2 authentication. Everything works fine when I upload small files, but for a 4 GB file I get an error with an expired token, it looks like the file was downloaded, but in the final session the partial token was confirmed again.

Is there a chance to deal with this situation? Upload a large file with a token updated before the session closes, or something else?

sample code below, thanks for any help. Hooray!

import requests from io import StringIO from requests_toolbelt.multipart.encoder import MultipartEncoder TOKEN_PAYLOAD = { 'grant_type': 'password', 'client_id': '###', 'client_secret': '###', 'username': '###', 'password': '####' } def get_token(): response = requests.post( 'https://oauth/token', params=TOKEN_PAYLOAD) response_data = response.json() token = response_data.get('access_token') return token # Create test file MB = 1024 ** 2 GB = MB * 1024 encoded_string = 'x' * 4 * GB file_test = StringIO() file_test.write(encoded_string) # Get token token = get_token() # Create form multipart_data = MultipartEncoder( fields={ '--': ('4GB_test.txt', file_test, 'text/plain'), 'id': '2217', 'fileFieldDefId': '4258', } ) # Create headers headers = { "Authorization": "Bearer {}".format(token), 'Content-Type': multipart_data.content_type } session = requests.Session() response = session.post( 'https://oauth2/rest/external/item/multipartUpdate/byId', headers=headers, data=multipart_data, ) print(response) # <Response [401]> print(response.content) # b'{"error":"invalid_token","error_description":"Access token expired: 0f7f6bd9-4e21-407f-4a78347711a9"}' # response.close() ? with refreshed token # session.close() ? with refreshed token 
+5
source share
1 answer

If you want to have valid access tokens even longer, you can also request update tokens and use them to generate new access tokens when the old one expires. Typically, access tokens are valid for 1 hour, you can maintain a timer and generate a new access token every time your timer reaches 60 minutes. This way you can have a valid access token for longer sessions.

You should use grant_type=refresh_token https://tools.ietf.org/html/rfc6749#section-6

+1
source

Source: https://habr.com/ru/post/1270318/


All Articles