Coverage for /home/runner/work/pycax/pycax/pycax/caxutils.py: 97%
30 statements
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-26 00:27 +0000
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-26 00:27 +0000
1"""
2Utility functions for internal use across various modules.
3"""
4from urllib.parse import urlencode
6import requests
7import pkgutil
8import pycax
10cax_baseurl = "https://api.streamnet.org/api/v1/"
12cax_api_key = "7A2F1EA9-4882-49E8-B23D-7DC202C2ACA5"
14class NoResultException(Exception):
15 """
16 Thrown when query returns no results.
17 """
19 pass
22def build_api_url(url, args):
23 """
24 Builds the API URL based on the base url and the arguments
25 """
26 return url + "?" + urlencode({k: v for k, v in args.items() if v is not None})
28def make_ua():
29 return {
30 "user-agent": "python-requests/"
31 + requests.__version__
32 + ",pycax/"
33 + pycax.__version__
34 }
36def cax_GET(url, args, **kwargs):
37 """
38 Handles technical details of sending GET request to the API
39 """
40 args['XApiKey']=cax_api_key
41 out = requests.get(url, params=args, headers=make_ua(), **kwargs)
42 out.raise_for_status()
43 stopifnot(out.headers["content-type"])
44 return out.json()
47def stopifnot(x, ctype="application/json;charset=utf-8"):
48 if x != ctype:
49 raise NoResultException("content-type did not equal " + str(ctype))
51def stop(x):
52 raise ValueError(x)
54def as_list(x):
55 if type(x) is list:
56 return x
57 else:
58 return [x]
60def get_data(filename):
61 # Read the data file
62 data = pkgutil.get_data('pycax', 'data/' + filename)
64 # Return the data
65 return data