2 Copyright (c) 2010 Brookhaven National Laboratory
3 All rights reserved. Use is subject to license terms and conditions.
5 Created on Jan 10, 2013
10 from json
import JSONEncoder, JSONDecoder
11 from OlogDataTypes
import LogEntry, Logbook, Tag, Property, Attachment
12 from _conf
import _conf
14 from requests
import auth
16 from urllib
import urlencode
17 from collections
import OrderedDict
24 __jsonheader = {
'content-type':
'application/json',
'accept':
'application/json'}
25 __logsResource =
'/resources/logs'
26 __propertiesResource =
'/resources/properties'
27 __tagsResource =
'/resources/tags'
28 __logbooksResource =
'/resources/logbooks'
29 __attachmentResource =
'/resources/attachments'
31 def __init__(self, url=None, username=None, password=None):
36 requests_log = logging.getLogger(
"requests")
37 requests_log.setLevel(logging.DEBUG)
41 if username
and password:
42 self.
__auth = auth.HTTPBasicAuth(username, password)
49 def __getDefaultConfig(self, arg, value):
51 If Value is None, this will try to find the value in one of the configuration files
53 if value ==
None and _conf.has_option(
'DEFAULT', arg):
54 return _conf.get(
'DEFAULT', arg)
58 def log(self, logEntry):
67 resp.raise_for_status()
70 for attachment
in logEntry.getAttachments():
74 files={
'file':attachment.getFile()}
76 resp.raise_for_status()
88 auth=self.
__auth).raise_for_status()
100 auth=self.
__auth).raise_for_status()
112 auth=self.
__auth).raise_for_status()
116 Search for logEntries based on one or many search criteria
117 >> find(search='*Timing*')
118 find logentries with the text Timing in the description
120 >> find(tag='magnets')
121 find log entries with the a tag named 'magnets'
123 >> find(logbook='controls')
124 find log entries in the logbook named 'controls'
126 >> find(property='context')
127 find log entires with property named 'context'
129 >> find(start=str(time.time() - 3600)
130 find the log entries made in the last hour
131 >> find(start=123243434, end=123244434)
132 find all the log entries made between the epoc times 123243434 and 123244434
134 Searching using multiple criteria
135 >>find(logbook='contorls', tag='magnets')
136 find all the log entries in logbook 'controls' AND with tag named 'magnets'
140 resp = requests.get(query_string,
145 resp.raise_for_status()
147 for jsonLogEntry
in resp.json():
153 Search for attachments on logentry _id_
158 resp.raise_for_status()
160 for jsonAttachment
in resp.json().pop(
'attachment'):
161 fileName = jsonAttachment.pop(
'fileName')
162 f = requests.get(self.
__url+
167 testFile = tempfile.NamedTemporaryFile(delete=
False)
168 testFile.name = fileName
169 testFile.write(f.content)
170 attachments.append(Attachment(file=testFile))
181 resp.raise_for_status()
183 for jsonTag
in resp.json().pop(
'tag'):
195 resp.raise_for_status()
197 for jsonLogbook
in resp.json().pop(
'logbook'):
203 List all Properties and their attributes
209 resp.raise_for_status()
211 for jsonProperty
in resp.json().pop(
'property'):
218 Method to delete a logEntry, logbook, property, tag
219 delete(logEntryId = int)
220 >>> delete(logEntryId=1234)
222 delete(logbookName = String)
223 >>> delete(logbookName = 'logbookName')
225 delete(tagName = String)
226 >>> delete(tagName = 'myTag')
227 # tagName = tag name of the tag to be deleted (it will be removed from all logEntries)
229 delete(propertyName = String)
230 >>> delete(propertyName = 'position')
231 # propertyName = property name of property to be deleted (it will be removed from all logEntries)
236 raise Exception,
'incorrect usage: Delete a single Logbook/tag/property'
239 def __handleSingleDeleteParameter(self, **kwds):
240 if 'logbookName' in kwds:
244 auth=self.
__auth).raise_for_status()
246 elif 'tagName' in kwds:
250 auth=self.
__auth).raise_for_status()
252 elif 'propertyName' in kwds:
254 data=
PropertyEncoder().encode(Property(kwds[
'propertyName'].strip(), attributes={})),
257 auth=self.
__auth).raise_for_status()
259 elif 'logEntryId' in kwds:
263 auth=self.
__auth).raise_for_status()
266 raise Exception,
' unkown key, use logEntryId, logbookName, tagName or propertyName'
270 def default(self, obj):
271 if isinstance(obj, Property):
273 for key
in obj.getAttributes():
274 test[str(key)] = str(obj.getAttributeValue(key))
276 prop[
"name"] = obj.getName()
277 prop[
"attributes"] = test
279 return json.JSONEncoder.default(self, obj)
286 def dictToProperty(self, d):
288 return Property(name=d.pop(
'name'), attributes=d.pop(
'attributes'))
292 def default(self, obj):
293 if isinstance(obj, Logbook):
294 return {
"name":obj.getName(),
"owner":obj.getOwner()}
295 return json.JSONEncoder.default(self, obj)
300 json.JSONDecoder.__init__(self, object_hook=self.
dictToLogbook)
302 def dictToLogbook(self, d):
304 return Logbook(name=d.pop(
'name'), owner=d.pop(
'owner'))
310 def default(self, obj):
311 if isinstance(obj, Tag):
312 return {
"state": obj.getState(),
"name": obj.getName()}
313 return json.JSONEncoder.default(self, obj)
318 json.JSONDecoder.__init__(self, object_hook=self.
dictToTag)
320 def dictToTag(self, d):
322 return Tag(name=d.pop(
'name'), state=d.pop(
'state'))
328 def default(self, obj):
329 if isinstance(obj, LogEntry):
331 for logbook
in obj.getLogbooks():
334 for tag
in obj.getTags():
337 for property
in obj.getProperties():
339 return [{
"description":obj.getText(),
340 "owner":obj.getOwner(),
344 "properties":properties}]
345 return json.JSONEncoder.default(self, obj)
352 def dictToLogEntry(self, d):
354 return LogEntry(text=d.pop(
'description'),
355 owner=d.pop(
'owner'),
356 logbooks=[
LogbookDecoder().dictToLogbook(logbook)
for logbook
in d.pop(
'logbooks')],
357 tags=[
TagDecoder().dictToTag(tag)
for tag
in d.pop(
'tags')],
358 properties=[
PropertyDecoder().dictToProperty(property)
for property
in d.pop(
'properties')],
360 createTime=d.pop(
'createdDate'),
361 modifyTime=d.pop(
'modifiedDate'))