Skip to content

Commit 8534082

Browse files
authored
Set a default User-Agent header
1 parent 32085ed commit 8534082

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

elasticsearch/_sync/client/utils.py

+17-1
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,17 @@
3737
Union,
3838
)
3939

40-
from elastic_transport import AsyncTransport, NodeConfig, SniffOptions, Transport
40+
from elastic_transport import (
41+
AsyncTransport,
42+
HttpHeaders,
43+
NodeConfig,
44+
SniffOptions,
45+
Transport,
46+
)
4147
from elastic_transport.client_utils import (
4248
DEFAULT,
4349
client_meta_version,
50+
create_user_agent,
4451
parse_cloud_id,
4552
percent_encode,
4653
url_to_node_config,
@@ -58,6 +65,9 @@
5865
# To be passed to 'client_meta_service' on the Transport
5966
CLIENT_META_SERVICE = ("es", client_meta_version(__versionstr__))
6067

68+
# Default User-Agent used by the client
69+
USER_AGENT = create_user_agent("elasticsearch-py", __versionstr__)
70+
6171
_TYPE_HOSTS = Union[str, List[Union[str, Mapping[str, Union[str, int]], NodeConfig]]]
6272

6373
_TYPE_ASYNC_SNIFF_CALLBACK = Callable[
@@ -92,6 +102,12 @@ def client_node_configs(
92102

93103
# Remove all values which are 'DEFAULT' to avoid overwriting actual defaults.
94104
node_options = {k: v for k, v in kwargs.items() if v is not DEFAULT}
105+
106+
# Set the 'User-Agent' default header.
107+
headers = HttpHeaders(node_options.pop("headers", ()))
108+
headers.setdefault("user-agent", USER_AGENT)
109+
node_options["headers"] = headers
110+
95111
return [node_config.replace(**node_options) for node_config in node_configs]
96112

97113

test_elasticsearch/test_transport.py

+9-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
from elastic_transport import ApiResponseMeta, BaseNode, HttpHeaders, NodeConfig
2626
from elastic_transport.client_utils import DEFAULT
2727

28-
from elasticsearch import Elasticsearch
28+
from elasticsearch import Elasticsearch, __versionstr__
2929
from elasticsearch.exceptions import (
3030
ApiError,
3131
ConnectionError,
@@ -204,6 +204,14 @@ def test_opaque_id(self):
204204
assert calls[1][0] == ("GET", "/")
205205
assert calls[1][1]["headers"]["x-opaque-id"] == "request-2"
206206

207+
def test_custom_user_agent_on_initialization(self):
208+
client = Elasticsearch(
209+
"http://localhost:9200", headers={"user-agent": "custom/1.2.3"}
210+
)
211+
headers = [node.config for node in client.transport.node_pool.all()][0].headers
212+
assert list(headers.keys()) == ["user-agent"]
213+
assert headers["user-agent"].startswith(f"elasticsearch-py/{__versionstr__} (")
214+
207215
def test_request_with_custom_user_agent_header(self):
208216
client = Elasticsearch(
209217
"http://localhost:9200", meta_header=False, node_class=DummyNode

0 commit comments

Comments
 (0)