singstat¶
Module contents¶
singstat.singstat¶
Client mixin for interacting with all of the API endpoints.
- class singstat.singstat.SingStat(cache_backend: str | BaseCache = 'sqlite', is_test_api: bool = False)¶
Bases:
objectClient mixin for other API Clients.
Normally, it does not need to be created by applications. But applications may use the public methods provided here.
The constructor sets the following:
Connection retries using exponential backoff. (Reference: https://stackoverflow.com/a/35504626.)
Cache (cache duration/expiry is set in
send_request()).User-agent header.
- Parameters:
cache_backend (str | BaseCache) – Cache backend name or instance to use. Refer to https://requests-cache.readthedocs.io/en/stable/user_guide/backends.html for more information and allowed values. Defaults to
"sqlite".is_test_api (bool) – Whether to use SingStat’s test API. If this is set to
True, thenisTestApi=trueis added to the parameters when callingsend_request(). Defaults toFalse.
- build_params(params_expected_type: Any, original_params: Any, default_params: Any | None = None, key_map: dict[str, str] | None = None, remove_none_values: bool = True) dict[str, Any]¶
Build the list of parameters that are compatible for use with the endpoint URLs, e.g. datetime objects to strings.
- Parameters:
params_expected_type (Any) – The expected type of
original_params. Should be one of the importable types fromsingstat.client.types_args.original_params (Any) – The set of parameters to use for building. Should be of the same type as what is specified in
params_expected_type.default_params (dict[str, Any] or None) – The set of parameters’ default values. Should be of the same type as what is specified in
params_expected_type. Defaults to{}, i.e. emptydict.key_map (dict[str, str] or None) – Mapping of keys used in
params_expected_typesto parameters expected by the endpoint. Defaults to{}, i.e. emptydict.remove_none_values (bool) – If True, then parameters with
Nonevalues are removed from the returned parameters. Defaults toTrue.
- Returns:
The set of parameters that can be used with the API endpoints.
- Return type:
- sanitise_data(value: Any, iterate: bool = True, ignore_keys: list[str] | None = None, key_path: str = '') Any¶
Convert the following:
If
iterateisTrueandvalueis adictorlist: sanitise the value’s contents.String with commas: convert to a tuple of numbers if all values are number-like.
String that is like date or datetime: convert to
datetime.dateordatetime.datetimerespectively.String that is number-like: convert to
intorfloatappropriately.Finally: leave the value as-is.
- Parameters:
value (Any) – Value to sanitise.
iterate (bool) – If true, then
listanddictobjects are sanitised recursively. Defaults toTrue.ignore_keys (list[str] or None) – List of dict keys to ignore when sanitising, if value is a
dict. Defaults to[], i.e. emptylist.key_path (str) – Current path of key in the
dict. Defaults to blank string.
- Returns:
The sanitised value.
- Return type:
Any
- send_request(url: str, params: dict[str, Any] | None = None, cache_duration: int = 0, sanitise: bool = True, sanitise_ignore_keys: list[str] | None = None) Any¶
Send a request to an endpoint and return its response.
Normally, this method does not need to be called directly. However, if SingStat were to change their API specification but this package has not yet been updated to support that change, then applications may use this method to call the changed endpoints.
If the client had been instantiated with
is_test_api=True, thenisTestApi=trueis added to the list of parameters to send to the endpoint.- Parameters:
url (Url) – The endpoint URL to send the request to.
params (dict[str, Any] or None) – List of parameters to be passed to the endpoint URL. Parameter names must match the names required by the endpoints, particularly with typecase (e.g. camelCase). Defaults to
{}, i.e. emptydict.cache_duration (int) – Number of seconds before the cache expires. Defaults to
0, i.e. do not cache.sanitise (bool) – If
True, then the response’s values are sanitised using thesanitise_data()method. Defaults toTrue.sanitise_ignore_keys (list[str] or None) – List of keys to ignore in the response value during sanitising when that response value is a
dict. Defaults to[], i.e. emptylist.
- Raises:
APIError – “No data records returned.” when count of data is 0.
APIError – “One or more validation errors occurred.” when HTTP 400 status is returned.
requests.exceptions.HTTPError – Error occurred during the request process.
requests.exceptions.JSONDecodeError – Error occurred when JSON-parsing the response.
- Returns:
Response JSON content of the request.
- Return type:
Any
singstat.timezone¶
Standardise all datetime-related timezones to SGT (Singapore Time).
- singstat.timezone.datetime_from_string(val: str) datetime | date | time¶
Convert a string into a datetime in SGT timezone.
Strings are parsed according to the following formats, in order:
%Y-%m-%dT%H:%M:%S.%f%z
%Y-%m-%dT%H:%M:%S%z
%Y-%m-%dT%H:%M:%S.%f
%Y-%m-%dT%H:%M:%S
%Y%m%dT%H:%M:%S.%f%z
%Y%m%dT%H:%M:%S%z
%Y%m%dT%H:%M:%S.%f
%Y%m%dT%H:%M:%S
%Y-%m-%d %H:%M:%S.%f%z
%Y-%m-%d %H:%M:%S%z
%Y-%m-%d %H:%M:%S.%f
%Y-%m-%d %H:%M:%S
%Y-%m-%d
%Y%m%d
%d/%m/%Y
%H:%M:%S.%f%z
%H:%M:%S%z
%H:%M:%S.%f
%H:%M%z
%H:%M
%H%M
- Parameters:
val (str) – String to convert to a datetime.
- Raises:
ValueError –
valis not a recognised datetime string.- Returns:
The value as a
datetime, ordateif there is no time, ortimeif there is no date.- Return type:
datetime or date or time
singstat.exceptions¶
Exceptions that could occur when interacting with any API endpoint.
- exception singstat.exceptions.APIError(message: str = 'Unexpected error occurred.', data: Any = None, errors: Any = None)¶
Bases:
ExceptionError when the API returns an error.
- Parameters:
message (str) – The general error message to display when the error is raised. Defaults to
"Unexpected error occurred.".data (Any) – Data response obtained by the calling method. Defaults to
None.errors (Any) – Other messages that were part of the raised error. Defaults to
None.
- Return type:
None