keenlabs / KeenClient-Python

Official Python client for the Keen IO API. Build analytics features directly into your Python apps.
https://keen.io/docs
MIT License
133 stars 58 forks source link

saved_queries.create() raises KeenApiError #119

Closed masojus closed 7 years ago

masojus commented 7 years ago

When attempting to create a Saved Query by passing in a dict representing the query attributes, the SDK fails unless one passes that dict as a json-formatted str. This differs from other parts of the SDK like add_event(). The solution is to do as KeenApi.post_events() does and call json.dumps() to format the dict properly for a PUT body before passing it as the data argument to fulfill(): https://github.com/keenlabs/KeenClient-Python/blob/master/keen/saved_queries.py#L68

Repro steps:

import keen
from keen.client import KeenClient

keen.project_id = '<id>'
keen.master_key = '<key>'
client = KeenClient(project_id=keen.project_id, master_key=keen.master_key)

new_saved_count_query = {
    'query': {
        'analysis_type': 'average',
        'target_property': 'price',
        'event_collection': 'purchases',
        'timeframe': 'this_2_weeks'
    },
    'metadata': { 'display_name': 'Fail to create' }
}
client.saved_queries.create('new_saved_count_query', new_saved_count_query)

Expected result:

{ u'created': True,
  u'created_date': u'2017-03-12T06:15:38.604365+00:00',
  u'last_modified_date': u'2017-03-12T06:15:38.604365+00:00',
  u'metadata': { u'display_name': u'Fail to create'},
  u'query': { u'analysis_type': u'average',
              u'event_collection': u'purchases',
              u'filters': [],
              u'group_by': None,
              u'interval': None,
              u'target_property': u'price',
              u'timeframe': u'this_2_weeks',
              u'timezone': None},
  u'query_name': u'new_saved_count_query',
  u'refresh_rate': 14400,
  u'run_information': None,
  u'updated': False,
  u'urls': { u'cached_query_results_url': u'/3.0/projects/<id>/queries/saved/new_saved_count_query/
result',
             u'cached_query_url': u'/3.0/projects/<id>/queries/saved/new_saved_count_query'}}

Actual result:

...
...
  File "C:\Python27\lib\site-packages\keen\saved_queries.py", line 70, in create
    keen_api._error_handling(response)
  File "C:\Python27\lib\site-packages\keen\api.py", line 219, in _error_handling
    raise exceptions.KeenApiError(error)
keen.exceptions.KeenApiError: Error from Keen API. Details:
 Message: The specified JSON is invalid.  No JSON object could be decoded
Code: InvalidJSONError
masojus commented 7 years ago

Fixed by Pull Request #120