Coverage for src/receptiviti/status.py: 89%
38 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-11-11 18:12 -0500
« prev ^ index » next coverage.py v7.6.1, created at 2024-11-11 18:12 -0500
1"""Check the status of the API."""
3import os
4import re
5from typing import Union
7import requests
9from receptiviti.readin_env import readin_env
12def status(
13 url: str = os.getenv("RECEPTIVITI_URL", ""),
14 key: str = os.getenv("RECEPTIVITI_KEY", ""),
15 secret: str = os.getenv("RECEPTIVITI_SECRET", ""),
16 dotenv: Union[bool, str] = False,
17 verbose=True,
18) -> Union[requests.Response, None]:
19 """
20 Check the API's status.
22 Ping the Receptiviti API to see if it's available, and if your credentials are valid.
24 Args:
25 url (str): The URL of the API.
26 key (str): Your API key.
27 secret (str): Your API secret.
28 dotenv (bool | str): Path to a .env file to read environment variables from, or `True`
29 to look for a file in the current directory.
30 verbose (bool): If `False`, will not print status messages.
32 Returns:
33 Response from the API server.
35 Examples:
36 ```
37 receptiviti.status()
38 ```
39 """
40 _, url, key, secret = _resolve_request_def(url, key, secret, dotenv)
41 try:
42 res = requests.get(url.lower() + "/v1/ping", auth=(key, secret), timeout=9999)
43 except requests.exceptions.RequestException:
44 if verbose:
45 print("Status: ERROR\nMessage: URL is unreachable")
46 return None
47 content = res.json() if res.text[:1] == "{" else {"message": res.text}
48 if verbose:
49 print("Status: " + ("OK" if res.status_code == 200 else "ERROR"))
50 print(
51 "Message: "
52 + (
53 str(res.status_code)
54 + (" (" + str(content["code"]) + ")" if "code" in content else "")
55 + ": "
56 + content["pong" if "pong" in content else "message"]
57 )
58 )
59 return res
62def _resolve_request_def(url: str, key: str, secret: str, dotenv: Union[bool, str]):
63 if dotenv:
64 readin_env("." if isinstance(dotenv, bool) else dotenv)
65 if not url:
66 url = os.getenv("RECEPTIVITI_URL", "https://api.receptiviti.com")
67 full_url = url
68 url = ("https://" if re.match("http", url, re.I) is None else "") + re.sub("/+[Vv]\\d+(?:/.*)?$|/+$", "", url)
69 if re.match("https?://[^.]+[.:][^.]", url, re.I) is None:
70 raise TypeError("`url` does not appear to be valid: " + url)
71 if not key:
72 key = os.getenv("RECEPTIVITI_KEY", "")
73 if not key:
74 msg = "specify your key, or set it to the RECEPTIVITI_KEY environment variable"
75 raise RuntimeError(msg)
76 if not secret:
77 secret = os.getenv("RECEPTIVITI_SECRET", "")
78 if not secret:
79 msg = "specify your secret, or set it to the RECEPTIVITI_SECRET environment variable"
80 raise RuntimeError(secret)
81 return (full_url, url, key, secret)