向所有 boto3 请求添加自定义标头

mmo*_*nks 5 header-injection http-headers botocore boto3

我需要向发出的每个 boto3 请求添加一些自定义标头。有没有办法管理连接本身以添加这些标头?

对于 boto2,connection.AWSAuthConnection有一个有用的方法 build_base_http_request。不过,我还没有在 boto3 文档中找到类似的功能。

小智 5

这已经过时了,但我们遇到了同样的问题,所以我发布了我们的解决方案。

我想为特定请求向 boto3 添加自定义标头。我发现了这个:https://github.com/boto/boto3/issues/2251,并使用事件系统添加标题

def _add_header(request, **kwargs):
    request.headers.add_header('x-trace-id', 'trace-trace')
    print(request.headers)  # for debug


some_client = boto3.client(service_name=SERVICE_NAME)
event_system = some_client.meta.events
event_system.register_first('before-sign.EVENT_NAME.*', _add_header)
Run Code Online (Sandbox Code Playgroud)

您可以尝试对所有请求使用通配符:

event_system.register_first('before-sign.*.*', _add_header)
Run Code Online (Sandbox Code Playgroud)

*SERVICE_NAME- 您可以在此处找到所有可用服务:https : //boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html

有关将函数注册到特定事件的更多信息:https : //boto3.amazonaws.com/v1/documentation/api/latest/guide/events.html