Skip to content
This repository has been archived by the owner on Apr 22, 2024. It is now read-only.

Commit

Permalink
Merge 659a338 into d370895
Browse files Browse the repository at this point in the history
  • Loading branch information
clslgrnc committed Feb 7, 2019
2 parents d370895 + 659a338 commit 0e9eca9
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 12 deletions.
9 changes: 8 additions & 1 deletion examples/tutorial.py
Expand Up @@ -13,7 +13,9 @@ def main(host='localhost', port=8086):
dbname = 'example'
dbuser = 'smly'
dbuser_password = 'my_secret_password'
query = 'select value from cpu_load_short;'
query = 'select Float_value from cpu_load_short;'
query_where = 'select Int_value from cpu_load_short where host=$host;'
bind_params = {'host': 'server01'}
json_body = [
{
"measurement": "cpu_load_short",
Expand Down Expand Up @@ -50,6 +52,11 @@ def main(host='localhost', port=8086):

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

print("Querying data: " + query_where)
result = client.query(query_where, bind_params=bind_params)

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

print("Switch user: " + user)
client.switch_user(user, password)

Expand Down
11 changes: 10 additions & 1 deletion influxdb/_dataframe_client.py
Expand Up @@ -142,6 +142,7 @@ def write_points(self,
def query(self,
query,
params=None,
bind_params=None,
epoch=None,
expected_response_code=200,
database=None,
Expand All @@ -155,6 +156,10 @@ def query(self,
:param query: the actual query string
:param params: additional parameters for the request, defaults to {}
:param bind_params: bind parameters for the query:
any variable in the query written as `$var_name` will be replaced
with `bind_params['var_name']`. Only works in the `WHERE` clause
and takes precedence over params['params']
:param epoch: response timestamps to be in epoch format either 'h',
'm', 's', 'ms', 'u', or 'ns',defaults to `None` which is
RFC3339 UTC format with nanosecond precision
Expand All @@ -172,6 +177,7 @@ def query(self,
:rtype: :class:`~.ResultSet`
"""
query_args = dict(params=params,
bind_params=bind_params,
epoch=epoch,
expected_response_code=expected_response_code,
raise_errors=raise_errors,
Expand Down Expand Up @@ -202,7 +208,10 @@ def _to_dataframe(self, rs, dropna=True):
df = pd.DataFrame(data)
df.time = pd.to_datetime(df.time)
df.set_index('time', inplace=True)
df.index = df.index.tz_localize('UTC')
try:
df.index = df.index.tz_localize('UTC')
except TypeError:
df.index = df.index.tz_convert('UTC')
df.index.name = None
result[key].append(df)
for key, data in result.items():
Expand Down
13 changes: 13 additions & 0 deletions influxdb/client.py
Expand Up @@ -345,6 +345,7 @@ def _read_chunked_response(response, raise_errors=True):
def query(self,
query,
params=None,
bind_params=None,
epoch=None,
expected_response_code=200,
database=None,
Expand All @@ -361,6 +362,12 @@ def query(self,
defaults to {}
:type params: dict
:param bind_params: bind parameters for the query:
any variable in the query written as `$var_name` will be replaced
with `bind_params['var_name']`. Only works in the `WHERE` clause
and takes precedence over params['params']
:type bind_params: dict
:param epoch: response timestamps to be in epoch format either 'h',
'm', 's', 'ms', 'u', or 'ns',defaults to `None` which is
RFC3339 UTC format with nanosecond precision
Expand Down Expand Up @@ -394,6 +401,12 @@ def query(self,
if params is None:
params = {}

if bind_params is not None:
params_dict = json.loads(params.get('params', '{}'))
params_dict.update(bind_params)
params['params'] = json.dumps(params_dict)


params['q'] = query
params['db'] = database or self._database

Expand Down
32 changes: 23 additions & 9 deletions influxdb/tests/dataframe_client_test.py
Expand Up @@ -818,13 +818,19 @@ def test_query_into_dataframe(self):
pd1 = pd.DataFrame(
[[23422]], columns=['value'],
index=pd.to_datetime(["2009-11-10T23:00:00Z"]))
pd1.index = pd1.index.tz_localize('UTC')
try:
pd1.index = pd1.index.tz_localize('UTC')
except TypeError:
pd1.index = pd1.index.tz_convert('UTC')
pd2 = pd.DataFrame(
[[23422], [23422], [23422]], columns=['value'],
index=pd.to_datetime(["2009-11-10T23:00:00Z",
"2009-11-10T23:00:00Z",
"2009-11-10T23:00:00Z"]))
pd2.index = pd2.index.tz_localize('UTC')
try:
pd2.index = pd2.index.tz_localize('UTC')
except TypeError:
pd2.index = pd2.index.tz_convert('UTC')
expected = {
('network', (('direction', ''),)): pd1,
('network', (('direction', 'in'),)): pd2
Expand All @@ -837,7 +843,7 @@ def test_query_into_dataframe(self):
assert_frame_equal(expected[k], result[k])

def test_multiquery_into_dataframe(self):
"""Test multiquyer into df for TestDataFrameClient object."""
"""Test multiquery into df for TestDataFrameClient object."""
data = {
"results": [
{
Expand Down Expand Up @@ -871,18 +877,26 @@ def test_multiquery_into_dataframe(self):
index=pd.to_datetime([
"2015-01-29 21:55:43.702900257+0000",
"2015-01-29 21:55:43.702900257+0000",
"2015-06-11 20:46:02+0000"])).tz_localize('UTC')
"2015-06-11 20:46:02+0000"]))
try:
pd1 = pd1.tz_localize('UTC')
except TypeError:
pd1 = pd1.tz_convert('UTC')
pd2 = pd.DataFrame(
[[3]], columns=['count'],
index=pd.to_datetime(["1970-01-01 00:00:00+00:00"]))\
.tz_localize('UTC')
index=pd.to_datetime(["1970-01-01 00:00:00+00:00"]))
try:
pd2 = pd2.tz_localize('UTC')
except TypeError:
pd2 = pd2.tz_convert('UTC')
expected = [{'cpu_load_short': pd1}, {'cpu_load_short': pd2}]

cli = DataFrameClient('host', 8086, 'username', 'password', 'db')
iql = "SELECT value FROM cpu_load_short WHERE region='us-west';"\
"SELECT count(value) FROM cpu_load_short WHERE region='us-west'"
iql = "SELECT value FROM cpu_load_short WHERE region=$region;"\
"SELECT count(value) FROM cpu_load_short WHERE region=$region"
bind_params = {'region': 'us-west'}
with _mocked_session(cli, 'GET', 200, data):
result = cli.query(iql)
result = cli.query(iql, bind_params=bind_params)
for r, e in zip(result, expected):
for k in e:
assert_frame_equal(e[k], r[k])
Expand Down
4 changes: 3 additions & 1 deletion influxdb/tests/server_tests/client_test_with_server.py
Expand Up @@ -440,7 +440,9 @@ def test_write_points_batch(self):
batch_size=2)
time.sleep(5)
net_in = self.cli.query("SELECT value FROM network "
"WHERE direction='in'").raw
"WHERE direction=$dir",
bind_params={'dir': 'in'}
).raw
net_out = self.cli.query("SELECT value FROM network "
"WHERE direction='out'").raw
cpu = self.cli.query("SELECT value FROM cpu_usage").raw
Expand Down

0 comments on commit 0e9eca9

Please sign in to comment.