11import requests
2+ import json
23from keen import exceptions
34import json
45
@@ -16,6 +17,8 @@ class KeenApi(object):
1617 # the default version of the Keen API
1718 api_version = "3.0"
1819
20+ # self says it belongs to KeenApi/andOr is the object passed into KeenApi
21+ # __init__ create keenapi object whenever KeenApi class is invoked
1922 def __init__ (self , project_id ,
2023 write_key = None , read_key = None ,
2124 base_url = None , api_version = None ):
@@ -30,6 +33,7 @@ def __init__(self, project_id,
3033 :param api_version: string, optional, set this to override what API
3134 version is used
3235 """
36+ # super? recreates the object with values passed into KeenApi
3337 super (KeenApi , self ).__init__ ()
3438 self .project_id = project_id
3539 self .write_key = write_key
@@ -55,6 +59,7 @@ def post_event(self, event):
5559 event .event_collection )
5660 headers = {"Content-Type" : "application/json" , "Authorization" : self .write_key }
5761 payload = event .to_json ()
62+ print payload
5863 response = requests .post (url , data = payload , headers = headers )
5964 if response .status_code != 201 :
6065 error = response .json ()
@@ -80,4 +85,26 @@ def query(self, analysis_type, params):
8085 error = response .json ()
8186 raise exceptions .KeenApiError (error )
8287
83- return response .json ()["result" ]
88+ return response .json ()["result" ]
89+
90+ def post_events (self , events ):
91+
92+ """
93+ Posts a single event to the Keen IO API. The write key must be set first.
94+
95+ :param event: an Event to upload
96+ """
97+ if not self .write_key :
98+ raise Exception ("The Keen IO API requires a write key to send events. "
99+ "Please set a 'write_key' when initializing the "
100+ "KeenApi object." )
101+
102+ url = "{0}/{1}/projects/{2}/events" .format (self .base_url , self .api_version ,
103+ self .project_id )
104+ headers = {"Content-Type" : "application/json" , "Authorization" : self .write_key }
105+ payload = json .dumps (events )
106+ response = requests .post (url , data = payload , headers = headers )
107+ print payload
108+ if response .status_code != 200 :
109+ error = response .json ()
110+ raise exceptions .KeenApiError (error )
0 commit comments