diff --git a/articles/test_with_articles.py b/articles/test_with_articles.py index a84e56828a3891195fc3a16e7ca9ce95942f8025..4e37efefa6622680aa2362585eb06c39ca9b8e4f 100644 --- a/articles/test_with_articles.py +++ b/articles/test_with_articles.py @@ -106,6 +106,19 @@ class TimelineListTest(CreateArticlesWithTagsTestCase): ], ) + def test_get_all_timeline_cached(self): + """ + Tests cached timeline api. + Should just a 200 response with a small message. + """ + logger.info("started TimelineListTest.test_get_all_timeline_cached") + + response = self.client.get('/articles/tags/timeview?mediaOverviewType=' + MediaOverviewType.ALLTAGS.value + + '&cached=true') + self.assertEqual(response.status_code, 200) + self.assertJSONEqual(str(response.content, encoding='utf8'), + {"message": "No data is gathered"}) + def test_get_standard_user_timeline(self): """ Tests the API without a user specified in the query. @@ -242,6 +255,17 @@ class OverviewTest(CreateArticlesWithTagsTestCase): ], ) + def test_overview_api_cached(self): + """ + Tests cached overview api. + Should just a 200 response with a small message. + """ + logger.info("started OverviewTest.test_overview_api_cached") + response = self.client.get('/articles/overview?cached=true') + self.assertEqual(response.status_code, 200) + self.assertJSONEqual(str(response.content, encoding='utf8'), + {"message": "No data is gathered"}) + def test_overview_api_with_user(self): """ Tests the API with a specific user id passed in the query. @@ -400,6 +424,18 @@ class TopMediaTest(CreateArticlesWithTagsTestCase): self.assertEqual(response.status_code, 200) self.assertJSONEqual(str(response.content, encoding='utf8'), [{'article_count': 1, 'medium_name': 'maz'}]) + def test_top_media_cached(self): + """ + Tests cached parameter. + Should just a 200 response with a small message. + """ + logger.info("started TopMediaTest.test_top_media_cached") + response = self.client.get( + '/articles/top/media?mediaOverviewType=' + MediaOverviewType.ALLTAGS.value + '&cached=true') + self.assertEqual(response.status_code, 200) + self.assertJSONEqual(str(response.content, encoding='utf8'), + {"message": "No data is gathered"}) + def test_top_media_with_extra_articles(self): """ Tests the API without a user specified in the query after two new articles are written to the database. @@ -653,6 +689,17 @@ class UserTagsTest(CreateArticlesWithTagsTestCase): self.assertEqual(response.status_code, 200) self.assertJSONEqual(str(response.content, encoding='utf8'), [{'name': 'Test1'}, {'name': 'Test2'}]) + def test_user_tags_cached(self): + """ + Tests cached user tags. + Should just a 200 response with a small message. + """ + logger.info("started UserTagsTest.test_user_tags_cached") + response = self.client.get('/articles/user/tags?cached=true') + self.assertEqual(response.status_code, 200) + self.assertJSONEqual(str(response.content, encoding='utf8'), + {"message": "No data is gathered"}) + def test_get_with_wrong_uid(self): """ Tests how the API handles a request with a user id that doesn't exist. diff --git a/articles/views.py b/articles/views.py index 091d08f7b0092132fd16cbbd42af50f2cb78c056..7c98044c2cabe1292eec08e54130034c0e22ea77 100644 --- a/articles/views.py +++ b/articles/views.py @@ -158,6 +158,9 @@ def user_tags(request_params): user_param_get = openapi.Parameter( 'user', openapi.IN_QUERY, description="id which is connected to the user", type=openapi.TYPE_NUMBER ) +cache_param_get = openapi.Parameter( + 'cached', openapi.IN_QUERY, description="is the answer already cached?", type=openapi.TYPE_BOOLEAN +) class TimelineList(APIView): @@ -165,7 +168,8 @@ class TimelineList(APIView): Returns Timeline objects containing monthly article_count and reach values for selected topics over the last year """ - @swagger_auto_schema(manual_parameters=[user_param_get], responses={200: TimelineSerializer(many=True)}) + @swagger_auto_schema(manual_parameters=[user_param_get, cache_param_get], + responses={200: TimelineSerializer(many=True)}) def get(self, request): """ Get Timeline objects for a specified media_overview_type @@ -179,6 +183,10 @@ class TimelineList(APIView): """ try: first = datetime.datetime.today() + if 'cached' in request.query_params and request.query_params['cached'].lower() == 'true': + logger.info('tags/timeview ' + str(datetime.datetime.today() - first)) + return Response({'message': 'No data is gathered'}, 200) + media_overview_type = request.query_params['mediaOverviewType'] today = datetime.datetime.today() datetime_recent = today - datetime.timedelta(days=365) @@ -221,7 +229,8 @@ class OverviewList(APIView): today = datetime.datetime.today() datetime_recent = today - datetime.timedelta(days=90) - @swagger_auto_schema(manual_parameters=[user_param_get], responses={200: OverviewSerializer(many=True)}) + @swagger_auto_schema(manual_parameters=[user_param_get, cache_param_get], + responses={200: OverviewSerializer(many=True)}) def get(self, request): """ Returns Overview objects for a users favorite tags in the last 90 days. @@ -230,6 +239,9 @@ class OverviewList(APIView): """ try: first = datetime.datetime.today() + if 'cached' in request.query_params and request.query_params['cached'].lower() == 'true': + logger.info('overview ' + str(datetime.datetime.today() - first)) + return Response({'message': 'No data is gathered'}, 200) if 'mediaOverviewType' in request.query_params: media_overview_type = request.query_params['mediaOverviewType'] else: @@ -443,7 +455,7 @@ class Logs(TemplateView): logs = UserActivityLogs.objects.filter(user_id=context['userid']).order_by('timestamp') for line in logs: line.timestamp = line.timestamp.strftime("%d. %b %Y, %H:%M:%S.%f") - line.timestamp = line.timestamp[:len(line.timestamp)-3] + line.timestamp = line.timestamp[:len(line.timestamp) - 3] context['logs'] = logs used_users = [] @@ -451,7 +463,7 @@ class Logs(TemplateView): user_logs = UserActivityLogs.objects.filter(user_id=user.id_tag).order_by('-timestamp') if user_logs: user_logs[0].timestamp = user_logs[0].timestamp.strftime("%d. %b %Y, %H:%M:%S.%f") - user_logs[0].timestamp = user_logs[0].timestamp[:len(user_logs[0].timestamp)-3] + user_logs[0].timestamp = user_logs[0].timestamp[:len(user_logs[0].timestamp) - 3] used_users.append([user, user_logs[0].timestamp]) used_users.sort(reverse=True, key=sort_by_timestamp) @@ -658,7 +670,8 @@ class UploadView(View): class TopMediaView(APIView): """Return the media with the highest article count""" - @swagger_auto_schema(manual_parameters=[user_param_get], responses={200: TopMediaSerializer(many=True)}) + @swagger_auto_schema(manual_parameters=[user_param_get, cache_param_get], + responses={200: TopMediaSerializer(many=True)}) def get(self, request): """ Get the top media outlets for a specified media_overview_type @@ -672,6 +685,9 @@ class TopMediaView(APIView): """ try: first = datetime.datetime.today() + if 'cached' in request.query_params and request.query_params['cached'].lower() == 'true': + logger.info('top/media ' + str(datetime.datetime.today() - first)) + return Response({'message': 'No data is gathered'}, 200) media_overview_type = request.query_params['mediaOverviewType'] tag_ids = [] if media_overview_type == MediaOverviewType.ALLTAGS.value: @@ -682,7 +698,9 @@ class TopMediaView(APIView): elif media_overview_type == MediaOverviewType.USERTAGS.value: tag_ids = user_tags(request.query_params) # Counts the number of articles in a medium depending on user tags - top_media = (Article.objects.filter(tags__id__in=tag_ids, wrongly_parsed=False).values('medium__name').annotate(article_count=Count('id', distinct=True)).order_by('-article_count', 'medium__name')) + top_media = ( + Article.objects.filter(tags__id__in=tag_ids, wrongly_parsed=False).values('medium__name').annotate( + article_count=Count('id', distinct=True)).order_by('-article_count', 'medium__name')) elif media_overview_type == MediaOverviewType.QUERYTAG.value: params_tag_ = request.query_params['tag'] tag_id = Tag.objects.filter(name=params_tag_).values_list('id', flat=True) @@ -732,7 +750,7 @@ tags_param_post = openapi.Parameter( class UserFavoriteTags(APIView): """Defines get and post methods related to a users favorite tags""" - @swagger_auto_schema(manual_parameters=[user_param_get], responses={200: TagSerializer(many=True)}) + @swagger_auto_schema(manual_parameters=[user_param_get, cache_param_get], responses={200: TagSerializer(many=True)}) def get(self, request): """ Returns favorite tags for a specific user @@ -741,6 +759,9 @@ class UserFavoriteTags(APIView): """ try: first = datetime.datetime.today() + if 'cached' in request.query_params and request.query_params['cached'].lower() == 'true': + logger.info('user/tags ' + str(datetime.datetime.today() - first)) + return Response({'message': 'No data is gathered'}, 200) tag_ids = user_tags(request.query_params) tags = Tag.objects.filter(id__in=tag_ids, article__wrongly_parsed=False).distinct() tag_serializer = TagSerializer(tags, many=True) @@ -1174,7 +1195,8 @@ class NightlyPersistLogs(APIView): run_too_soon = False if existing_logs: - if existing_logs[0].transferred_date > timezone.make_aware(datetime.datetime.now() - datetime.timedelta(hours=23)): + if existing_logs[0].transferred_date > timezone.make_aware( + datetime.datetime.now() - datetime.timedelta(hours=23)): run_too_soon = True if not run_too_soon: