Skip to content
This repository has been archived by the owner on Dec 13, 2022. It is now read-only.

Commit

Permalink
307-insights-api-added
Browse files Browse the repository at this point in the history
 - [x] Set API endpoint as api/contents/insights
 - [x] Filter parameter country, type, year
 - [x] Pagination implemented
 - [x] ordering implemented
 - [x] search implemented
 - [x] pagination page bug fixed
 - [x] desc ordering added
 - [x] total count of record added
  • Loading branch information
sonikabaniya committed May 21, 2021
1 parent 27517e6 commit 77247d4
Show file tree
Hide file tree
Showing 3 changed files with 123 additions and 1 deletion.
3 changes: 2 additions & 1 deletion covidadmin/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
# from wagtail.core import urls as wagtail_urls
from wagtail.documents import urls as wagtaildocs_urls

from visualization.views import SlugBlogShow, SlugStaticPageShow, UpcomingEventView
from visualization.views import InsightsView, SlugBlogShow, SlugStaticPageShow, UpcomingEventView

from .api import api_router

Expand All @@ -39,6 +39,7 @@
path("api/contents/<str:type>/<str:slug>/", SlugBlogShow.as_view()),
path("api/staticpage/<str:type>", SlugStaticPageShow.as_view()),
path("api/upcoming-events", UpcomingEventView.as_view()),
path("api/contents/insights", InsightsView.as_view()),
path("", include("country.urls")),
path("api-auth/", include("rest_framework.urls")),
path("cms/", include(wagtailadmin_urls)),
Expand Down
1 change: 1 addition & 0 deletions visualization/views/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from .filter_params import FilterParams
from .global_over_view import GlobalOverView
from .global_suppliers_view import GlobalSuppliersView
from .insights_view import InsightsView
from .monopolization_view import MonopolizationView
from .product_distribution_view import ProductDistributionView
from .product_flow_view import ProductFlowView
Expand Down
120 changes: 120 additions & 0 deletions visualization/views/insights_view.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.http import JsonResponse
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from rest_framework.views import APIView

from content.models import InsightsPage, ResourcesPage
from visualization.helpers.general import page_expire_period


class ViewPaginatorMixin(object):
min_limit = 1
max_limit = 10

def paginate(self, object_list, page=1, limit=10, count=0, **kwargs):
try:
page = int(page)
if page < 1:
page = 1
except (TypeError, ValueError):
page = 1

try:
limit = int(limit)
if limit < self.min_limit:
limit = self.min_limit
if limit > self.max_limit:
limit = self.max_limit
except (ValueError, TypeError):
limit = self.max_limit

paginator = Paginator(object_list, limit)
try:
objects = paginator.page(page)
except PageNotAnInteger:
objects = paginator.page(1)
except EmptyPage:
objects = paginator.page(paginator.num_pages)
data = {
"previous_page": objects.has_previous() and objects.previous_page_number() or None,
"next_page": objects.has_next() and objects.next_page_number() or None,
"count": count,
"data": list(objects),
}
return data


class InsightsView(ViewPaginatorMixin, APIView):
@method_decorator(cache_page(page_expire_period()))
def get(self, request):
country = self.request.GET.get("country", None)
insight_type = self.request.GET.get("type", None)
year = self.request.GET.get("year", None)
order = self.request.GET.get("order", None)
query = self.request.GET.get("query", None)
page = self.request.GET.get("page", None)

result_insight = []
result_resource = []
filter_args = {}
filter_insights_args = {}

if country:
filter_args["country__country_code_alpha_2"] = country

if insight_type:
if insight_type in ["News", "Blog"]:
filter_insights_args["contents_type"] = insight_type

if year:
filter_args["published_date__year"] = year

try:
if insight_type in ["News", "Blog"] or insight_type is None:
results_insight = InsightsPage.objects.filter(**filter_args, **filter_insights_args).values(
"title", "page_ptr_id", "country__name", "published_date__year", "contents_type"
)

for i in results_insight:
result_insight.append(
{
"id": i["page_ptr_id"],
"title": i["title"],
"country": i["country__name"],
"type": i["contents_type"],
"year": i["published_date__year"],
}
)
if insight_type in ["Resources"] or insight_type is None:
results_resources = ResourcesPage.objects.filter(**filter_args).values(
"title", "page_ptr_id", "country__name", "published_date__year"
)

for i in results_resources:
result_resource.append(
{
"id": i["page_ptr_id"],
"title": i["title"],
"country": i["country__name"],
"type": "Resources",
"year": i["published_date__year"],
}
)

result = result_insight + result_resource
count = len([ele for ele in result if isinstance(ele, dict)])

if order is not None:
if "-" in order:
result = sorted(result, key=lambda k: k[order[1:]], reverse=True)
else:
result = sorted(result, key=lambda k: k[order])

if query is not None:
result = list(filter(lambda i: i["title"].find(query) != -1, result))

return JsonResponse({"data": self.paginate(result, page, count=count)})

except Exception as e:
return JsonResponse([{"error": str(e)}], safe=False)

0 comments on commit 77247d4

Please sign in to comment.