Is there a way to pass current_user object from flask app to schema to be used to determine a Boolean.
Currently I have a couple of tables:
Tables/Relations:
user_table
subscription_table
-foreignkey to user_table as user_id
-foreignkey to game_table as game_id
game_table
- backref to subscription_table as subscription
- is_subscribed is a property that returns a Bool if user has a subscription to current game_table
from flask import current_user
class Game(db.Model):
...
@property
def isSubscribed(user=None):
return current_user.is_subscribed_to_current_game()
...
I want to be able to extract game_table data with a schema. But how can I pass a user_id from my request to the schema to be used to see if user is currently subscribed to a game_table?
OR Another approach is:
How can I append another element/dict element to the already dumped result?
{
'data':[
{
'id' :1,
'name': 'some_name',
'isSubscribed': false, <<<<< How do I append a boolean from request to the already dumped schema?
},...
]
}
Thanks! I'm really new to marshmallow.
class GameSchema(marshmallow.Schema):
is_subscribed = marshmallow.fields.Method('get_subscribed')
def get_subscribed(self, game):
return game.user_id == self.context.get('user_id')
schema = GameSchema()
schema.context['user_id'] = flask.current_user
schema.dump(game)
Also, it is possible to update dumped result afterwards:
games_data = GameSchema(many=True).dump(games)
for game_data in games_data:
game_data['is_subscribed'] = is_user_subscribed_to_game(user_id, game_data['id'])
return games_data
@maximkulkin is correct--either use context or update the data afterwards.
You could even update the context automatically using pre_load:
from marshmallow import Schema, fields, pre_dump
class GameSchema(Schema):
is_subscribed = fields.Method('get_subscribed')
def get_subscribed(self, game):
return game.user_id == self.context['current_user'].id
@pre_dump
def set_current_user(self, data):
self.context['current_user'] = current_user
Most helpful comment
Also, it is possible to update dumped result afterwards: