Search code examples
pythonflaskflask-sqlalchemyflask-restplus

How can I log marshaled messages sent by Flask-Restplus


Consider following bare minimum example:

from flask_restplus import Api, Resource, fields
from .models import User

ns = api.namespace('users', description='User related operations')

user = api.model('User', {
    'id': fields.Integer(readOnly=True, description='The user identifier'),
    'name': fields.String(required=True, description='The users name'),
    'password': fields.String(required=True, description='The users password')
})

@ns.route('/')
class UserList(Resource):
    @ns.doc('list_users')
    @ns.marshal_list_with(user)
    def get(self):
        data = User.query.all()
        print "Print the response here!"
        return data

I'm troubleshooting and I would like to be able to print/log the JSON response being returned by Flask-RestPlus, how could I do this?


Solution

  • Figured it out very quickly myself suddenly. Using the marshal function does the same as the @ns.marshal_list_with(user) annotation

    from flask_restplus import Api, Resource, fields, marshal
    from .models import User
    import json
    
    ns = api.namespace('users', description='User related operations')
    
    user = api.model('User', {
        'id': fields.Integer(readOnly=True, description='The user identifier'),
        'name': fields.String(required=True, description='The users firstName'),
        'password': fields.String(required=True, description='The users password')
    })
    
    @ns.route('/')
    class UserList(Resource):
        @ns.doc('list_users')
        @ns.marshal_list_with(user)
        def get(self):
            data = User.query.all()
            print json.dumps(marshal(User.query.all(), user))
            return data