question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Specifying a default, non-JSON-serializable value causes Swagger page to crash

See original GitHub issue

I am using flask-restx==0.2.0 with flask_accepts==0.16.4

Specifying default as a non serializable value like datetime in Marshmallow causes the Swagger page to fail to load. Here is my code:

Marshmallow class

class RespondSchema(Schema):
    data = fields.String(required=True)
    timestamp = fields.DateTime(default=datetime.utcnow)

Route

@api.route("/route")
class SomeRoute(Resource):
    @api.doc("some_route")
    @accepts(schema=AcceptSchema, api=api)
    @responds(schema=RespondSchema, api=api)
    def post(self):
        return SomeService.do_stuff(request.parsed_obj)

Traceback

Traceback (most recent call last):
  File "/Users/andrew.mickael/PycharmProjects/Financial-Ingestion-Service/venv/lib/python3.7/site-packages/flask/app.py", line 2464, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/andrew.mickael/PycharmProjects/Financial-Ingestion-Service/venv/lib/python3.7/site-packages/werkzeug/middleware/proxy_fix.py", line 169, in __call__
    return self.app(environ, start_response)
  File "/Users/andrew.mickael/PycharmProjects/Financial-Ingestion-Service/venv/lib/python3.7/site-packages/flask/app.py", line 2450, in wsgi_app
    response = self.handle_exception(e)
  File "/Users/andrew.mickael/PycharmProjects/Financial-Ingestion-Service/venv/lib/python3.7/site-packages/flask_restx/api.py", line 638, in error_router
    return original_handler(f)
  File "/Users/andrew.mickael/PycharmProjects/Financial-Ingestion-Service/venv/lib/python3.7/site-packages/flask_cors/extension.py", line 161, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "/Users/andrew.mickael/PycharmProjects/Financial-Ingestion-Service/venv/lib/python3.7/site-packages/flask/app.py", line 1867, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/andrew.mickael/PycharmProjects/Financial-Ingestion-Service/venv/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/Users/andrew.mickael/PycharmProjects/Financial-Ingestion-Service/venv/lib/python3.7/site-packages/flask_restx/api.py", line 636, in error_router
    return self.handle_error(e)
  File "/Users/andrew.mickael/PycharmProjects/Financial-Ingestion-Service/venv/lib/python3.7/site-packages/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/andrew.mickael/PycharmProjects/Financial-Ingestion-Service/venv/lib/python3.7/site-packages/flask/app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/andrew.mickael/PycharmProjects/Financial-Ingestion-Service/venv/lib/python3.7/site-packages/flask_restx/api.py", line 638, in error_router
    return original_handler(f)
  File "/Users/andrew.mickael/PycharmProjects/Financial-Ingestion-Service/venv/lib/python3.7/site-packages/flask_cors/extension.py", line 161, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "/Users/andrew.mickael/PycharmProjects/Financial-Ingestion-Service/venv/lib/python3.7/site-packages/flask/app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/andrew.mickael/PycharmProjects/Financial-Ingestion-Service/venv/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/Users/andrew.mickael/PycharmProjects/Financial-Ingestion-Service/venv/lib/python3.7/site-packages/flask_restx/api.py", line 636, in error_router
    return self.handle_error(e)
  File "/Users/andrew.mickael/PycharmProjects/Financial-Ingestion-Service/venv/lib/python3.7/site-packages/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/andrew.mickael/PycharmProjects/Financial-Ingestion-Service/venv/lib/python3.7/site-packages/flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/andrew.mickael/PycharmProjects/Financial-Ingestion-Service/venv/lib/python3.7/site-packages/flask_restx/api.py", line 379, in wrapper
    return self.make_response(data, code, headers=headers)
  File "/Users/andrew.mickael/PycharmProjects/Financial-Ingestion-Service/venv/lib/python3.7/site-packages/flask_restx/api.py", line 402, in make_response
    resp = self.representations[mediatype](data, *args, **kwargs)
  File "/Users/andrew.mickael/PycharmProjects/Financial-Ingestion-Service/venv/lib/python3.7/site-packages/flask_restx/representations.py", line 25, in output_json
    dumped = dumps(data, **settings) + "\n"
  File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 201, in encode
    chunks = list(chunks)
  File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 431, in _iterencode
    yield from _iterencode_dict(o, _current_indent_level)
  File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 405, in _iterencode_dict
    yield from chunks
  File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 405, in _iterencode_dict
    yield from chunks
  File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 405, in _iterencode_dict
    yield from chunks
  File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 405, in _iterencode_dict
    yield from chunks
  File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 405, in _iterencode_dict
    yield from chunks
  File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 438, in _iterencode
    o = _default(o)
  File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type builtin_function_or_method is not JSON serializable

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:12 (6 by maintainers)

github_iconTop GitHub Comments

4reactions
SteadBytescommented, Apr 21, 2020

@amickael @apryor6 sorry for the slow response. The flask-restx Flask app setting RESTX_JSON can be used to configure additional parameters for JSON serialisation. Take a look at his and let me know if it works for you 😄

from datetime import datetime
from json import JSONEncoder

from flask import Flask
from flask_accepts import accepts, responds
from flask_restx import Api, Resource
from marshmallow import Schema, fields


class CustomJSONEncoder(JSONEncoder):
    """Custom encoder for handling default values from a function call"""

    def default(self, o):
        if callable(o):
            return str(o())
        return super().default(o)


app = Flask(__name__)
# Realistically this would be set in a config file
app.config.update(RESTX_JSON={"cls": CustomJSONEncoder})

api = Api(app)

@api.route("/route")
class SomeRoute(Resource):
    @api.doc("some_route")
    @accepts(schema=AcceptSchema, api=api)
    @responds(schema=RespondSchema, api=api)
    def post(self):
        return SomeService.do_stuff(request.parsed_obj)

This setting seems to be completely undocumented so I apologise for that - I’ll get it added to the documentation ASAP 👍

1reaction
amickaelcommented, Apr 8, 2020

Thank you for your help @ribeirojose. This is not urgent at all, I can work around it for now.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Swagger UI freezes after API fetch and browser crashes
I was able to comment out each of my API controllers, load the swagger page, and then turn them back on until the...
Read more >
Fixing JSON Self Referencing Loop Exceptions
When building applications that use JSON, you'll often have to deal with looping. Here's the real solution to fixing JSON self-referencing ...
Read more >
Troubleshoot ASP.NET Core on Azure App Service and IIS
Learn how to diagnose problems with Azure App Service and Internet Information Services (IIS) deployments of ASP.NET Core apps.
Read more >
API Documentation — Girder 3.1.15 documentation
In this way, the Swagger page is just the simplest and lightest client application for Girder. This page is served out of the...
Read more >
Fix list for IBM App Connect Enterprise Version 11.0
IT41042, PUBLICATION NODE NOT FINDING DEFAULT QM DETAILS ... DISABLE SCIENTIFIC NOTATION WHEN SERIALIZING A DOUBLE VALUE IN THE JSON PARSER.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found