Last active
July 17, 2020 02:42
-
-
Save abhijat/dfb55bb9c3b34018cc86b8e9edfaac11 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
| registry = {} | |
| class Meta(type): | |
| def __new__(mcs, name, bases, namespace): | |
| cls_instance = super().__new__(mcs, name, bases, namespace) | |
| registry[getattr(namespace['Meta'], 'system_name')] = cls_instance | |
| return cls_instance | |
| class AWSProcessor(metaclass=Meta): | |
| class Meta: | |
| system_name = 'aws' | |
| def process(self): | |
| print('business logic on aws') | |
| class GCPProcessor(metaclass=Meta): | |
| class Meta: | |
| system_name = 'gcp' | |
| def process(self): | |
| print('business logic on gcp') | |
| def locate_processor(system_name): | |
| return registry[system_name]() | |
| locate_processor('aws').process() | |
| locate_processor('gcp').process() | |
| """ | |
| Nested JSON queries | |
| """ | |
| class NestedData(models.Model): | |
| data = JSONField(encoder=DjangoJSONEncoder) | |
| def __repr__(self): | |
| import json | |
| return json.dumps(self.data) | |
| def __str__(self): | |
| return self.__repr__() | |
| class JSONTest(TestCase): | |
| def test_nested_query(self): | |
| good = NestedData.objects.create(data={ | |
| 'created_at': datetime.now().astimezone(pytz.UTC).isoformat(), | |
| 'details': { | |
| 'ratings': 9.1 | |
| } | |
| }) | |
| bad = NestedData.objects.create(data={ | |
| 'created_at': datetime(year=2011, month=1, day=1).astimezone(pytz.UTC).isoformat(), | |
| 'details': { | |
| 'ratings': 4.222 | |
| } | |
| }) | |
| good_ratings = NestedData.objects.filter(data__details__ratings__gt=8).all() | |
| self.assertListEqual([good], list(good_ratings)) | |
| bad_ratings = NestedData.objects.filter(data__details__ratings__lte=5).all() | |
| self.assertListEqual([bad], list(bad_ratings)) | |
| now = datetime.now().astimezone(pytz.UTC) | |
| old_ratings = NestedData.objects.filter(data__created_at__lte=now).all() | |
| self.assertCountEqual((bad, good,), old_ratings) | |
| past = datetime(year=2011, month=1, day=21).astimezone(pytz.UTC) | |
| new_ratings = NestedData.objects.filter(data__created_at__gt=past).all() | |
| self.assertCountEqual((good,), new_ratings) | |
| self.assertEqual(NestedData.objects.order_by('data__created_at').values_list('data__details__ratings', flat=True)[0], 4.222) | |
| self.assertEqual(NestedData.objects.order_by('-data__created_at').values_list('data__details__ratings', flat=True)[0], 9.1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment