@@ -58,7 +58,7 @@ def add_connection(self, alias, conn):
5858 """
5959 Add a connection object, it will be passed through as-is.
6060 """
61- self ._conns [alias ] = conn
61+ self ._conns [alias ] = self . _with_user_agent ( conn )
6262
6363 def remove_connection (self , alias ):
6464 """
@@ -82,7 +82,7 @@ def create_connection(self, alias="default", **kwargs):
8282 """
8383 kwargs .setdefault ("serializer" , serializer )
8484 conn = self ._conns [alias ] = self .elasticsearch_class (** kwargs )
85- return conn
85+ return self . _with_user_agent ( conn )
8686
8787 def get_connection (self , alias = "default" ):
8888 """
@@ -96,7 +96,7 @@ def get_connection(self, alias="default"):
9696 # do not check isinstance(Elasticsearch) so that people can wrap their
9797 # clients
9898 if not isinstance (alias , str ):
99- return alias
99+ return self . _with_user_agent ( alias )
100100
101101 # connection already established
102102 try :
@@ -111,6 +111,21 @@ def get_connection(self, alias="default"):
111111 # no connection and no kwargs to set one up
112112 raise KeyError (f"There is no connection with alias { alias !r} ." )
113113
114+ def _with_user_agent (self , conn ):
115+ from . import __versionstr__ # this is here to avoid circular imports
116+
117+ # try to inject our user agent
118+ if hasattr (conn , "_headers" ):
119+ is_frozen = conn ._headers .frozen
120+ if is_frozen :
121+ conn ._headers = conn ._headers .copy ()
122+ conn ._headers .update (
123+ {"user-agent" : f"elasticsearch-dsl-py/{ __versionstr__ } " }
124+ )
125+ if is_frozen :
126+ conn ._headers .freeze ()
127+ return conn
128+
114129
115130connections = Connections ()
116131configure = connections .configure
0 commit comments