U viOb@sdZddlZddlZddlZddlmZddlmZddlm Z ddl m Z ddl m Z ddl mZmZmZmZddlZdd lmZmZdd lmZdd lmZdd lmZdd lmZmZddl m!Z!ddl"m#Z#ddl$m%Z%m&Z&ddl'm(Z(ddl)m*Z*e+dZ,er ddl-Z-ddl-m.Z.Gddde Z/Gddde0Z1e1e/j2dZ3e1e/j4dZ5Gddde0Z6Gddde0Z7Gddde0Z8Gd d!d!e0Z9d"d#Z:Gd$d%d%eZ;dS)&zECollect and write time series data to InfluxDB Cloud or InfluxDB OSS.N) defaultdict) timedelta)Enum)random)sleep)UnionAnyIterable NamedTuple) operators Observable)ThreadPoolScheduler)Subject)WritePrecision) _BaseWriteApi_HAS_DATACLASS)get_org_query_param)DataframeSerializer)PointDEFAULT_WRITE_PRECISION) WritesRetry)_UTF_8_encodingz influxdb_client.client.write_api) dataclassc@seZdZdZdZdZdZdS) WriteTypez3Configuration which type of writes will client use.N)__name__ __module__ __qualname____doc__batching asynchronous synchronousr$r$Q/opt/alt/python38/lib/python3.8/site-packages/influxdb_client/client/write_api.pyr#src @sXeZdZdZejddddddddd ed d f ed d ddZddZddZ ddZ d S) WriteOptionszWrite configuration.riiHi rir max_workersN) write_typereturnc CsF||_||_||_||_||_||_||_||_| |_| |_ | |_ dS)aw Create write api configuration. :param write_type: methods of write (batching, asynchronous, synchronous) :param batch_size: the number of data point to collect in batch :param flush_interval: flush data at least in this interval (milliseconds) :param jitter_interval: this is primarily to avoid large write spikes for users running a large number of client instances ie, a jitter of 5s and flush duration 10s means flushes will happen every 10-15s (milliseconds) :param retry_interval: the time to wait before retry unsuccessful write (milliseconds) :param max_retries: the number of max retries when write fails, 0 means retry is disabled :param max_retry_delay: the maximum delay between each retry attempt in milliseconds :param max_retry_time: total timeout for all retry attempts in milliseconds, if 0 retry is disabled :param exponential_base: base for the exponential retry delay :parama max_close_wait: the maximum time to wait for writes to be flushed if close() is called :param write_scheduler: N) r+ batch_sizeflush_intervaljitter_intervalretry_interval max_retriesmax_retry_delaymax_retry_timeexponential_basewrite_schedulermax_close_wait) selfr+r-r.r/r0r1r2r3r4r6r5r$r$r%__init__.szWriteOptions.__init__c Ks>t|j|jd|jd|jd|jd|j|dddgdS)a" Create a Retry strategy from write options. :key retry_callback: The callable ``callback`` to run after retryable error occurred. The callable must accept one argument: - `Exception`: an retryable error r'retry_callbackNPOST)totalr0r/r2r3r4r9allowed_methods)rr1r0r/r2r3r4get)r7kwargsr$r$r%to_retry_strategyUs zWriteOptions.to_retry_strategycCs|j}|d=|S)4Return a dict of attributes that you want to pickle.r5__dict__copyr7stater$r$r% __getstate__gs zWriteOptions.__getstate__cCs|j|tdd|_dS)'Set your object with the provided dict.rr)N)rBupdater r5rDr$r$r% __setstate__ns zWriteOptions.__setstate__) rrrr rr!r r8r?rFrIr$r$r$r%r&+s$  'r&)r+c@s8eZdZdZddddZeddZdddd ZdS) PointSettingszSettings to store default tags.Nr,cKs*t|_|D]\}}|||qdS)z Create point settings for write api. :param default_tags: Default tags which will be added to each point written by api. N)dict defaultTagsitemsadd_default_tag)r7Z default_tagskeyvalr$r$r%r8|szPointSettings.__init__cCs"|drtj|ddS|S)Nz${env.) startswithosenvironr=)valuer$r$r% _get_values zPointSettings._get_valuecCs|||j|<dS)z'Add new default tag with key and value.N)rXrM)r7rPrWr$r$r%rOszPointSettings.add_default_tag)rrrr r8 staticmethodrXrOr$r$r$r%rJys   rJc@sJeZdZefddddZedddZeeddd Z e dd d Z dS) _BatchItemKeyNrKcCs||_||_||_dSN)bucketorg precision)r7r\r]r^r$r$r%r8sz_BatchItemKey.__init__cCst|j|j|jfSr[)hashr\r]r^r7r$r$r%__hash__sz_BatchItemKey.__hash__)or,cCs0t||jo.|j|jko.|j|jko.|j|jkSr[) isinstance __class__r\r]r^)r7rbr$r$r%__eq__s    z_BatchItemKey.__eq__cCs dt|jt|jt|jS)Nz4_BatchItemKey[bucket:'{}', org:'{}', precision:'{}'])formatstrr\r]r^r`r$r$r%__str__s z_BatchItemKey.__str__) rrrrr8intraobjectboolrergrhr$r$r$r%rZsrZc@s@eZdZd eddddZeeefdddZedd d ZdS) _BatchItemrN)rPr,cCs||_||_||_dSr[rPdatasize)r7rPrnror$r$r%r8sz_BatchItem.__init__rKcCs|jj|jj|jjfSr[)rPr\r]r^r`r$r$r% to_key_tuplesz_BatchItem.to_key_tuplecCsdt|jt|jS)Nz _BatchItem[key:'{}', size: '{}'])rfrgrPror`r$r$r%rhsz_BatchItem.__str__)r)rrrrZr8rgrprhr$r$r$r%rlsrlc@s,eZdZdeedddZedddZdS) _BatchResponseNrn exceptioncCs||_||_dSr[rr)r7rnrsr$r$r%r8sz_BatchResponse.__init__rKcCsd|jrdndt|jS)Nz!_BatchResponse[status:'{}', '{}']failedsuccess)rfrsrgrnr`r$r$r%rhs z_BatchResponse.__str__)N)rrrrl Exceptionr8rgrhr$r$r$r%rqsrqcCsdtdd|S)N cSs|jSr[rn batch_itemr$r$r%z_body_reduce..)joinmap)Z batch_itemsr$r$r% _body_reducesrcseZdZdZeefeeddfdd Zddefeee ee de e de e de e d eee d d e d f eed d dZddZddZddZddZddZefddZedddZddZeed d!d"Zd#d$Zed%d&d'Z e!d(d)Z"d*d+Z#d,d-Z$d.d/Z%Z&S)0WriteApia Implementation for '/api/v2/write' endpoint. Example: .. code-block:: python from influxdb_client import InfluxDBClient from influxdb_client.client.write_api import SYNCHRONOUS # Initialize SYNCHRONOUS instance of WriteApi with InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org") as client: write_api = client.write_api(write_options=SYNCHRONOUS) N) write_optionspoint_settingsr,c stj||d|_|dd_|dd_|dd_d_jjt j krt _ t d_j tj|jt|jdjdtd d td d tjfd d d tjjj_n d_ d_jjt jkrd}t|t dS)a Initialize defaults. :param influxdb_client: with default settings (organization) :param write_options: write api configuration :param point_settings: settings to store default tags. :key success_callback: The callable ``callback`` to run after successfully writen a batch. The callable must accept two arguments: - `Tuple`: ``(bucket, organization, precision)`` - `str`: written data **[batching mode]** :key error_callback: The callable ``callback`` to run after unsuccessfully writen a batch. The callable must accept three arguments: - `Tuple`: ``(bucket, organization, precision)`` - `str`: written data - `Exception`: an occurred error **[batching mode]** :key retry_callback: The callable ``callback`` to run after retryable error occurred. The callable must accept three arguments: - `Tuple`: ``(bucket, organization, precision)`` - `str`: written data - `Exception`: an retryable error **[batching mode]** )influxdb_clientrsuccess_callbackNerror_callbackr9rZ milliseconds)countZtimespan schedulercSs&|tddtddtS)NcSs|jSr[)rPryr$r$r%r{ r|z5WriteApi.__init__....csttfddS)Ncstjt|t|dS)Nrm)rlrPrlen)xsgroupr$r%r{r|zGWriteApi.__init__......)pipeopsZ to_iterabler~rr$rr%r{s)rrZgroup_byr~ merge_all)Zwindowr$r$r%r{ s  z#WriteApi.__init__..cSs |jdkS)Nr)robatchr$r$r%r{r|csj|dS)Nrndelay) _to_response _jitter_delayrr`r$r%r{r|)ZmapperzThe 'WriteType.asynchronous' is deprecated and will be removed in future major version. You can use native asynchronous version of the client: - https://influxdb-client.readthedocs.io/en/stable/usage.html#how-to-use-asyncio )!superr8_write_optionsr=_success_callback_error_callback_retry_callback_window_schedulerr+rr!r_subjectr rrZwindow_with_time_or_countr-rr.Zflat_mapfilterr~r subscribe_on_next _on_error _on_complete _disposabler"warningswarnDeprecationWarning)r7rrrr>messagerdr`r%r8s8#   zWriteApi.__init__rgrrLbytesr r)r\r]recordwrite_precisionr,c  stjd|jjtjkr:j||f|Stt }j |||f|jjtj krfdndfdd}t t || }sdSt|dkr|dS|S) aQ Write time-series data into InfluxDB. :param str bucket: specifies the destination bucket for writes (required) :param str, Organization org: specifies the destination organization for writes; take the ID, Name or Organization. If not specified the default value from ``InfluxDBClient.org`` is used. :param WritePrecision write_precision: specifies the precision for the unix timestamps within the body line-protocol. The precision specified on a Point has precedes and is use for write. :param record: Point, Line Protocol, Dictionary, NamedTuple, Data Classes, Pandas DataFrame or RxPY Observable to write :key data_frame_measurement_name: name of measurement for writing Pandas DataFrame - ``DataFrame`` :key data_frame_tag_columns: list of DataFrame columns which are tags, rest columns will be fields - ``DataFrame`` :key data_frame_timestamp_column: name of DataFrame column which contains a timestamp. The column can be defined as a :class:`~str` value formatted as `2018-10-26`, `2018-10-26 12:00`, `2018-10-26 12:00:00-05:00` or other formats and types supported by `pandas.to_datetime `_ - ``DataFrame`` :key data_frame_timestamp_timezone: name of the timezone which is used for timestamp column - ``DataFrame`` :key record_measurement_key: key of record with specified measurement - ``dictionary``, ``NamedTuple``, ``dataclass`` :key record_measurement_name: static measurement name - ``dictionary``, ``NamedTuple``, ``dataclass`` :key record_time_key: key of record with specified timestamp - ``dictionary``, ``NamedTuple``, ``dataclass`` :key record_tag_keys: list of record keys to use as a tag - ``dictionary``, ``NamedTuple``, ``dataclass`` :key record_field_keys: list of record keys to use as a field - ``dictionary``, ``NamedTuple``, ``dataclass`` Example: .. code-block:: python # Record as Line Protocol write_api.write("my-bucket", "my-org", "h2o_feet,location=us-west level=125i 1") # Record as Dictionary dictionary = { "measurement": "h2o_feet", "tags": {"location": "us-west"}, "fields": {"level": 125}, "time": 1 } write_api.write("my-bucket", "my-org", dictionary) # Record as Point from influxdb_client import Point point = Point("h2o_feet").tag("location", "us-west").field("level", 125).time(1) write_api.write("my-bucket", "my-org", point) DataFrame: If the ``data_frame_timestamp_column`` is not specified the index of `Pandas DataFrame `_ is used as a ``timestamp`` for written data. The index can be `PeriodIndex `_ or its must be transformable to ``datetime`` by `pandas.to_datetime `_. If you would like to transform a column to ``PeriodIndex``, you can use something like: .. code-block:: python import pandas as pd # DataFrame data_frame = ... # Set column as Index data_frame.set_index('column_name', inplace=True) # Transform index to PeriodIndex data_frame.index = pd.to_datetime(data_frame.index, unit='s') )r]clientTFcs$d|d}||dS)Nrwrr)r} _post_write)payloadZ final_string _async_reqr\r]r7r$r% write_payloadysz%WriteApi.write..write_payloadNrr)r_influxdb_clientZ_append_default_tagsrr+rr!_write_batchingrlist _serializer"r~rNr) r7r\r]rrr>Zpayloadsrresultsr$rr%write$s$H   zWriteApi.writecCsdS)z Flush data.Nr$r`r$r$r%flushszWriteApi.flushcCs |dS)z)Flush data and dispose a batching buffer.N)__del__r`r$r$r%closeszWriteApi.closecCs|S)u Enter the runtime context related to this object. It will bind this method’s return value to the target(s) specified in the `as` clause of the statement. return: self instance r$r`r$r$r% __enter__s zWriteApi.__enter__cCs |dS)zGExit the runtime context related to this object and close the WriteApi.N)r)r7exc_typeexc_valexc_tbr$r$r%__exit__szWriteApi.__exit__cCs|jrd|j|jd|_|jjd}d}d}|jjsdt|||7}||kr4t d|qdq4|j r|j j j ddd|_ |jrd|_dS)zClose WriteApi.Nr'rg?zXReached max_close_wait (%s seconds) waiting for batches to finish writing. Force closingF)wait) rZ on_completeddisposerr6rZ is_disposedrloggerwarningrexecutorshutdown)r7Z max_wait_timeZwaitedZ sleep_periodr$r$r%rs,   zWriteApi.__del__c  st|tr.t}jt||dn~t|trVj|t fnVt|t r~j| |j fn.t|t rjt j|fdifndt|jkrt|jjjf}t|jD]}j||fqnt|dr*j|fntrXt|rXjt|fnTt|tr|D]} j| fqhn&t|tr| fdddS)N)rPrnrZ DataFrame_asdictcsj|fSr[)r)itr\r>r]r^r7r$r%r{r|z*WriteApi._write_batching..)!rcrrZrZon_nextrlrgrencoderrZto_line_protocolrrL from_dicttyperr_point_settingsrr-rangeZnumber_of_chunks serializehasattrrr dataclasses is_dataclassasdictr r r) r7r\r]rnr^r>_key serializerZ chunk_idxitemr$rr%rsL        zWriteApi._write_batchingrycsrtdjr"fdd}nd}jj|d}jdjjjjj jj d|idtdt d S) Nz(Write time series data into InfluxDB: %scsj|Sr[)rrprn)rsrzr7r$r%_retry_callback_delegatesz0WriteApi._http.._retry_callback_delegate)r9Fretries) urlopen_kwzWrite request finished %srx) rdebugrrr?rrPr\r]rnr^rq)r7rzrretryr$rr%_https  zWriteApi._httpc Ks |jjf|||||dd|S)Nztext/plain; charset=utf-8)r]r\bodyr^Z async_req content_type)_write_serviceZ post_write)r7rr\r]rr^r>r$r$r%rs zWriteApi._post_writerc sLttjjtj|jjdtfddtj fdddS)N)Zduetimercs |Sr[)r)xr`r$r%r{r|z'WriteApi._to_response..cstt|dS)N)rsrn)rxZjustrq)rssourcerxr$r%r{r|)handler) rZofrrZ subscribe_onrr5rr~Zcatch)r7rnrr$)rnr7r%r s   zWriteApi._to_responsecCstt|jjdS)Nr)rrrr/r`r$r$r%rszWriteApi._jitter_delay)responsec Cs|jrjtd|j|jrz||j|jj|jWqtk rf}ztd|W5d}~XYqXn\td||jrz||j|jjWn.tk r}ztd|W5d}~XYnXdS)Nz8The batch item wasn't processed successfully because: %sz4The configured error callback threw an exception: %sz.The batch item: %s was processed successfully.z6The configured success callback threw an exception: %s) rsrerrorrrnrprvrr)r7rer$r$r%rs  zWriteApi._on_nextcCstd|dS)Nz$unexpected error during batching: %s)rr)exr$r$r%r0szWriteApi._on_errorcCs|jtddS)Nz#the batching processor was disposed)rrrinfor`r$r$r%r4s zWriteApi._on_completecCs&|j}|d=|d=|d=|d=|S)r@rrrrrArDr$r$r%rF8s  zWriteApi.__getstate__cCs2|j||j|j|j|j|j|j|jddS)rG)rrr9N) rBrHr8rrrrrrrDr$r$r%rIBs zWriteApi.__setstate__)'rrrr r&rJr8rrgrr rrLrr r rrrrrrrrrrlrrrrrrqrrYrrrFrI __classcell__r$r$rr%rsRO  ` * *   r)sD              J