CMSDK 2.0.1
Cross-platform C++ base library and SDK for the Psyclone AIOS platform
Loading...
Searching...
No Matches
http.py
Go to the documentation of this file.
1"""Plain HTTP to a Psyclone service's HTTP interface (request/reply or ingestion), stdlib only."""
2import urllib.error
3import urllib.parse
4import urllib.request
5
6
7class Reply:
8 def __init__(self, status, content_type, body):
9 self.status = status
10 self.content_type = content_type
11 self.body = body
12
13 @property
14 def text(self):
15 return self.body.decode("utf-8", "replace")
16
17 def json(self):
18 import json
19 return json.loads(self.body)
20
21 def __repr__(self):
22 return "Reply(%d, %r, %d bytes)" % (self.status, self.content_type, len(self.body))
23
24
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.
30
31 ::
32
33 http = PsycloneHttp("http://host:8082")
34 r = http.request("/ask", "Question", {"Text": "hello"})
35 print(r.status, r.text)
36 """
37
38 def __init__(self, base_url, timeout=10.0, headers=None, ssl_context=None):
39 self.base = base_url.rstrip("/")
40 self.timeout = timeout
41 self.headers = dict(headers or {})
42 self.ssl_context = ssl_context
43
44 def _url(self, path, post, query=None):
45 q = {}
46 if post is not None:
47 q["PsyPost"] = post
48 q.update(query or {})
49 p = path if path.startswith("/") else "/" + path
50 if q:
51 p += ("&" if "?" in p else "?") + urllib.parse.urlencode(q)
52 return self.base + p
53
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))
56 if content_type:
57 req.add_header("Content-Type", content_type)
58 try:
59 with urllib.request.urlopen(req, timeout=self.timeout, context=self.ssl_context) as r:
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"")
63
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")
68
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)
74
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)
Definition http.py:44
_send(self, method, url, body=None, content_type=None)
Definition http.py:54
request(self, path, post=None, fields=None)
Definition http.py:64
request_body(self, path, post, body, content_type="application/json")
Definition http.py:69
__init__(self, base_url, timeout=10.0, headers=None, ssl_context=None)
Definition http.py:38
get(self, path, post=None, query=None)
Definition http.py:75
__init__(self, status, content_type, body)
Definition http.py:8