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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With