question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Pass schema context to `missing` callback.

See original GitHub issue

I sometimes need to fetch a default deserialized value from the outside of the schema. Method and Function callbacks are not called if the field is missing in JSON, would be nice to have something like:

class TestSchema(Schema):
    value = fields.Function(missing=itemgetter('default_value'))

So that TestSchema(context={'default_value': 123}).load({}) would returnvalue = 123` using the context.

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
lawschlossercommented, Nov 20, 2020

I was hoping to use the context dictionary to drive field logic, but I was disappointed to find that when using the missing parameter as a callable function, there is no avenue for accessing the context data.

I’d like to propose feeding the context dictionary as a parameter to the missing callable (unfortunately this would be a breaking change).

The rationale:

  1. The purpose behind context (if I am not mistaken) is to provide information to drive logic within a Field/Schema’s methods.
  2. The purpose behind the missing callable is to support an asynchronous/callback mechanism to allow the missing value to be determined/defined after the field has been instantiated (i.e. during load/parse time).
  3. To support both of the above intentions, I would think it appropriate to provide the context when calling the missing callable.

Below is a somewhat simplified example of what I would like to achieve.

In this specific case I have a custom field where I can define the missing callback on the Field itself, and have the context be provided to it.

class UserId(marshmallow.fields.Str):

    def __init__(self, *args, **kwargs):
        kwargs["missing"] = self._get_missing
        super(UserId, self).__init__(*args, **kwargs)

    @classmethod
    def _get_missing(cls, context):
        return context["user_id"]

Add it to a simple UserSchema… (note that the missing parameter is not specified in the UserId instantiation)

class UserSchema(marshmallow.Schema):
    id = UserId()

And then parse…

import flask
from myapp import authenticate
schema = UserSchema()
schema.context = authenticate()  # injects user information (e.g the user's actual id)
parsed = schema.load({}) # note the empty dictionary, thereby invoking the field's `missing` callable
# parsed {id: "302339403"}  # sweet, the `missing` callback populated the id for us!

Obviously the missing callable does not need to be defined as method on the field, but I figured this implementation might turn some gears for other potential solutions.

I’m a noob to marshmallow, so perhaps there are better ways to skin/think about this. Much appreciated!

And thank your for all of your work!

0reactions
lawschlossercommented, Dec 1, 2020

@lawschlosser Ah, I missed your comment. Unfortunately I can’t give this the thought it deserves at the moment. Would you mind opening a new issue so we don’t lose track of it?

Done, thanks!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Subscriptions in Apollo Server
We can pass this schema object to both the subscription server and ApolloServer . This way, we make sure that the same schema...
Read more >
Set up Lambda proxy integrations in API Gateway
Learn how to configure a Lambda proxy integration request and integration response in API Gateway.
Read more >
Schema
In both cases, the callback function is called with the current value as the first argument and a context object as the second....
Read more >
Schema | REST API Handbook
A schema is metadata that tells us how our data is structured. Most databases implement some form of schema which enables us to...
Read more >
Package API — xmlschema 2.1.1 documentation
defuse – optional argument to pass for construct schema and XMLResource instances ... use_defaults – whether to use default values for filling missing...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found