vlbi.py 6.73 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# An example client for the Radboud Radio Lab VLBI Monitor
# 
# Copyright (c) 2016 Pim Schellart
# 
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.

"""This module provides client side tools to interface with the VLBI monitor.
"""

import requests
import json
import datetime
import os

class ServerError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

class Client(object):
    headers = {'content-type': 'application/json'}

    def __init__(self, server, facility, username, password, backup=True, backupDir="./backup"):
        self.server = server
        self.facility = facility
        self.username = username
        self.password = password
        self.backup = backup
        self.backupDir = backupDir

    def post(self, request):
        if self.backup:
            filename = "{0}-{1}-{2}-{3}.json".format(request["method"], self.facility, self.username, datetime.datetime.utcnow().isoformat())
            with open(os.path.join(self.backupDir, filename), "w") as f:
                json.dump(request, f)

        response = requests.post(self.server, data=json.dumps(request), headers=self.headers).json()
    
        if "error" in response:
            raise ServerError(str(response["error"]["message"]))

        if "results" in response:
            return response["results"]

    @property
    def auth(self):
        return {"facility": self.facility, "username": self.username, "password": self.password}

51
52
53
54
55
56
57
    """List all valid methods.
    """
    def listMethods(self):
        request = {"jsonrpc": "2.0", "auth": self.auth, "method": "listMethods", "id": 0}
    
        return self.post(request)

58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
    """Send new data record to server. At the server this new data record is merged with current record and stored.
    """
    def updateRecord(self, record):
        request = {"jsonrpc": "2.0", "auth": self.auth, "method": "updateRecords", "params": {"records": [record]}, "id": 0}
    
        self.post(request)
    
    """Get the current record for the specified list of *observatories* and *fields*.
    """
    def getCurrentRecord(self, observatories=[], fields=[]):
        request = {"jsonrpc": "2.0", "auth": self.auth, "method": "getCurrentRecords", "params": {"observatories": observatories, "fields": fields}, "id": 1}

        return self.post(request)
    
    """Get a single *field* as a function of time between *startTime* and *endTime*.

    If a *startTime* and/or *endTime* is/are provided the search is restricted to this range. Both parameters need to be of the standard library ``datetime.datetime'' type. If either *startTime* or *endTime* is missing the range will be infinite in the respective direction.

    The output will be a time ordered list of field dictionaries containing ``time'' and ``value'' attributes.
    """
    def getSingleFieldTimeseries(self, observatory, field, startTime, endTime):
        if startTime and endTime:
            request = {"jsonrpc": "2.0", "auth": self.auth, "method": "getSingleFieldTimeseries", "params": {"observatories": [observatory], "fields": [field], "startTime": startTime.isoformat('T') + 'Z', "endTime": endTime.isoformat('T') + 'Z'}, "id": 0}
        elif startTime:
            request = {"jsonrpc": "2.0", "auth": self.auth, "method": "getSingleFieldTimeseries", "params": {"observatories": [observatory], "fields": [field], "startTime": startTime.isoformat('T') + 'Z'}, "id": 0}
        elif endTime:
            request = {"jsonrpc": "2.0", "auth": self.auth, "method": "getSingleFieldTimeseries", "params": {"observatories": [observatory], "fields": [field], "endTime": endTime.isoformat('T') + 'Z'}, "id": 0}
        else:
            request = {"jsonrpc": "2.0", "auth": self.auth, "method": "getSingleFieldTimeseries", "params": {"observatories": [observatory], "fields": [field]}, "id": 0}
    
        return self.post(request)

    """Send a string *message*.
    """
    def addMessage(self, message):
        request = {"jsonrpc": "2.0", "auth": self.auth, "method": "addMessages", "params": {"messages": [message]}, "id": 0}
    
        self.post(request)

    """Send a log *message* string.
    """
    def addLog(self, message):
        request = {"jsonrpc": "2.0", "auth": self.auth, "method": "addLogs", "params": {"messages": [message]}, "id": 0}
    
        self.post(request)
    
    """Get a list of message strings from the server.

    If a *startTime* and/or *endTime* is/are provided the search is restricted to this range. Both parameters need to be of the standard library ``datetime.datetime'' type. If either *startTime* or *endTime* is missing the range will be infinite in the respective direction.
    """
    def getMessages(self, startTime, endTime):
        if startTime and endTime:
            request = {"jsonrpc": "2.0", "auth": self.auth, "method": "getMessages", "params": {"startTime": startTime.isoformat('T') + 'Z', "endTime": endTime.isoformat('T') + 'Z'}, "id": 0}
        elif startTime:
            request = {"jsonrpc": "2.0", "auth": self.auth, "method": "getMessages", "params": {"startTime": startTime.isoformat('T') + 'Z'}, "id": 0}
        elif endTime:
            request = {"jsonrpc": "2.0", "auth": self.auth, "method": "getMessages", "params": {"endTime": endTime.isoformat('T') + 'Z'}, "id": 0}
        else:
            request = {"jsonrpc": "2.0", "auth": self.auth, "method": "getMessages", "id": 0}
    
        return self.post(request)
    
120
    """Change user password.
121
    """
122
123
124
    def changePassword(self, username, password):
        user = {"username" : username, "password": password}
        request = {"jsonrpc": "2.0", "auth": self.auth, "method": "changePassword", "params": {"user": user}, "id": 0}
125
126
127
    
        self.post(request)

128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
    """Add user.

    Note that only admins can do this.
    """
    def addUser(self, username, password, name=None, email=None, permissions=None):
        user = {"username": username, "password": password,
                "name": name, "email": email, "permissions": permissions}

        request = {"jsonrpc": "2.0", "auth": self.auth, "method": "addUser", "params": {"user": user}, "id": 0}

        self.post(request)

    """Remove user.

    Note that only admins can do this.
143
144
145
    """
    def removeUser(self, username):
        user = {"username" : username}
146
        request = {"jsonrpc": "2.0", "auth": self.auth, "method": "removeUser", "params": {"user": user}, "id": 0}
147
148
149
    
        self.post(request)

150
151
152
    """Get user info.

    Note that only admins can do this.
153
154
155
    """
    def getUser(self, username):
        user = {"username" : username}
156
        request = {"jsonrpc": "2.0", "auth": self.auth, "method": "getUser", "params": {"user": user}, "id": 0}
157
158
159
    
        return self.post(request)