diff --git a/main.py b/main.py index 55f47d0b58101b2c10e335fa5399b9a71cf882f5..fd59606c150507ae5b36fa65da0434d86d6a7c7b 100644 --- a/main.py +++ b/main.py @@ -15,7 +15,7 @@ class RestApp(App): def load_locations(self): self.root.ids.results.clear_widgets() - self.openmrs_connection.send_request('location', {}, None, self.on_locations_loaded, + self.openmrs_connection.send_request('location', None, None, self.on_locations_loaded, self.on_locations_not_loaded, self.on_locations_not_loaded) def on_locations_loaded(self, _, response): diff --git a/openmrs.py b/openmrs.py index 6723c66eaa8c3a324c0bf91ee0d81ac34b30629c..6cc768aed47945f16090b20b96ffcc7c0a146fb8 100644 --- a/openmrs.py +++ b/openmrs.py @@ -8,26 +8,27 @@ except ImportError: from urllib.parse import quote -class RESTConnection(object): - @staticmethod - def _construct_url(authority, port, resource): - return 'http://{authority}:{port}/openmrs/ws/rest/v1/{resource}' \ - .format(authority=authority, port=port, resource=resource) - +class RESTConnection: def __init__(self, authority, port, username, password): self.authority = authority self.port = port - credentials = '{username}:{password}'.format(username=username, password=password) + credentials = f'{username}:{password}' credentials = base64.standard_b64encode(credentials.encode('UTF8')).decode('UTF8') self.headers = { - 'Authorization': 'Basic {credentials}'.format(credentials=credentials), + 'Authorization': f'Basic {credentials}', 'Content-type': 'application/json', } + def construct_url(self, resource, get_parameters=None): + get_parameters = '&'.join(f'{quote(str(key))}={quote(str(value))}' for key, value in get_parameters.items()) \ + if get_parameters is not None else '' + return f'http://{self.authority}:{self.port}/openmrs/ws/rest/v1/{resource}?{get_parameters}' + + def send_request_by_url(self, url, post_parameters, on_success, on_failure, on_error): + UrlRequest(url, req_headers=self.headers, + req_body=json.dumps(post_parameters) if post_parameters is not None else None, + on_success=on_success, on_failure=on_failure, on_error=on_error) + def send_request(self, resource, get_parameters, post_parameters, on_success, on_failure, on_error): - url = RESTConnection._construct_url(self.authority, self.port, resource) - get_parameters = '&'.join('{key}={value}'.format(key=quote(key), value=quote(value)) - for key, value in get_parameters.items()) if get_parameters is not None else '' - post_parameters = json.dumps(post_parameters) if post_parameters is not None else None - UrlRequest('{url}?{get_parameters}'.format(url=url, get_parameters=get_parameters), req_headers=self.headers, - req_body=post_parameters, on_success=on_success, on_failure=on_failure, on_error=on_error) + url = self.construct_url(resource, get_parameters) + self.send_request_by_url(url, post_parameters, on_success, on_failure, on_error)