Search code examples
jsonpython-3.xattributeerrorsanic

AttributeError when I return class


I'm using sanic for my API, and peewe as ORM.

and I wanna create helper for json response, but I got the error

AttributeError: 'JsonResponse' object has no attribute 'all_records'

get method in controller

from sanic.response import json
from sanic.views import HTTPMethodView

from models.project import Project
from helpers.json import JsonResponse


class ProjectListResource(HTTPMethodView):
    def get(self, resp):
        projects = Project().select().dicts()
        return JsonResponse(projects, all_records=True)

and my helper class

from sanic.response import json


class JsonResponse:
    def __init__(self, model, all_records=None):
        self.model = self._model_query(model)
        self.all_records = all_records

    def _model_query(self, model):
        if self.all_records:
            records = json({model: list(model)})
        else:
            records = {}

        return records

Solution

  • Solved.

    I needed first initialize all_records variable.

    def __init__(self, model, all_records=None):
            self.all_records = all_records
            self.model = self._model_query(model)