Search code examples
pythoninfluxdbgetenv

InfluxDB : cant connect with the client because of my token and os.getenv


I am just starting with InfluxDB. On the UI there is a section for Python to start with the database with an example: initialize the client, write data, make a request and close the client. In order to authenticate the request you have to generate a token on the UI which allows to secure the request. But when I run the example code I get the error "can only concatenate str (not "NoneType") to str" from line 12 of my code.

The code :

from datetime import datetime
import os

from influxdb_client import InfluxDBClient, Point, WritePrecision
from influxdb_client.client.write_api import SYNCHRONOUS

# You can generate an API token from the "API Tokens Tab" in the UI
token = os.getenv("INFLUX_TOKEN")
org = "XXXXXXX"
bucket = "XXXXXXX Bucket"

with InfluxDBClient(url="https://europe-west1-1.gcp.cloud2.influxdata.com", token=token, org=org) as client:

    write_api = client.write_api(write_options=SYNCHRONOUS)
    point = Point("mem") \
        .tag("host", "host1") \
        .field("used_percent", 23.43234543) \
        .time(datetime.utcnow(), WritePrecision.NS)

    write_api.write(bucket, org, point)
    
    query = """from(bucket: "XXXXXXX Bucket") |> range(start: -1h)"""
    tables = client.query_api().query(query, org=org)
    for table in tables:
        for record in table.records:
            print(record)
            
    client.close()

I understand that the problem come from the os.getenv("INFLUX_TOKEN") because it's supposed to return a string but actually return NoneType object, but I dont know why it doesn't work. With the token I got 2 things : the name of the token and its code which I obtain when when it's created. I've tried :

  • os.getenv("the name of the token")
  • os.getenv("the code of the token")
  • same of 2 above but with ' instead of "

All the time the same error, so please if someone can help me!


Solution

  • You actually have a problem with your environment variable if os.getenv("INFLUX_TOKEN") returns None it means that INFLUX_TOKEN variable is not set.

    You can manually set it in your shell, after you generate the token by typing in your ssh shell

    export INFLUX_TOKEN="your-influx-token"

    You can find more about the environment variables here