Skip to content

Commit

Permalink
Set streaming serialization separately from many (#661)
Browse files Browse the repository at this point in the history
  • Loading branch information
whytheplatypus authored Nov 7, 2018
1 parent bcbd10d commit cb7b5c1
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 7 deletions.
37 changes: 31 additions & 6 deletions apps/metrics/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
ListSerializer,
IntegerField,
DateTimeField,
LIST_SERIALIZER_KWARGS,
)
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
Expand All @@ -29,6 +30,8 @@

log = logging.getLogger('hhs_server.%s' % __name__)

STREAM_SERIALIZER_KWARGS = LIST_SERIALIZER_KWARGS


class StreamingSerializer(ListSerializer):
@property
Expand All @@ -45,13 +48,35 @@ def data(self):


class StreamableSerializerMixin(object):
def __new__(cls, *args, **kwargs):

# We override this method in order to automagically create
# `ListSerializer` classes instead when `many=True` is set.
if kwargs.pop('many', False):
if kwargs.pop('stream', False):
return cls.stream_init(*args, **kwargs)
return cls.many_init(*args, **kwargs)

return super().__new__(cls, *args, **kwargs)

@classmethod
def many_init(cls, *args, **kwargs):
stream = kwargs.pop('stream', False)
if stream:
meta = getattr(cls, 'Meta', None)
setattr(meta, 'list_serializer_class', getattr(meta, 'stream_serializer_class', StreamingSerializer))
return super().many_init(*args, **kwargs)
def stream_init(cls, *args, **kwargs):
allow_empty = kwargs.pop('allow_empty', None)
child_serializer = cls(*args, **kwargs)
stream_kwargs = {
'child': child_serializer,
}
if allow_empty is not None:
stream_kwargs['allow_empty'] = allow_empty

stream_kwargs.update({
key: value for key, value in kwargs.items()
if key in STREAM_SERIALIZER_KWARGS
})

meta = getattr(cls, 'Meta', None)
stream_serializer_class = getattr(meta, 'stream_serializer_class', StreamingSerializer)
return stream_serializer_class(*args, **stream_kwargs)


class UserSerializer(ModelSerializer):
Expand Down
2 changes: 1 addition & 1 deletion hhs_oauth_server/request_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def __str__(self):

if log_msg['response_code'] in (300, 301, 302, 307):
log_msg['location'] = self.response.get('Location', '?')
elif self.response.content:
elif getattr(self.response, 'content', False):
log_msg['size'] = len(self.response.content)

log_msg['user'] = str(get_user_from_request(self.request))
Expand Down

0 comments on commit cb7b5c1

Please sign in to comment.