Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use marshal_with in flask_restful for attributes that can be of different types

I'm using flask_restful.marshal_with to sanitize my entities:

class Domain(db.Model):

    __tablename__ = 'domain'

    id = db.Column(db.BigInteger, primary_key=True)
    domain_name = db.Column(db.String(253), unique=True)
    user_id = db.Column(db.BigInteger, db.ForeignKey('user.id'), nullable=True)
    .... # bunch of other sensitive fields I don't want to output

Here's my handler:

class Domains(Resource):
    domain_fields = {
        'id': fields.Integer,
        'user_id': fields.Integer,
        'domain_name': fields.String
        }

    @marshal_with(domain_fields)
    def get(self, domain_id):
        """return domain details"""
        entity = domain.Domain.query.get(domain_id)

        return entity 

The user_id attribute can be either None or an Integer.

What's a a good say to setup the domain_fields to output either Bool or Int instead of just limited to Int?

like image 546
ristoh Avatar asked Sep 15 '25 01:09

ristoh


1 Answers

You could put a default in user_id that will be returned if user_id is None, or you could create a custom field for user_id to handle properly.

domain_fields = {
    'id': fields.Integer,
    'user_id': fields.Integer(default=False),
    'domain_name': fields.String
}

or

class CustomField(fields.Raw):
    def output(self, key, obj):
        return obj.user_id or False

domain_fields = {
    'id': fields.Integer,
    'user_id': CustomField,
    'domain_name': fields.String
}
like image 129
juanrossi Avatar answered Sep 16 '25 14:09

juanrossi