GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 3d6413...7ed725 )
by Daniel
01:08
created

DatabaseConnection.close()   A

Complexity

Conditions 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 1
c 3
b 0
f 0
dl 0
loc 3
rs 10
1
from __future__ import absolute_import
2
3
# python 3 vs 2
4
try:
5
    from urlparse import urljoin
6
except:
7
    from urllib.parse import urljoin
8
9
from requests import Session
10
from requests.auth import HTTPBasicAuth
11
12
import json
13
14
from ._websocket import WebsocketHandler
15
16
# The subpath to the Create Read Update Delete portion of the API
17
CRUD_PATH = "crud/"
18
19
20
# Returned when the given credentials are not accepted by the server
21
class AuthenticationError(Exception):
22
    def __init__(self, value):
23
        self.value = value
24
25
    def __str__(self):
26
        return repr(self.value)
27
28
29
# Returned when the server gives an unhandled error code
30
class ServerError(Exception):
31
    def __init__(self, value):
32
        self.value = value
33
34
    def __str__(self):
35
        return repr(self.value)
36
37
38
class DatabaseConnection(object):
39
    def __init__(self, user_or_apikey=None, user_password=None, url="https://connectordb.com"):
40
41
        # Set up the API URL
42
        if not url.startswith("http"):
43
            url = "https://" + url
44
        if not url.endswith("/"):
45
            url = url + "/"
46
        self.url = urljoin(url, "/api/v1/")
47
48
        # Set up a session, which allows us to reuse connections
49
        self.r = Session()
50
        self.r.headers.update({'content-type': 'application/json'})
51
52
        # Prepare the websocket
53
        self.ws = WebsocketHandler(self.url,None)
54
55
        # Set the authentication if any
56
        self.setauth(user_or_apikey,user_password)
57
58
    def setauth(self,user_or_apikey=None, user_password=None):
59
        """ setauth sets the authentication header for use in the session.
60
        It is for use when apikey is updated or something of the sort, such that
61
        there is a seamless experience. """
62
        auth = None
63
        if user_or_apikey is not None:
64
            # ConnectorDB allows login using both basic auth or an apikey url param.
65
            # The python client uses basic auth for all logins
66
            if user_password is None:
67
                # Login by api key - the basic auth login uses "" user and apikey as password
68
                user_password = user_or_apikey
69
                user_or_apikey = ""
70
            auth = HTTPBasicAuth(user_or_apikey, user_password)
71
            self.r.auth = auth
72
73
        # Set the websocket's authentication
74
        self.ws.setauth(auth)
75
76
    def close(self):
77
        """Closes the active connections to ConnectorDB"""
78
        self.r.close()
79
80
    def handleresult(self, r):
81
        """Handles HTTP error codes for the given request
82
83
        Raises:
84
            AuthenticationError on the appropriate 4** errors
85
            ServerError if the response is not an ok (2**)
86
87
        Arguments:
88
            r -- The request result
89
        """
90
        if r.status_code >= 400 and r.status_code < 500:
91
            msg = r.json()
92
            raise AuthenticationError(str(msg["code"]) + ": " + msg["msg"] +
93
                                      " (" + msg["ref"] + ")")
94
        elif r.status_code > 300:
95
            err = None
96
            try:
97
                msg = r.json()
98
                err = ServerError(str(msg["code"]) + ": " + msg["msg"] + " (" +
99
                                  msg["ref"] + ")")
100
            except:
101
                raise ServerError(
102
                    "Server returned error, but did not give a valid error message")
103
            raise err
104
        return r
105
106
    def ping(self):
107
        """Attempts to ping the server using current credentials, and responds with the path of the currently
108
        authenticated device"""
109
        return self.handleresult(self.r.get(self.url,
110
                                            params={"q": "this"})).text
111
112
    def query(self, query_type, query=None):
113
        """Run the given query on the connection (POST request to /query)"""
114
        return self.handleresult(self.r.post(urljoin(self.url + "query/",
115
                                                     query_type),
116
                                             data=json.dumps(query))).json()
117
118
    def create(self, path, data=None):
119
        """Send a POST CRUD API request to the given path using the given data which will be converted
120
        to json"""
121
        return self.handleresult(self.r.post(urljoin(self.url + CRUD_PATH,
122
                                                     path),
123
                                             data=json.dumps(data)))
124
125
    def read(self, path, params=None):
126
        """Read the result at the given path (GET) from the CRUD API, using the optional params dictionary
127
        as url parameters."""
128
        return self.handleresult(self.r.get(urljoin(self.url + CRUD_PATH,
129
                                                    path),
130
                                            params=params))
131
132
    def update(self, path, data=None):
133
        """Send an update request to the given path of the CRUD API, with the given data dict, which will be converted
134
        into json"""
135
        return self.handleresult(self.r.put(urljoin(self.url + CRUD_PATH,
136
                                                    path),
137
                                            data=json.dumps(data)))
138
139
    def delete(self, path):
140
        """Send a delete request to the given path of the CRUD API. This deletes the object. Or at least tries to."""
141
        return self.handleresult(self.r.delete(urljoin(self.url + CRUD_PATH,
142
                                                       path)))
143
144
    def get(self, path, params=None):
145
        """Sends a get request to the given path in the database and with optional URL parameters"""
146
        return self.handleresult(self.r.get(urljoin(self.url, path),
147
                                            params=params))
148
149
    def subscribe(self, stream, callback, transform=""):
150
        """Subscribe to the given stream with the callback"""
151
        return self.ws.subscribe(stream, callback, transform)
152
153
    def unsubscribe(self, stream, transform=""):
154
        """Unsubscribe from the given stream"""
155
        return self.ws.unsubscribe(stream, transform)
156
157
    def wsdisconnect(self):
158
        """Disconnects the websocket"""
159
        self.ws.disconnect()
160