k.r*_*cki 6 oauth-2.0 python-2.7 python-3.x python-requests
我正在使用oauth2身份验证的请求会话.当我上传小文件时,一切都很完美,但对于4GB文件,我得到令牌过期错误,看起来文件已上传,但在结束会话时,部分令牌再次得到验证.
有没有机会处理这种情况?在会话关闭之前刷新令牌刷新的大文件或什么?
代码示例如下,非常感谢您的帮助.干杯!
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
Run Code Online (Sandbox Code Playgroud)
小智 1
如果您希望拥有更长时间的有效访问令牌,您还可以请求刷新令牌,并在旧令牌过期时使用它们生成新的访问令牌。一般访问令牌的有效期为 1 小时,您可以维护一个计时器,并在每次计时器达到 60 分钟时生成新的访问令牌。这样您就可以获得更长会话的有效访问令牌。
您必须使用grant_type=refresh_token https://www.rfc-editor.org/rfc/rfc6749#section-6
| 归档时间: |
|
| 查看次数: |
506 次 |
| 最近记录: |