Example #1
0
    async def delete(self,
                     start: Union[str, datetime],
                     stop: Union[str, datetime],
                     predicate: str,
                     bucket: str,
                     org: Union[str, Organization, None] = None) -> bool:
        """
        Delete Time series data from InfluxDB.

        :param str, datetime.datetime start: start time
        :param str, datetime.datetime stop: stop time
        :param str predicate: predicate
        :param str bucket: bucket id or name from which data will be deleted
        :param str, Organization org: specifies the organization to delete data from.
                                      Take the ``ID``, ``Name`` or ``Organization``.
                                      If not specified the default value from ``InfluxDBClientAsync.org`` is used.
        :return: ``True`` for successfully deleted data, otherwise raise an exception
        """
        predicate_request = self._prepare_predicate_request(
            start, stop, predicate)
        org_param = get_org_query_param(org=org,
                                        client=self._influxdb_client,
                                        required_id=False)

        response = await self._service.post_delete_async(
            delete_predicate_request=predicate_request,
            bucket=bucket,
            org=org_param)
        return response[1] == 204
Example #2
0
    def test_not_permission_to_read_org(self):
        # Create Token without permission to read Organizations
        resource = PermissionResource(type="buckets",
                                      org_id=self.find_my_org().id)
        authorization = self.client \
            .authorizations_api() \
            .create_authorization(org_id=self.find_my_org().id,
                                  permissions=[Permission(resource=resource, action="read"),
                                               Permission(resource=resource, action="write")])
        self.client.close()

        # Initialize client without permission to read Organizations
        self.client = InfluxDBClient(url=self.client.url,
                                     token=authorization.token)

        with pytest.raises(InfluxDBError) as e:
            get_org_query_param("my-org", self.client, required_id=True)
        assert "The client cannot find organization with name: 'my-org' to determine their ID. Are you using token " \
               "with sufficient permission?" in f"{e.value} "
Example #3
0
    def create_bucket(self,
                      bucket=None,
                      bucket_name=None,
                      org_id=None,
                      retention_rules=None,
                      description=None,
                      org=None) -> Bucket:
        """Create a bucket.

        :param Bucket bucket: bucket to create
        :param bucket_name: bucket name
        :param description: bucket description
        :param org_id: org_id
        :param bucket_name: bucket name
        :param retention_rules: retention rules array or single BucketRetentionRules
        :param str, Organization org: specifies the organization for create the bucket;
                                      Take the ``ID``, ``Name`` or ``Organization``.
                                      If not specified the default value from ``InfluxDBClient.org`` is used.
        :return: Bucket
                 If the method is called asynchronously,
                 returns the request thread.
        """
        if retention_rules is None:
            retention_rules = []

        rules = []

        if isinstance(retention_rules, list):
            rules.extend(retention_rules)
        else:
            rules.append(retention_rules)

        if org_id is not None:
            warnings.warn("org_id is deprecated; use org", DeprecationWarning)

        if bucket is None:
            bucket = PostBucketRequest(
                name=bucket_name,
                retention_rules=rules,
                description=description,
                org_id=get_org_query_param(
                    org=(org_id if org is None else org),
                    client=self._influxdb_client,
                    required_id=True))

        return self._buckets_service.post_buckets(post_bucket_request=bucket)
Example #4
0
    def delete(self, start: Union[str, datetime], stop: Union[str, datetime], predicate: str, bucket: str,
               org: Union[str, Organization, None] = None) -> None:
        """
        Delete Time series data from InfluxDB.

        :param str, datetime.datetime start: start time
        :param str, datetime.datetime stop: stop time
        :param str predicate: predicate
        :param str bucket: bucket id or name from which data will be deleted
        :param str, Organization org: specifies the organization to delete data from.
                                      Take the ``ID``, ``Name`` or ``Organization``.
                                      If not specified the default value from ``InfluxDBClient.org`` is used.
        :return:
        """
        predicate_request = self._prepare_predicate_request(start, stop, predicate)
        org_param = get_org_query_param(org=org, client=self._influxdb_client, required_id=False)

        return self._service.post_delete(delete_predicate_request=predicate_request, bucket=bucket, org=org_param)
    async def write(self,
                    bucket: str,
                    org: str = None,
                    record: Union[str, Iterable['str'], Point,
                                  Iterable['Point'], dict, Iterable['dict'],
                                  bytes, Iterable['bytes'], NamedTuple,
                                  Iterable['NamedTuple'], 'dataclass',
                                  Iterable['dataclass']] = None,
                    write_precision: WritePrecision = DEFAULT_WRITE_PRECISION,
                    **kwargs) -> bool:
        """
        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 ``InfluxDBClientAsync.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
        :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 <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html#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``
        :return: ``True`` for successfully accepted data, otherwise raise an exception

        Example:
            .. code-block:: python

                # Record as Line Protocol
                await 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
                }
                await 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)
                await write_api.write("my-bucket", "my-org", point)

        DataFrame:
            If the ``data_frame_timestamp_column`` is not specified the index of `Pandas DataFrame <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html>`_
            is used as a ``timestamp`` for written data. The index can be `PeriodIndex <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.PeriodIndex.html#pandas.PeriodIndex>`_
            or its must be transformable to ``datetime`` by
            `pandas.to_datetime <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html#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')

        """  # noqa: E501
        org = get_org_query_param(org=org, client=self._influxdb_client)
        self._append_default_tags(record)

        payloads = defaultdict(list)
        self._serialize(record,
                        write_precision,
                        payloads,
                        precision_from_point=False,
                        **kwargs)

        # joint list by \n
        body = b'\n'.join(payloads[write_precision])
        response = await self._write_service.post_write_async(
            org=org,
            bucket=bucket,
            body=body,
            precision=write_precision,
            async_req=False,
            content_encoding="identity",
            content_type="text/plain; charset=utf-8")
        return response[1] == 204
Example #6
0
 def test_both_none(self):
     self.client.close()
     self.client = InfluxDBClient(url=self.client.url, token="my-token")
     org = get_org_query_param(None, self.client)
     self.assertIsNone(org)
Example #7
0
 def test_required_id_not_exist(self):
     with pytest.raises(InfluxDBError) as e:
         get_org_query_param("not_exist_name",
                             self.client,
                             required_id=True)
     assert "The client cannot find organization with name: 'not_exist_name' to determine their ID." in f"{e.value} "
Example #8
0
 def test_required_id(self):
     org = get_org_query_param(None, self.client, required_id=True)
     self.assertEqual(self.my_organization.id, org)
Example #9
0
 def test_organization_as_query_param(self):
     organization = Organization(id="org-id", name="org-name")
     org = get_org_query_param(organization, self.client)
     self.assertEqual("org-id", org)
Example #10
0
 def _org_param(self, org):
     return get_org_query_param(org=org, client=self._influxdb_client)