encode / apistar

The Web API toolkit. 🛠
https://docs.apistar.com
BSD 3-Clause "New" or "Revised" License
5.57k stars 411 forks source link

Added Data Classes (Python 3.7+) support for serialization #607

Closed frol closed 6 years ago

frol commented 6 years ago

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
tomchristie commented 6 years ago

Closing this off given that 0.6 is moving to a framework-agnostic suite of API tools, and will no longer include the server. See https://discuss.apistar.org/t/api-star-as-a-framework-independant-tool/614 and #624.