Created
August 6, 2019 07:54
-
-
Save multimeric/2e710b50dfccc6cdb348f398627bc0ee to your computer and use it in GitHub Desktop.
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
class ResourceHyperlink(ma.Field): | |
""" | |
Serializes as a hyperlink to a flask_restful Resource | |
""" | |
def __init__(self, endpoint, url_args=None, *args, **kwargs): | |
super().__init__(*args, **kwargs) | |
# If the user passes in a list of args, we assume a field with the exact same name appears on the relation | |
if isinstance(url_args, list): | |
self.url_args = {key: None for key in url_args} | |
else: | |
self.url_args = url_args | |
self.endpoint = endpoint | |
def convert_url(self, object): | |
args = {} | |
for key, value in self.url_args.items(): | |
if value is None: | |
args[key] = getattr(object, key) | |
else: | |
args[key] = getattr(object, value) | |
return url_for(self.endpoint, **args) | |
def _serialize(self, value, attr, obj): | |
""" | |
:param value: The current value of this attribute (the SQLAlchemy model) | |
:param attr: The name of the attribute | |
:param obj: The current object we're serializing | |
""" | |
if isinstance(value, InstrumentedList): | |
return [self.convert_url(relation) for relation in value] | |
else: | |
return self.convert_url(value) | |
def _deserialize(self, value, attr, data): | |
raise NotImplementedError() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Copied from marshmallow-code/flask-marshmallow#144
You use it like this:
Basically you can either provide
url_args
as a list of keys that we take directly from the related model to apply to the URL (in this case,report_id
andsample_id
), or you can make that a dictionary that maps URL segments to model properties as I explained above.I also require that you pass in an endpoint rather than a resource object, just because there will be issues with circular dependencies if you import the resources from the schema and then import the schema in the resources in order to dump/load. The endpoint string for a given resource will be
module.path.resource_name
, although you can override it with therestful.add_resource()
function.I also recommend that you prefetch the related objects for this field, using
query.options(joinedload(user_models.User.roles))
, since my class makes use of the related object. If you don't do this, the efficiency will be much worse