1"""Plain HTTP to a Psyclone service's HTTP interface (request/reply or ingestion), stdlib only."""
8 def __init__(self, status, content_type, body):
15 return self.
body.decode(
"utf-8",
"replace")
19 return json.loads(self.
body)
26 """Each request becomes one message posted as ``post`` (the ``PsyPost`` query parameter): query
27 parameters and form fields become string entries, a JSON/XML/text body a string entry. The reply is
28 what the responder put in ``JSON``/``XML``/``HTML``/``TEXT``/``BINARY`` (``ResultCode`` = status), or the
29 whole reply message as JSON.
33 http = PsycloneHttp("http://host:8082")
34 r = http.request("/ask", "Question", {"Text": "hello"})
35 print(r.status, r.text)
38 def __init__(self, base_url, timeout=10.0, headers=None, ssl_context=None):
39 self.
base = base_url.rstrip(
"/")
44 def _url(self, path, post, query=None):
49 p = path
if path.startswith(
"/")
else "/" + path
51 p += (
"&" if "?" in p
else "?") + urllib.parse.urlencode(q)
54 def _send(self, method, url, body=None, content_type=None):
55 req = urllib.request.Request(url, data=body, method=method, headers=dict(self.
headers))
57 req.add_header(
"Content-Type", content_type)
60 return Reply(r.status, r.headers.get(
"Content-Type"), r.read())
61 except urllib.error.HTTPError
as e:
62 return Reply(e.code, e.headers.get(
"Content-Type"), e.read()
or b
"")
64 def request(self, path, post=None, fields=None):
65 """POST ``fields`` as a form to ``path``, posted into the system as ``post``."""
66 body = urllib.parse.urlencode(fields
or {}).encode(
"utf-8")
67 return self.
_send(
"POST", self.
_url(path, post), body,
"application/x-www-form-urlencoded")
69 def request_body(self, path, post, body, content_type="application/json"):
70 """POST a JSON (or other text) body; the service passes it on as a string entry."""
71 if isinstance(body, str):
72 body = body.encode(
"utf-8")
73 return self.
_send(
"POST", self.
_url(path, post), body, content_type)
75 def get(self, path, post=None, query=None):
76 """GET ``path`` with ``query`` parameters (each becomes an entry)."""
77 return self.
_send(
"GET", self.
_url(path, post, query))
_url(self, path, post, query=None)
_send(self, method, url, body=None, content_type=None)
request(self, path, post=None, fields=None)
request_body(self, path, post, body, content_type="application/json")
__init__(self, base_url, timeout=10.0, headers=None, ssl_context=None)
get(self, path, post=None, query=None)
__init__(self, status, content_type, body)