Answer the question
In order to leave comments, you need to log in
How to add additional data to ModelSchema flask-marshmallow?
I'm writing an API for Flask-RESTplus using Flask-Marshmallow . There is a need to add some information to the response generated via schema.dump(some_data) . For example, I have a Flask-SQLAlchemy model :
class User(mixins.PaginatedAPIMixin, db.Model):
id = db.Column(db.Integer, primary_key=True, unique=True)
username = db.Column(db.String(45), nullable=False, unique=True)
password_hash = db.Column(db.String(128), unique=True)
@api.route('/', endpoint='users')
class UsersResource(Resource):
@api.param('page', description='Page number :int:')
@api.param('per_page', description='Items per page :int:')
def get(self):
args = parse_get_args(page=int, per_page=int)
users = User.get_paginated(User.query, self, args['page'], args['per_page'])
schema = UsersSchema(many=True)
dumped_data = schema.dump(users['items']).data
dumped_data.append({'_links': users['_links'], '_meta': users['_meta']})
return schema.jsonify(dumped_data)
class UsersSchema(ma.ModelSchema):
class Meta:
model = User
fields = ('id', 'username')
{'items': items,
'_meta': {
'page': 1,
'per_page': 20,
'total_pages': 1,
'total_items': 2
},
'_links': {
'self': 'api/v1/users/?page=1&per_page=20',
'next': None,
'prev': None
}}
[
{
"id": 1,
"username": "spam"
},
{
"id": 2,
"username": "egg"
},
{}
]
[
"items": [
{
"id": 1,
"username": "spam"
},
{
"id": 2,
"username": "egg"
}
],
"_links": {
"self": "api/v1/users/?page=1&per_page=20"
},
"_meta": {
"page": 1,
"per_page": 20,
"total_pages": 1,
"total_items": 2
},
]
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question