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.

Question: best way on how to organize CRUD schema objects with marshmallow

See original GitHub issue

Hi, one question on what is the best practice to organize marshmallow schema objects for CRUD methods. Say, I have a simple class in SqlAlchemy:

class Order(Base):
    __tablename__ = 'Orders'
    
    id = Column(Integer, primary_key=True)
    name = Column(String)
    quantity = Column(Integer)
    placed_at = Column(DateTime)

Now, when creating new Order, I need schema that has name field only (and eventually placed_at automatically set to datetime.utcnow()). When updating, my endpoint for example should allow to change only name and quantity fields. On reading (and delete) however I want all fields: id, name, quantity and placed_at to be serialized (dumped).

What is the best/recommended way to do this: shall I crate one base class, containing the smallest set of attributes and then extend it (subclass it) and add additional fields? Or, shall I simply create different classes with no common class. I prefer using the base class approach whenever possible, but I am not sure will this complicate managing of dump_only and exclude_fields in sub-classes and make code hard to maintain?

Thank you in advance

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
scottwernervtcommented, Oct 29, 2018

You can filter schema attributes when loading and dumping using the only, exclude, and partial arguments.

from datetime import datetime

from marshmallow import Schema
from marshmallow.fields import DateTime, Integer, String

class Order(Schema):
    id = Integer(dump_only=True)
    name = String(required=True)
    quantity = Integer()
    # Use sqla default attribute to set timestamp
    placed_at = DateTime(dump_only=True)


order_schema = Order()
create_order_schema = Order(only=('name',))
update_update_schema = Order(only=('name', 'quantity'))

# post
create_order_schema.load({'name': 'Candy', 'quantity': 5})
# {'name': 'Candy'}

# get/delete: dump model
order_schema.dump({'id': 1, 'name': 'candy', 'quantity': 5, 'placed_at': datetime.utcnow()})
# {'id': 1, 'placed_at': '2018-10-29T14:48:37.969904+00:00', 'quantity': 5, 'name': 'candy'}

# patch: only name and quantity are allowed
update_update_schema.load({'quantity': 10}, partial=True)
# {'quantity': 10}
0reactions
nikoladspcommented, Oct 29, 2018

Yes, I am thinking the same, but trouble is that service code should be used both in endpoints and console application doing some administrative stuff directly (without usage of REST), so it seems I will have to keep validation inside service itself in order not to duplicate it. Second option is to use schema instance and perform validation inside service, but somehow this look more as the job for some ‘parameter’ class that will be instantiated within the service and raise an exception in __init__ automatically, or via separate validate() method that should be called upon creation of ‘param’ object

Read more comments on GitHub >

github_iconTop Results From Across the Web

Flask organize marshmallow schemas - python - Stack Overflow
Things are going a bit messy and hard to maintain, mainly with schemas, so I have questions about best way to organize whole...
Read more >
Object validation and conversion with Marshmallow in Python
Marshmallow provides a simple way to validate object data before sending it to the database. Marshmallow schemas use the validate() method in ...
Read more >
Flask REST API With SQLAlchemy & Marshmallow - YouTube
Flask- Marshmallow is a thin integration layer for Flask (a Python web ... and marshmallow (an object serialization/deserialization library) ...
Read more >
Marshmallow Schema Dump Many
Marshmallow schemas can be used to. Validate input data De-serialize input leaf to app-level objects Serialize app-level objects to primitive. How the.
Read more >
Building REST APIs using Flask-RESTPlus, SQLAlchemy ...
Create the Marshmallow Schemas from our models defined earlier using ... Flask-RESTPlus provides many ways to organize our application and ...
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