我有一个mongoengine模型,其中包含一些公共字段和某些我想从“用户”组中隐藏的字段。那么,限制访问某些字段的明智方法是什么?
我的堆栈是Flask-Restful + mongoengine
我的想法是编写应做限制的自定义资源序列化器和装饰器。但是,还有一点不清楚-这个装饰器应该从函数输出中删除某些字段,还是相反地添加一些适合角色的字段?
@staticmethod
def serialize_operator(event):
json_to_decode = {
"id" : str(event.id),
"title" : event.title,
"description" : event.description,
"type" : event.type # so I want to hide this field
}
return json.loads(json.dumps(json_to_decode))
@get_auth
@some_restriction_decorator(user = get_auth())
def get(self):
pass
答案 0 :(得分:1)
我建议在模型类中定义序列化器,并使用字段(来自flask_restful)来定义它。然后,在您的控制器中,您可以使用marshal_with装饰器(或marshal函数)对返回值进行序列化。
# Model definition
from mongoengine import Document, StringField
from flask_restful import fields
class Article(Document):
title = StringField()
description = StringField()
type = StringField()
public_serializer = {
'id': fields.String,
'title': fields.String,
'description': fields.String
}
# Controller
from flask_restful import marshal_with
...
@marshal_with(Article.public_serializer)
def get(self):
return Article.objects.get(...)
这样,仅返回序列化程序中指定的字段。
注意1:您可以在任何需要的位置定义序列化程序,我只是希望将其包含在模型中。
注2:marshal_with句柄也会自动列出,因此return list(Article.objects)
也将起作用
注意3:您可以创建多个序列化器,并根据情况使用不同的