This commit adds support for Python 3.7 feature called Data Classes. With this change, you can return an object (an instance of a Data Class) and apistar will automatically serialize it to JSON.
import dataclasses
@dataclasses.dataclass
class Item:
title: str
count: int = 0
def handler():
return Item(title="qq")
Without this change you would get an exception:
Traceback (most recent call last):
File ".../env/lib/python3.7/site-packages/apistar/server/app.py", line 243, in __call__
return self.injector.run(funcs, state)
File ".../env/lib/python3.7/site-packages/apistar/server/injector.py", line 106, in run
state[output_name] = func(**func_kwargs)
File ".../env/lib/python3.7/site-packages/apistar/server/app.py", line 187, in finalize_wsgi
raise exc_info[0].with_traceback(exc_info[1], exc_info[2])
File ".../env/lib/python3.7/site-packages/apistar/server/app.py", line 236, in __call__
return self.injector.run(funcs, state)
File ".../env/lib/python3.7/site-packages/apistar/server/injector.py", line 106, in run
state[output_name] = func(**func_kwargs)
File ".../env/lib/python3.7/site-packages/apistar/server/app.py", line 227, in __call__
return self.injector.run(funcs, state)
File ".../env/lib/python3.7/site-packages/apistar/server/injector.py", line 106, in run
state[output_name] = func(**func_kwargs)
File ".../env/lib/python3.7/site-packages/apistar/server/app.py", line 174, in render_response
return JSONResponse(return_value)
File ".../env/lib/python3.7/site-packages/apistar/http.py", line 193, in __init__
self.content = self.render(content)
File ".../env/lib/python3.7/site-packages/apistar/http.py", line 240, in render
return json.dumps(content, **options).encode('utf-8')
File "/usr/lib/python3.7/json/__init__.py", line 238, in dumps
**kw).encode(obj)
File "/usr/lib/python3.7/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python3.7/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File ".../env/lib/python3.7/site-packages/apistar/http.py", line 245, in default
raise TypeError(error % type(obj).__name__)
TypeError: Object of type 'Item' is not JSON serializable
This commit adds support for Python 3.7 feature called Data Classes. With this change, you can return an object (an instance of a Data Class) and apistar will automatically serialize it to JSON.
Without this change you would get an exception: