简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM