Last active
July 2, 2020 16:22
-
-
Save richard-savant/4b37c84579968ebbb8f14776a7ca3b8e to your computer and use it in GitHub Desktop.
Marshmallow with custom operation for a field
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from src import models | |
from werkzeug import security | |
from marshmallow.fields import Field | |
from marshmallow import post_load, fields | |
import json | |
class Author(models.db.Model): | |
id = models.db.Column(models.db.Integer, primary_key=True) | |
name = models.db.Column(models.db.String(255)) | |
password_hash = models.db.Column(models.db.String) | |
def set_password(self, password: str) -> None: | |
self.password_hash = security.generate_password_hash(password) | |
return self.password_hash | |
def check_password(self, password: str) -> bool: | |
return security.check_password_hash(self.password_hash, password) | |
ma = models.ma | |
class AuthorSchema(models.ma.SQLAlchemySchema): | |
class Meta: | |
model = Author | |
load_instance = True | |
id = ma.auto_field(dump_only=True) | |
name = ma.auto_field() | |
_password = fields.Str(required=True) | |
@post_load | |
def make_instance(self, *data, **kwargs) -> 'Author': | |
instance: Author = super().make_instance(*data, **kwargs) | |
# TODO: execute custom code here like: | |
# instance.set_password("something") | |
__import__('ipdb').set_trace() | |
return instance | |
# from src.models import User | |
from src.app import create_app | |
# Load config | |
import src.settings as cfg_module | |
cfg: object = cfg_module.DevelopmentConfig() | |
app = create_app(cfg) | |
with app.app_context(): | |
author_serializer = AuthorSchema() | |
data_author = [{"_password": "richard", "name": "MegaAuthor"}, {"_password": "alexis", "name": "OkAuthor"}, {"name": "Ram", "_password": "12345"}] | |
authors = author_serializer.load(data_author, many=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment