Home > OS >  Flask restful throws Object of type MethodViewType is not JSON serializable in simple code
Flask restful throws Object of type MethodViewType is not JSON serializable in simple code

Time:03-31

I just started using Flask and here goes first troubles. I made simple code with flask_restful and I don't understand what is the issue. When I request on /reservations I get Object of type MethodViewType is not JSON serializable. When I request on the second method to get specific reservation I get 'MethodViewType' object is not iterable.

Here goes the code:

from flask import Flask, jsonify, request, render_template
from flask_restful import Resource, Api
import code_generator

app = Flask(__name__)
api = Api(app)

reservations = [
    {
        'first name': 'John',
        'surname': 'Smith',
        'event name': 'Event1',
        'code': 'J0HN'
    },
    {
        'first name': 'Jan',
        'surname': 'Kowalski',
        'event name': 'Event2',
        'code': '0001'
    }
]


class reservations(Resource):
    def get(self):
        return reservations

class reservation(Resource):
    def get(self, code):
        for reservation in reservations:
            if reservation['code'] == code:
                return reservation
        return {'reservation': None}, 404



api.add_resource(reservations, '/reservations')
api.add_resource(reservation, '/reservation/<string:code>')




if __name__ == '__main__':
    app.run(debug= True)

And here goes error message from first get request:

127.0.0.1 - - [31/Mar/2022 12:17:56] "GET /reservations HTTP/1.1" 500 -
Traceback (most recent call last):
  File "C:\Users\APaws\sandbox\venv\venv\Lib\site-packages\flask\app.py", line 2091, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Users\APaws\sandbox\venv\venv\Lib\site-packages\flask\app.py", line 2076, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Users\APaws\sandbox\venv\venv\Lib\site-packages\flask_restful\__init__.py", line 271, in error_router
    return original_handler(e)
  File "C:\Users\APaws\sandbox\venv\venv\Lib\site-packages\flask\app.py", line 2073, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\APaws\sandbox\venv\venv\Lib\site-packages\flask\app.py", line 1518, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\APaws\sandbox\venv\venv\Lib\site-packages\flask_restful\__init__.py", line 271, in error_router
    return original_handler(e)
  File "C:\Users\APaws\sandbox\venv\venv\Lib\site-packages\flask\app.py", line 1516, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\APaws\sandbox\venv\venv\Lib\site-packages\flask\app.py", line 1502, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "C:\Users\APaws\sandbox\venv\venv\Lib\site-packages\flask_restful\__init__.py", line 471, in wrapper
    return self.make_response(data, code, headers=headers)
  File "C:\Users\APaws\sandbox\venv\venv\Lib\site-packages\flask_restful\__init__.py", line 500, in make_response
    resp = self.representations[mediatype](data, *args, **kwargs)
  File "C:\Users\APaws\sandbox\venv\venv\Lib\site-packages\flask_restful\representations\json.py", line 21, in output_json
    dumped = dumps(data, **settings)   "\n"
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\Lib\json\__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\Lib\json\encoder.py", line 201, in encode
    chunks = list(chunks)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\Lib\json\encoder.py", line 438, in _iterencode
    o = _default(o)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\Lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type MethodViewType is not JSON serializable

And here is the second request error:

127.0.0.1 - - [31/Mar/2022 12:32:40] "GET /reservation/0001 HTTP/1.1" 500 -
Traceback (most recent call last):
  File "C:\Users\APaws\sandbox\venv\venv\Lib\site-packages\flask\app.py", line 2091, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Users\APaws\sandbox\venv\venv\Lib\site-packages\flask\app.py", line 2076, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Users\APaws\sandbox\venv\venv\Lib\site-packages\flask_restful\__init__.py", line 271, in error_router
    return original_handler(e)
  File "C:\Users\APaws\sandbox\venv\venv\Lib\site-packages\flask\app.py", line 2073, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\APaws\sandbox\venv\venv\Lib\site-packages\flask\app.py", line 1518, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\APaws\sandbox\venv\venv\Lib\site-packages\flask_restful\__init__.py", line 271, in error_router
    return original_handler(e)
  File "C:\Users\APaws\sandbox\venv\venv\Lib\site-packages\flask\app.py", line 1516, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\APaws\sandbox\venv\venv\Lib\site-packages\flask\app.py", line 1502, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "C:\Users\APaws\sandbox\venv\venv\Lib\site-packages\flask_restful\__init__.py", line 467, in wrapper
    resp = resource(*args, **kwargs)
  File "C:\Users\APaws\sandbox\venv\venv\Lib\site-packages\flask\views.py", line 84, in view
    return current_app.ensure_sync(self.dispatch_request)(*args, **kwargs)
  File "C:\Users\APaws\sandbox\venv\venv\Lib\site-packages\flask_restful\__init__.py", line 582, in dispatch_request
    resp = meth(*args, **kwargs)
  File "C:\Users\APaws\sandbox\venv\app.py", line 48, in get
    for reservation in reservations:
TypeError: 'MethodViewType' object is not iterable

CodePudding user response:

class reservations(Resource):
    def get(self):
        return reservations

you named your class as "reservations" which is conflicting with your array of dictionaries. which is also called "reservations"

reservations = [
    {
        'first name': 'John',
        'surname': 'Smith',
        'event name': 'Event1',
        'code': 'J0HN'
    },
    {
        'first name': 'Jan',
        'surname': 'Kowalski',
        'event name': 'Event2',
        'code': '0001'
    }
]

Both the errors are related to this bug, where the class is not json serializable and it is also not iterable.

CodePudding user response:

I think iterating through a JSON tuple is not allowed in Python.

  • Related