Python function returns none

If I do this query in Influxdb 1.8:

SELECT Watt from kWh WHERE groep='Droger' ORDER by time DESC LIMIT 1

It gives this result:

time Watt


2025-01-31T21:33:46.962262637Z 18.16

If I do the same using this query:

def read_energy_data(groep):
    client = InfluxDBClient(host='192.168.178.999', port=8086, username='admin', 
    password='Willem1584')
    client.switch_database('FamilieBot')
    results = client.query(("SELECT Watt from kWh WHERE groep= %s  ORDER by 
    time DESC LIMIT 1") % (groep))
    points = results.get_points()
    for item in points:
        return item[groep]

print(read_energy_data("Droger"))

It returns None

What am I doing wrong?

Hello @Aziona,
What errors are you getting?

Can you run this example?

 python

>>> from influxdb import InfluxDBClient

>>> json_body = [
    {
        "measurement": "cpu_load_short",
        "tags": {
            "host": "server01",
            "region": "us-west"
        },
        "time": "2009-11-10T23:00:00Z",
        "fields": {
            "value": 0.64
        }
    }
]

>>> client = InfluxDBClient('localhost', 8086, 'root', 'root', 'example')

>>> client.create_database('example')

>>> client.write_points(json_body)

>>> result = client.query('select value from cpu_load_short;')

>>> print("Result: {0}".format(result))

Or try a

SHOW MEASUREMENT

query instead? Explore your schema using InfluxQL | InfluxDB OSS v1 Documentation

I don’t think you shoul dhave to use switch_databases I’d try just initializing with the database you want to query from.

Did you check if your client actually connects? The IP address is invalid, since it ends in 999.

1 Like

Good point, I changed the IP and the username/password for the post only. I was finally able to do it but by changing how I pass the variable. I made it work using this. There is a tag named [groep] which contains a.o. Dryer and Oven. The measurement is named kDh.

from influxdb import InfluxDBClient

def read_energy_data(test):
client = InfluxDBClient(host=‘192.168.178.106’, port=8086, username=‘admin’, password=‘Hello1234’)
client.switch_database(‘FamilieBot’)
results = client.query((“SELECT last(Watt),groep from kWh Group by groep ORDER by time DESC LIMIT 1”) )
points = results.get_points(tags={“groep”:test})
for item in points:
return item[‘last’]
print(item[‘last’])

print(read_energy_data(‘Dryer’))
print(read_energy_data(‘Oven’))

infclient.close()

Thank you for the initialize database comment, I have now added it to the connect string. Apparently the keyword is database (and not dbname or databasename). I could not find that in the documentation on github but found it on the forum.