65 lines
3.0 KiB
Python
65 lines
3.0 KiB
Python
"""Sends one request to a REST API that speaks JSON, with a credential that no redirect may carry elsewhere."""
|
|
import dataclasses
|
|
import http.client
|
|
import json
|
|
import typing
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
from failure import Failure
|
|
|
|
# The API's own message in the JSON of an error answer; empty where it holds none.
|
|
MessageOf = typing.Callable[[object], str]
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class ErrorAnswer(Failure):
|
|
"""The API answered an HTTP error, whose code is status, such as 409 for a conflict."""
|
|
status: int
|
|
|
|
|
|
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
"""Refuses every redirect, which a REST API doesn't send: urllib would resend the credential to the new location, even one off https."""
|
|
|
|
def redirect_request(self, *args: typing.Any, **kwargs: typing.Any) -> None:
|
|
return None
|
|
|
|
|
|
# Sends a request: method, url, token and the body as JSON where there is one. It returns the JSON answer, None where the answer has no body, or a Failure saying why there is none.
|
|
Http = typing.Callable[[str, str, str, object], object]
|
|
|
|
OPENER = urllib.request.build_opener(NoRedirect)
|
|
|
|
|
|
def http_json(method: str, url: str, authorization: str, body: object, seconds: int, message_of: MessageOf) -> object:
|
|
"""The JSON that url answers to a request with the Authorization header given, and body as JSON where there is one; None where it answers a success without a body, as Jira does to a new issue link. A Failure names the server where it cannot be reached, and the request where it answers an error, breaks HTTP or answers something other than JSON. Each connect and each read may wait that many seconds."""
|
|
request_name = f"{method} {urllib.parse.urlsplit(url).path}"
|
|
data = None if body is None else json.dumps(body).encode()
|
|
request = urllib.request.Request(url, data, {"Authorization": authorization, "Content-Type": "application/json", "Accept": "application/json"}, method=method)
|
|
try:
|
|
with OPENER.open(request, timeout=seconds) as response:
|
|
raw = response.read()
|
|
except urllib.error.HTTPError as failure:
|
|
with failure:
|
|
return ErrorAnswer(f"{request_name} answered {failure.code}: {error_message(failure, message_of) or failure.reason}", failure.code)
|
|
except http.client.HTTPException as failure:
|
|
return Failure(f"{request_name} got a broken answer: {failure!r}")
|
|
except (OSError, ValueError) as failure:
|
|
server = urllib.parse.urlunsplit(urllib.parse.urlsplit(url)[:2] + ("", "", ""))
|
|
return Failure(f"cannot reach {server}: {getattr(failure, 'reason', failure)}")
|
|
if not raw.strip():
|
|
return None
|
|
try:
|
|
return json.loads(raw)
|
|
except ValueError:
|
|
return Failure(f"{request_name} answered with something other than JSON")
|
|
|
|
|
|
def error_message(failure: urllib.error.HTTPError, message_of: MessageOf) -> str:
|
|
"""The API's message in an error answer; empty where the body is cut short, breaks HTTP or holds none."""
|
|
try:
|
|
return message_of(json.loads(failure.read()))
|
|
except (http.client.HTTPException, OSError, ValueError):
|
|
return ""
|