Skip to content

Commit 7d5952f

Browse files
feat: support-basic-env
1 parent 099b9f6 commit 7d5952f

File tree

4 files changed

+105
-1
lines changed

4 files changed

+105
-1
lines changed

influxdb_client_3/__init__.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1+
import importlib.util
12
import urllib.parse
3+
24
import pyarrow as pa
3-
import importlib.util
45

56
from influxdb_client_3.query.query_api import QueryApi as _QueryApi, QueryApiOptionsBuilder
67
from influxdb_client_3.read_file import UploadFile

influxdb_client_3/write_client/client/_base.py

+50
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
import os
88
from typing import Iterable
99

10+
from typing_extensions import deprecated
11+
1012
from influxdb_client_3.write_client.client.write.dataframe_serializer import DataframeSerializer
1113
from influxdb_client_3.write_client.configuration import Configuration
1214
from influxdb_client_3.write_client.rest import _UTF_8_encoding
@@ -173,6 +175,7 @@ def _has_section(key: str):
173175
profilers=profilers, proxy=proxy, **kwargs)
174176

175177
@classmethod
178+
@deprecated('Use _from_env() instead.')
176179
def _from_env_properties(cls, debug=None, enable_gzip=False, **kwargs):
177180
url = os.getenv('INFLUXDB_V2_URL', "http://localhost:8086")
178181
token = os.getenv('INFLUXDB_V2_TOKEN', "my-token")
@@ -203,6 +206,53 @@ def _from_env_properties(cls, debug=None, enable_gzip=False, **kwargs):
203206
connection_pool_maxsize=_to_int(connection_pool_maxsize), auth_basic=_to_bool(auth_basic),
204207
profilers=profilers, **kwargs)
205208

209+
@classmethod
210+
def _from_env(cls, debug=None, enable_gzip=False, **kwargs):
211+
"""
212+
Creates and configures an instance of the class using environment variable values. The method loads
213+
configuration values for connecting to an InfluxDB server instance from preset environment variables.
214+
Options include connection details such as host, token, organization, and optional parameters
215+
like SSL settings, profiling, and default tags. Non-specified parameters fallback to defaults
216+
or None, ensuring a straightforward integration with varied InfluxDB setups.
217+
218+
:param debug: Determines whether debugging mode is enabled.
219+
:type debug: Optional[bool]
220+
:param enable_gzip: Indicates whether gzip compression is enabled for requests.
221+
:type enable_gzip: bool
222+
:param kwargs: Additional keyword arguments to configure the instance.
223+
:type kwargs: dict
224+
:return: Instance of the class configured using the provided environmental settings.
225+
:rtype: cls
226+
"""
227+
url = os.getenv('INFLUX_HOST', "http://localhost:8086")
228+
token = os.getenv('INFLUX_TOKEN', "my-token")
229+
org = os.getenv('INFLUX_ORG', "my-org")
230+
timeout = os.getenv('INFLUX_TIMEOUT', "10000")
231+
verify_ssl = os.getenv('INFLUX_VERIFY_SSL', "True")
232+
ssl_ca_cert = os.getenv('INFLUX_SSL_CA_CERT', None)
233+
cert_file = os.getenv('INFLUX_CERT_FILE', None)
234+
cert_key_file = os.getenv('INFLUX_CERT_KEY_FILE', None)
235+
cert_key_password = os.getenv('INFLUX_CERT_KEY_PASSWORD', None)
236+
connection_pool_maxsize = os.getenv('INFLUX_CONNECTION_POOL_MAXSIZE', None)
237+
auth_basic = os.getenv('INFLUX_AUTH_BASIC', "False")
238+
239+
prof = os.getenv("INFLUX_PROFILERS", None)
240+
profilers = None
241+
if prof is not None:
242+
profilers = [x.strip() for x in prof.split(',')]
243+
244+
default_tags = dict()
245+
246+
for key, value in os.environ.items():
247+
if key.startswith("INFLUX_TAG_"):
248+
default_tags[key[11:].lower()] = value
249+
250+
return cls(url, token, debug=debug, timeout=_to_int(timeout), org=org, default_tags=default_tags,
251+
enable_gzip=enable_gzip, verify_ssl=_to_bool(verify_ssl), ssl_ca_cert=ssl_ca_cert,
252+
cert_file=cert_file, cert_key_file=cert_key_file, cert_key_password=cert_key_password,
253+
connection_pool_maxsize=_to_int(connection_pool_maxsize), auth_basic=_to_bool(auth_basic),
254+
profilers=profilers, **kwargs)
255+
206256

207257
class _BaseWriteApi(object):
208258
def __init__(self, influxdb_client, point_settings=None):

influxdb_client_3/write_client/client/influxdb_client.py

+19
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
import logging
66

7+
from typing_extensions import deprecated
8+
79
from influxdb_client_3.write_client.client._base import _BaseClient
810
from influxdb_client_3.write_client.client.write_api import WriteApi, WriteOptions, PointSettings
911

@@ -167,6 +169,7 @@ def from_config_file(cls, config_file: str = "config.ini", debug=None, enable_gz
167169
return InfluxDBClient._from_config_file(config_file=config_file, debug=debug, enable_gzip=enable_gzip, **kwargs)
168170

169171
@classmethod
172+
@deprecated('Use InfluxDBClient.from_env() instead.')
170173
def from_env_properties(cls, debug=None, enable_gzip=False, **kwargs):
171174
"""
172175
Configure client via environment properties.
@@ -200,6 +203,22 @@ def from_env_properties(cls, debug=None, enable_gzip=False, **kwargs):
200203
"""
201204
return InfluxDBClient._from_env_properties(debug=debug, enable_gzip=enable_gzip, **kwargs)
202205

206+
@classmethod
207+
def from_env(cls, debug=None, enable_gzip=False, **kwargs):
208+
"""
209+
Creates an instance of the class using environment configuration variables.
210+
211+
This class method retrieves configuration variables from the system environment
212+
and uses them to configure and initialize an instance of the class. This allows
213+
for dynamic configuration of the client without the need for hardcoding values
214+
or explicitly passing them during instantiation.
215+
216+
:param debug: Enable verbose logging of http requests
217+
:param enable_gzip: Enable Gzip compression for http requests. Currently, only the "Write" and "Query" endpoints
218+
supports the Gzip compression.
219+
"""
220+
return InfluxDBClient._from_env(debug=debug, enable_gzip=enable_gzip, **kwargs)
221+
203222
def write_api(self, write_options=WriteOptions(), point_settings=PointSettings(), **kwargs) -> WriteApi:
204223
"""
205224
Create Write API instance.

tests/test_influxdb_client.py

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import unittest
2+
from unittest.mock import patch
3+
4+
import influxdb_client_3
5+
from influxdb_client_3 import WritePrecision
6+
7+
8+
class TestInfluxDBClient(unittest.TestCase):
9+
@patch.dict('os.environ', {'INFLUX_HOST': 'http://localhost:9999', 'INFLUX_TOKEN': 'test_token',
10+
'INFLUX_DATABASE': 'test_db', 'INFLUX_ORG': 'test_org',
11+
'INFLUX_PRECISION': WritePrecision.MS, 'INFLUX_TIMEOUT': '6000',
12+
'INFLUX_VERIFY_SSL': 'False',
13+
'INFLUX_CERT_FILE': 'path_to_cert', 'INFLUX_CERT_KEY_FILE': 'path_to_cert_key',
14+
'INFLUX_CERT_KEY_PASSWORD': 'cert_key_password', 'INFLUX_CONNECTION_POOL_MAXSIZE': '200',
15+
'INFLUX_PROFILERS': 'prof1,prof2,prof3', 'INFLUX_TAG_NAME': 'Tag1'})
16+
def test_from_env(self):
17+
base = influxdb_client_3._InfluxDBClient.from_env(enable_gzip=True)
18+
self.assertEqual(base.url, "http://localhost:9999")
19+
self.assertEqual(base.org, "test_org")
20+
self.assertEqual(base.default_tags['name'], "Tag1")
21+
self.assertEqual(base.profilers, ['prof1', 'prof2', 'prof3'])
22+
self.assertEqual(base.conf.enable_gzip, True)
23+
self.assertEqual(base.conf.timeout, 6000)
24+
self.assertEqual(base.conf.verify_ssl, False)
25+
self.assertEqual(base.conf.connection_pool_maxsize, 200)
26+
self.assertEqual(base.conf.cert_file, "path_to_cert")
27+
self.assertEqual(base.conf.cert_key_file, "path_to_cert_key")
28+
self.assertEqual(base.conf.cert_key_password, "cert_key_password")
29+
self.assertEqual(base.auth_header_name, "Authorization")
30+
self.assertEqual(base.auth_header_value, "Token test_token")
31+
32+
33+
if __name__ == '__main__':
34+
unittest.main()

0 commit comments

Comments
 (0)