I've searched the documentation/internet and cannot find an answer to this question. How do I pass in extra headers to http requests in say methods like elasticsearch.Elasticsearch.search? Well really it would be most convenient if I could just do it once at say instantiation of elasticsearch.Elasticsearch...
How is this most easily achieved?
Currently there is no direct way to inject your own headers. What I recommend is to subclass the connection class and modify the headers there:
from elasticsearch import Urllib3HttpConnection, Elasticsearch
class MyConnection(Urllib3HttpConnection):
def __init__(*args, **kwargs):
extra_headers = kwargs.pop('extra_headers', {})
super(MyConnection, self).__init__(*args, **kwargs)
self.headers.update(extra_headers)
es = Elasticsearch(connection_class=MyConnection, extra_headers={'Any': 'header'})
Unfortunately there is no easy way to do this on a per-api basis.
Hope this helps.
Thanks for the response! This method will probably be fine. Cheers!
NameError: global name 'self' is not defined
@gibbon88 yes, I forgot the self argument in def __init__(self, *args, **kwargs)
Thanks for the snippet @HonzaKral For anyone looking at this in future, I modified his code to allow sending a custom header with a value set at request time:
from elasticsearch import Urllib3HttpConnection
class MyUrllib3Http(Urllib3HttpConnection):
def __init__(self, *args, **kwargs):
internal_params = kwargs.pop("internal_params", {})
super(MyUrllib3Http, self).__init__(*args, **kwargs)
self.internal_params = internal_params
def perform_request(self, method, url, params=None, body=None, timeout=None, ignore=(), headers=None):
for param,header in self.internal_params.items():
if param in params:
headers = {} if headers is None else headers
headers[header] = params.pop(param)
return super().perform_request(method, url, params=params, body=body, timeout=timeout, ignore=ignore, headers=headers)
internal_params is a dict whose keys are the param keys in params and values are the header their value should be placed in.
Most helpful comment
Currently there is no direct way to inject your own headers. What I recommend is to subclass the connection class and modify the headers there:
Unfortunately there is no easy way to do this on a per-api basis.
Hope this helps.