I use sanic for my API, and peewe as ORM And I want to create a helper class which will enhance the json answer, but here’s an error, tell me which way to look.

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 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 

    1 answer 1

    In the JsonResponse class in the initialization method, you call the _model_query method, which refers to self.all_records, as the first line. However, at this point self.all_records does not exist yet - it will be created only in the next line of the initialization method.

    You need to rewrite the initialization method like this:

     def __init__(self, model, all_records=None): self.all_records = all_records # Сначала эта строка self.model = self._model_query(model) # И только потом эта 
    • Thank you, it works. Something did not immediately look :) sometimes you need to be more careful. - Mike Yusko