ya-dao commented on issue #6241:
URL: https://github.com/apache/doris/issues/6241#issuecomment-2919498744
Here is a Python 2.7 code demo powered by AI, which has worked for my need,
the key point is to rebuild authorization header after redirect manually.
```python
import requests
import base64
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
# 生成Base64编码的认证头
auth_str = "xxx:yyy"
auth_encoded = base64.b64encode(auth_str.encode('utf-8')).decode('utf-8')
auth_header = 'Basic %s' % auth_encoded
url = 'http://1.2.3.4:8030/api/test_db/test_streamload_table/_stream_load'
headers = {
'format': 'json',
'Expect': '100-continue',
'strip_outer_array': 'true',
'num_as_string': 'true',
'column_separator': ',',
'columns': '`id`,`name`',
'Content-Type': 'application/json',
'Authorization': auth_header
}
data = """[
{
"id": 2,
"name": "Bob"
},
{
"id": 1,
"name": "Alice"
}
]"""
# 创建一个自定义的Session,处理重定向时保留认证头
class AuthRedirectSession(requests.Session):
def rebuild_auth(self, prepared_request, response):
# 在重定向时保留Authorization头
if 'Authorization' in self.headers:
prepared_request.headers['Authorization'] =
self.headers['Authorization']
return super(AuthRedirectSession,
self).rebuild_auth(prepared_request, response)
try:
# 使用自定义Session
session = AuthRedirectSession()
# 设置重试策略(可选)
retries = Retry(
total=3,
backoff_factor=1,
status_forcelist=[500, 502, 503, 504]
)
session.mount('http://', HTTPAdapter(max_retries=retries))
# 发送请求,禁用自动重定向
response = session.put(url, headers=headers, data=data,
allow_redirects=False)
# 手动处理重定向
if response.status_code in (301, 302, 303, 307, 308):
redirect_url = response.headers['Location']
print("重定向到: %s" % redirect_url)
# 发送重定向请求,携带原始认证头
redirect_response = session.put(redirect_url, headers=headers,
data=data)
redirect_response.raise_for_status()
print("请求成功")
print(redirect_response.text)
else:
# 处理非重定向响应
response.raise_for_status()
print("请求成功")
print(response.text)
except requests.exceptions.RequestException as e:
print("请求失败:", e)
if 'response' in locals() and response:
print("状态码:", response.status_code)
print("响应内容:", response.text)
```
<img width="648" alt="Image"
src="https://github.com/user-attachments/assets/4f63fc95-8853-4b52-952b-3d9248cb3bcd"
/>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]