Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

request MUST be declared for serializer #3

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 13 additions & 9 deletions sorl_thumbnail_serializer/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,14 @@ class TestModelViewSet(viewsets.ModelViewSet):

from rest_framework import serializers
from sorl.thumbnail import get_thumbnail
from .settings import SORL_THUMBNAIL_SETTINGS as api_settings


class HyperlinkedSorlImageField(serializers.ImageField):

"""A Django REST Framework Field class returning hyperlinked scaled and cached images."""

def __init__(self, geometry_string, options={}, *args, **kwargs):
def __init__(self, geometry_string, options={}, uri_prefix=api_settings['URI_PREFIX'], *args, **kwargs):
"""
Create an instance of the HyperlinkedSorlImageField image serializer.

Expand All @@ -65,6 +66,7 @@ def __init__(self, geometry_string, options={}, *args, **kwargs):
""" # NOQA
self.geometry_string = geometry_string
self.options = options
self.uri_prefix = uri_prefix
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A corresponding entry in the Args: list above would be nice ☺️

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you mean you don't like settings usage here?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry that's a bit unclear now that I read it myself. I just meant I'd like an the docstring above, under the Args heading.


super(HyperlinkedSorlImageField, self).__init__(*args, **kwargs)

Expand All @@ -82,12 +84,14 @@ def to_representation(self, value):

image = get_thumbnail(value, self.geometry_string, **self.options)

try:
request = self.context.get('request', None)
return request.build_absolute_uri(image.url)
except:
try:
return super(HyperlinkedSorlImageField, self).to_representation(image.url)
except AttributeError: # NOQA
return super(HyperlinkedSorlImageField, self).to_native(image.url) # NOQA
request = self.context.get('request', None)
assert request is not None, (
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure how this would fare with existing usage as the current implementation attempts to use FileField.to_representation() behaviour (i.e. relative path to image) as a fallback. Up until now I've let to_representation() fail silently (which admittedly is not always the best option) but this introduces a potential AssertionError.

While I'm not too afraid of breaking changes at this stage I think it's worth some consideration. Perhaps this behaviour should only be triggered by a specific option?

"`%s` requires the request in the serializer"
" context. Add `context={'request': request}` when instantiating "
"the serializer." % self.__class__.__name__
)

if self.uri_prefix:
return request.build_absolute_uri(self.uri_prefix + image.url)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is uri_prefix (and settings.URI_PREFIX) meant to for a path component or a complete URL, or both? I guess build_absolute_uri() would handle both.

I think I would prefer something like

from urllib.parse import urljoin
urljoin(self.uri_prefix, image.url)

or even os.path.join(self.uri_prefix, image.url) though.

return request.build_absolute_uri(image.url)
to_native = to_representation
5 changes: 5 additions & 0 deletions sorl_thumbnail_serializer/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.conf import settings

SORL_THUMBNAIL_SETTINGS = getattr(settings, "SORL_THUMBNAIL_SETTINGS", {})

SORL_THUMBNAIL_SETTINGS.setdefault("URI_PREFIX", None)