Merge pull request #837 from mwhudson/serialize-to_json

make serialization api a touch easier to use
This commit is contained in:
Michael Hudson-Doyle 2020-09-23 10:47:20 +12:00 committed by GitHub
commit eea6bb0e27
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 18 additions and 11 deletions

View File

@ -14,7 +14,6 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import inspect
import json
import aiohttp
@ -42,9 +41,8 @@ def _wrap(make_request, path, meth, serializer):
if arg_name == payload_arg:
data = serializer.serialize(payload_ann, value)
else:
query_args[arg_name] = json.dumps(
serializer.serialize(
meth_params[arg_name].annotation, value))
query_args[arg_name] = serializer.to_json(
meth_params[arg_name].annotation, value)
async with make_request(
meth.__name__, path, json=data, params=query_args) as resp:
resp.raise_for_status()
@ -77,7 +75,7 @@ def make_client_for_conn(
# session.request needs a full URL with scheme and host
# even though that's in some ways a bit silly with a unix
# socket, so we just hardcode something here (I guess the
# "a" gets sent a long to the server inthe Host: header
# "a" gets sent along to the server in the Host: header
# and the server could in principle do something like
# virtual host based selection but well....)
url = 'http://a' + path

View File

@ -14,7 +14,6 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import inspect
import json
from aiohttp import web
@ -104,13 +103,11 @@ def _make_handler(controller, definition, implementation, serializer):
args = {}
try:
if data_annotation is not None:
payload = json.loads(await request.text())
args[data_arg] = serializer.deserialize(
data_annotation, payload)
args[data_arg] = serializer.from_json(
data_annotation, await request.text())
for arg, ann, default in query_args_anns:
if arg in request.query:
v = serializer.deserialize(
ann, json.loads(request.query[arg]))
v = serializer.from_json(ann, request.query[arg])
elif default != inspect._empty:
v = default
else:

View File

@ -15,6 +15,7 @@
import datetime
import enum
import json
import inspect
import typing
@ -124,3 +125,14 @@ class Serializer:
if isinstance(annotation, type) and issubclass(annotation, enum.Enum):
return getattr(annotation, value)
return self.type_deserializers[annotation](annotation, value, metadata)
def to_json(self, annotation, value):
return json.dumps(self.serialize(annotation, value))
def from_json(self, annotation, value):
return self.deserialize(annotation, json.loads(value))
_serializer = Serializer()
to_json = _serializer.to_json
from_json = _serializer.from_json