Skip to content

Commit

Permalink
update hyperlinkrelated to gracefully support nullable / non-required…
Browse files Browse the repository at this point in the history
… sqla relations
  • Loading branch information
feigner committed Feb 12, 2019
1 parent 8b2286f commit 75ced3c
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
9 changes: 8 additions & 1 deletion flask_marshmallow/sqla.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from Flask-SQLALchemy.
"""
from flask import url_for, current_app
from werkzeug.routing import BuildError
from six.moves.urllib import parse

import marshmallow_sqlalchemy as msqla
Expand Down Expand Up @@ -62,7 +63,13 @@ def __init__(self, endpoint, url_key='id', external=False, **kwargs):
def _serialize(self, value, attr, obj):
key = super(HyperlinkRelated, self)._serialize(value, attr, obj)
kwargs = {self.url_key: key}
return url_for(self.endpoint, _external=self.external, **kwargs)
try:
return url_for(self.endpoint, _external=self.external, **kwargs)
except BuildError as e:
if not self.required:
return self.missing if self.missing else None
else:
raise e

def _deserialize(self, value, *args, **kwargs):
if self.external:
Expand Down
15 changes: 13 additions & 2 deletions tests/test_sqla.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from flask import Flask, url_for
from flask_sqlalchemy import SQLAlchemy
from werkzeug.wrappers import BaseResponse
from werkzeug.routing import BuildError

from flask_marshmallow import Marshmallow
from flask_marshmallow.sqla import HyperlinkRelated
Expand Down Expand Up @@ -138,12 +139,16 @@ class Meta:
deserialized, errors = get_load_data(book_schema, book_result)
assert deserialized.author == author

# Deserialization works on nullable / non-required relation
book.author = None
book_result = book_schema.dump(book)
assert book_result['author'] is None

def test_hyperlink_related_field_errors(self, extma, models, db, extapp):
class BookSchema(extma.ModelSchema):
class Meta:
model = models.Book

author = HyperlinkRelated('author')
author = HyperlinkRelated('author', required=True)

book_schema = BookSchema()

Expand All @@ -166,6 +171,12 @@ class Meta:
deserialized, errors = get_load_data(book_schema, book_result)
assert 'URL pattern "pk" not found' in errors['author'][0]

# Deserialization fails on empty required field
book.author = None
with pytest.raises(BuildError) as exc:
book_schema.dump(book)
assert "endpoint 'author'" in str(exc.value)

def test_hyperlink_related_field_external(self, extma, models, db, extapp):
class BookSchema(extma.ModelSchema):
class Meta:
Expand Down

0 comments on commit 75ced3c

Please sign in to comment.