Ejemplo n.º 1
0
 async def test_init_without_token(self, mocked):
     mocked.post('http://localhost/api/v2/query?org=my-org',
                 status=200,
                 body='')
     await self.client.close()
     self.client = InfluxDBClientAsync("http://localhost")
     await self.client.query_api().query("buckets()", "my-org")
async def main():
    """
    Configure Retries - for more info see https://github.com/inyutin/aiohttp_retry
    """
    retry_options = ExponentialRetry(attempts=3)
    async with InfluxDBClientAsync(
            url="http://localhost:8086",
            token="my-token",
            org="my-org",
            client_session_type=RetryClient,
            client_session_kwargs={"retry_options": retry_options}) as client:
        """
        Write data:
        """
        print(f"\n------- Written data: -------\n")
        write_api = client.write_api()
        _point1 = Point("async_m").tag("location",
                                       "Prague").field("temperature", 25.3)
        _point2 = Point("async_m").tag("location",
                                       "New York").field("temperature", 24.3)
        successfully = await write_api.write(bucket="my-bucket",
                                             record=[_point1, _point2])
        print(f" > successfully: {successfully}")
        """
        Query: Stream of FluxRecords
        """
        print(f"\n------- Query: Stream of FluxRecords -------\n")
        query_api = client.query_api()
        records = await query_api.query_stream(
            'from(bucket:"my-bucket") '
            '|> range(start: -10m) '
            '|> filter(fn: (r) => r["_measurement"] == "async_m")')
        async for record in records:
            print(record)
Ejemplo n.º 3
0
 async def test_username_password_authorization(self):
     await self.client.close()
     self.client = InfluxDBClientAsync(url="http://localhost:8086",
                                       username="******",
                                       password="******",
                                       debug=True)
     await self.client.query_api().query("buckets()", "my-org")
Ejemplo n.º 4
0
 def test_initialize_out_side_async_context(self):
     with pytest.raises(InfluxDBError) as e:
         InfluxDBClientAsync(url="http://localhost:8086",
                             token="my-token",
                             org="my-org")
     self.assertEqual(
         "The async client should be initialised inside async coroutine "
         "otherwise there can be unexpected behaviour.", e.value.message)
async def main():
    async with InfluxDBClientAsync(url='http://localhost:8086',
                                   token='my-token',
                                   org='my-org') as client:
        # Initialize async OrganizationsService
        organizations_service = OrganizationsService(
            api_client=client.api_client)

        # Find organization with name 'my-org'
        organizations = await organizations_service.get_orgs(org='my-org')
        for organization in organizations.orgs:
            print(f'name: {organization.name}, id: {organization.id}')
Ejemplo n.º 6
0
    async def test_redacted_auth_header(self):
        await self.client.close()
        self.client = InfluxDBClientAsync(url="http://localhost:8086",
                                          token="my-token",
                                          org="my-org",
                                          debug=True)

        log_stream = StringIO()
        logger = logging.getLogger("influxdb_client.client.http")
        logger.addHandler(logging.StreamHandler(log_stream))

        await self.client.query_api().query("buckets()", "my-org")

        self.assertIn("Authorization: ***", log_stream.getvalue())
Ejemplo n.º 7
0
 async def test_query_and_debug(self):
     await self.client.close()
     self.client = InfluxDBClientAsync(url="http://localhost:8086",
                                       token="my-token",
                                       debug=True)
     # Query
     results = await self.client.query_api().query("buckets()", "my-org")
     self.assertIn(
         "my-bucket",
         list(map(lambda record: record["name"], results[0].records)))
     # Query RAW
     results = await self.client.query_api().query_raw(
         "buckets()", "my-org")
     self.assertIn("my-bucket", results)
     # Bucket API
     buckets_service = BucketsService(api_client=self.client.api_client)
     results = await buckets_service.get_buckets()
     self.assertIn("my-bucket",
                   list(map(lambda bucket: bucket.name, results.buckets)))
async def main():
    async with InfluxDBClientAsync(url='http://localhost:8086',
                                   token='my-token',
                                   org='my-org') as client:
        write_api = client.write_api()
        """
        Async write
        """
        async def async_write(batch):
            """
            Prepare async task
            """
            await write_api.write(bucket='my-bucket', record=batch)
            return batch

        """
        Prepare batches from generator
        """
        batches = rx \
            .from_iterable(csv_to_generator('vix-daily.csv')) \
            .pipe(ops.buffer_with_count(500)) \
            .pipe(ops.map(lambda batch: rx.from_future(asyncio.ensure_future(async_write(batch)))), ops.merge_all())

        done = asyncio.Future()
        """
        Write batches by subscribing to Rx generator
        """
        batches.subscribe(
            on_next=lambda batch: print(f'Written batch... {len(batch)}'),
            on_error=lambda ex: print(f'Unexpected error: {ex}'),
            on_completed=lambda: done.set_result(0),
            scheduler=AsyncIOScheduler(asyncio.get_event_loop()))
        """
        Wait to finish all writes
        """
        await done
Ejemplo n.º 9
0
 async def setUp(self) -> None:
     self.client = InfluxDBClientAsync(url="http://localhost:8086",
                                       token="my-token",
                                       org="my-org")
Ejemplo n.º 10
0
async def main():
    async with InfluxDBClientAsync(url="http://localhost:8086", token="my-token", org="my-org") as client:
        """
        Check the version of the InfluxDB
        """
        version = await client.version()
        print(f"\n------- Version -------\n")
        print(f"InfluxDB: {version}")

        """
        Prepare data
        """
        print(f"\n------- Write data by async API: -------\n")
        write_api = client.write_api()
        _point1 = Point("async_m").tag("location", "Prague").field("temperature", 25.3)
        _point2 = Point("async_m").tag("location", "New York").field("temperature", 24.3)
        successfully = await write_api.write(bucket="my-bucket", record=[_point1, _point2])
        print(f" > successfully: {successfully}")

        """
        Query: List of FluxTables
        """
        query_api = client.query_api()
        print(f"\n------- Query: List of FluxTables -------\n")
        tables = await query_api.query('from(bucket:"my-bucket") '
                                       '|> range(start: -10m) '
                                       '|> filter(fn: (r) => r["_measurement"] == "async_m")')

        for table in tables:
            for record in table.records:
                print(f'Temperature in {record["location"]} is {record["_value"]}')

        """
        Query: Stream of FluxRecords
        """
        print(f"\n------- Query: Stream of FluxRecords -------\n")
        query_api = client.query_api()
        records = await query_api.query_stream('from(bucket:"my-bucket") '
                                               '|> range(start: -10m) '
                                               '|> filter(fn: (r) => r["_measurement"] == "async_m")')
        async for record in records:
            print(record)

        """
        Query: Pandas DataFrame
        """
        print(f"\n------- Query: Pandas DataFrame -------\n")
        query_api = client.query_api()
        dataframe = await query_api.query_data_frame('from(bucket:"my-bucket") '
                                                     '|> range(start: -10m) '
                                                     '|> filter(fn: (r) => r["_measurement"] == "async_m")'
                                                     ' |> group()')
        print(dataframe)

        """
        Query: String output
        """
        print(f"\n------- Query: String output -------\n")
        query_api = client.query_api()
        raw = await query_api.query_raw('from(bucket:"my-bucket") '
                                        '|> range(start: -10m) '
                                        '|> filter(fn: (r) => r["_measurement"] == "async_m")')
        print(raw)

        """
        Delete data
        """
        print(f"\n------- Delete data with location = 'Prague' -------\n")
        successfully = await client.delete_api().delete(start=datetime.utcfromtimestamp(0), stop=datetime.now(),
                                                        predicate="location = \"Prague\"", bucket="my-bucket")
        print(f" > successfully: {successfully}")