Using a dynamically generated schema from an endpoint #778
-
I'm trying to define a schema on the fly based upon the user attached to the request (field based permissions so the schema is altered based upon who is logged in). I see I can create a schema dynamically: What I'm not sure about is how I use that schema in an endpoint response? The only examples of responses I see have them defined in the decorator: Is there a format for generating an endpoint response when the schema is defined inside the endpoint? Or does the schema always have to be defined in the decorator? I'm trying to dive through the source to find this answer but getting very lost. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
@helmetwearer would you wnat these schemes to be described in OpenAPI documentation json ? if so - maybe you can do like this, let's say you have 3 types of users: Anonymous, Regular, Admin class SomeSchemaAnonymous(ModelSchema):
class Config:
... modelf_fields = ['foo', 'bar']
class SomeSchemaRegular(ModelSchema):
class Config:
... modelf_fields = ['foo', 'bar', 'extra']
class SomeSchemaAdmin(ModelSchema):
class Config:
... modelf_fields = ['foo', 'bar', 'extra', 'secret']
@api.get('/some', response=Union[SomeSchemaAnonymous, SomeSchemaRegular, SomeSchemaAdmin])
def some(request):
obj = SomeModle.objects.get(...)
if user.is_anonymous():
return SomeSchemaAnonymous.from_orm(obj).dict()
elif ...
return SomeSchemaRegular.from_orm(obj).dict()
... but if that really complex dynamic thing then you can define response as anything and then create schemas dynanmically and validate use them for serialization: @api.get('/some', reponse=dict)
def some(request):
obj = SomeModle.objects.get(...)
if user.is_anonymous():
fields = ['foo', 'bar']
else:
fields = ['foo', 'bar', 'extra', request.user.username]
Schema = create_schema(SomeModel, fields=fields)
return Schema.from_orm(obj).dict() |
Beta Was this translation helpful? Give feedback.
@helmetwearer would you wnat these schemes to be described in OpenAPI documentation json ?
if so - maybe you can do like this, let's say you have 3 types of users: Anonymous, Regular, Admin