1
|
1 |
|
import logging |
2
|
1 |
|
import platform |
3
|
1 |
|
import sys |
4
|
1 |
|
from .query_object import QueryObject as _QueryObject |
5
|
|
|
|
6
|
|
|
|
7
|
1 |
|
logger = logging.getLogger(__name__) |
8
|
|
|
|
9
|
|
|
|
10
|
1 |
|
class CustomQueryObject(_QueryObject): |
11
|
1 |
|
def __init__(self, query, description=""): |
12
|
|
|
"""Create a new CustomQueryObject. |
13
|
|
|
|
14
|
|
|
Parameters |
15
|
|
|
----------- |
16
|
|
|
|
17
|
|
|
query : function |
18
|
|
|
Function that defines a custom query method. The query can have any |
19
|
|
|
signature, but input and output of the query needs to be JSON |
20
|
|
|
serializable. |
21
|
|
|
|
22
|
|
|
description : str |
23
|
|
|
The description of the custom query object |
24
|
|
|
|
25
|
|
|
""" |
26
|
1 |
|
super().__init__(description) |
27
|
|
|
|
28
|
1 |
|
self.custom_query = query |
29
|
|
|
|
30
|
1 |
|
def query(self, *args, **kwargs): |
31
|
|
|
"""Query the custom defined query method using the given input. |
32
|
|
|
|
33
|
|
|
Parameters |
34
|
|
|
---------- |
35
|
|
|
args : list |
36
|
|
|
positional arguments to the query |
37
|
|
|
|
38
|
|
|
kwargs : dict |
39
|
|
|
keyword arguments to the query |
40
|
|
|
|
41
|
|
|
Returns |
42
|
|
|
------- |
43
|
|
|
out: object. |
44
|
|
|
The results depends on the implementation of the query method. |
45
|
|
|
Typically the return value will be whatever that function returns. |
46
|
|
|
|
47
|
|
|
See Also |
48
|
|
|
-------- |
49
|
|
|
QueryObject |
50
|
|
|
""" |
51
|
|
|
# include the dependent files in sys path so that the query can run |
52
|
|
|
# correctly |
53
|
|
|
|
54
|
|
|
try: |
55
|
|
|
logger.debug( |
56
|
|
|
"Running custom query with arguments " f"({args}, {kwargs})..." |
57
|
|
|
) |
58
|
|
|
ret = self.custom_query(*args, **kwargs) |
59
|
|
|
except Exception as e: |
60
|
|
|
logger.exception( |
61
|
|
|
"Exception hit when running custom query, error: " f"{str(e)}" |
62
|
|
|
) |
63
|
|
|
raise |
64
|
|
|
|
65
|
|
|
logger.debug(f"Received response {ret}") |
66
|
|
|
try: |
67
|
|
|
return self._make_serializable(ret) |
68
|
|
|
except Exception as e: |
69
|
|
|
logger.exception( |
70
|
|
|
"Cannot properly serialize custom query result, " f"error: {str(e)}" |
71
|
|
|
) |
72
|
|
|
raise |
73
|
|
|
|
74
|
1 |
|
def get_docstring(self): |
75
|
|
|
"""Get doc string from customized query""" |
76
|
1 |
|
default_docstring = "-- no docstring found in query function --" |
77
|
|
|
|
78
|
|
|
# TODO: fix docstring parsing on Windows systems |
79
|
1 |
|
if sys.platform == 'win32': |
80
|
|
|
return default_docstring |
81
|
|
|
|
82
|
1 |
|
ds = getattr(self.custom_query, '__doc__', None) |
83
|
1 |
|
return ds if ds and isinstance(ds, str) else default_docstring |
84
|
|
|
|
85
|
1 |
|
def get_methods(self): |
86
|
1 |
|
return [self.get_query_method()] |
87
|
|
|
|
88
|
1 |
|
def get_query_method(self): |
89
|
|
|
return {"method": "query"} |
90
|
|
|
|