Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from typing import Dict, Optional

from algoliasearch.http.hosts import HostsCollection
from algoliasearch.http.user_agent import UserAgent


class BaseConfig:
Expand All @@ -27,9 +28,18 @@ def __init__(self, app_id: Optional[str] = None, api_key: Optional[str] = None):
self.proxies: Optional[Dict[str, str]] = None
self.hosts: Optional[HostsCollection] = None

self._user_agent: UserAgent = UserAgent()

def set_client_api_key(self, api_key: str) -> None:
"""Sets a new API key to authenticate requests."""
self.api_key = api_key
if self.headers is None:
self.headers = {}
self.headers["x-algolia-api-key"] = api_key

def add_user_agent(self, segment: str, version: Optional[str] = None) -> None:
"""adds a segment to the default user agent, and update the headers sent with each requests as well"""
self._user_agent = self._user_agent.add(segment, version)

if self.headers is not None:
self.headers["user-agent"] = self._user_agent.get()
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ def __init__(self) -> None:
def get(self) -> str:
return self.value

def add(self, segment: str, version: Optional[str] = __version__) -> Self:
self.value += "; {} ({})".format(segment, version)
def add(self, segment: str, version: Optional[str] = None) -> Self:
self.value += "; {}".format(segment)

if version is not None:
self.value += " ({})".format(version)

return self
4 changes: 4 additions & 0 deletions playground/python/app/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ def main():
client = SearchClientSync(
environ.get("ALGOLIA_APPLICATION_ID"), environ.get("ALGOLIA_ADMIN_KEY")
)
client.add_user_agent("playground")
client.add_user_agent("bar", "baz")

print("user_agent", client._config._user_agent.get())
print("client initialized", client)

try:
Expand Down
4 changes: 2 additions & 2 deletions playground/python/poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions templates/python/api.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,10 @@ class {{classname}}{{#isSyncClient}}Sync{{/isSyncClient}}:
"""Sets a new API key to authenticate requests."""
self._transporter.config.set_client_api_key(api_key)

{{^isSyncClient}}async {{/isSyncClient}}def add_user_agent(self, segment: str, version: Optional[str] = None) -> None:
"""adds a segment to the default user agent, and update the headers sent with each requests as well"""
self._transporter.config.add_user_agent(segment, version)

{{#isSearchClient}}
{{> search_helpers}}
{{/isSearchClient}}
Expand Down
6 changes: 4 additions & 2 deletions templates/python/config.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@ from algoliasearch.http.hosts import (
)
from algoliasearch.http.user_agent import UserAgent
from algoliasearch.http.base_config import BaseConfig
from algoliasearch import __version__


class {{#lambda.pascalcase}}{{client}}{{/lambda.pascalcase}}Config(BaseConfig):
def __init__(self, app_id: Optional[str], api_key: Optional[str]{{#hasRegionalHost}}, region: {{#fallbackToAliasHost}}Optional[str] = None{{/fallbackToAliasHost}}{{^fallbackToAliasHost}}str = ""{{/fallbackToAliasHost}}{{/hasRegionalHost}}) -> None:
super().__init__(app_id, api_key)

user_agent = UserAgent().add("{{#lambda.pascalcase}}{{client}}{{/lambda.pascalcase}}")
self._user_agent = UserAgent()
self.add_user_agent("{{#lambda.pascalcase}}{{client}}{{/lambda.pascalcase}}", __version__)

if app_id is None or not app_id:
raise ValueError("`app_id` is missing.")
Expand All @@ -25,7 +27,7 @@ class {{#lambda.pascalcase}}{{client}}{{/lambda.pascalcase}}Config(BaseConfig):
self.headers = {
"x-algolia-application-id": app_id,
"x-algolia-api-key": api_key,
"user-agent": user_agent.get(),
"user-agent": self._user_agent.get(),
"content-type": "application/json",
}

Expand Down
Loading