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

Commit

Permalink
Merge pull request #310 from open-contracting/CPA-307
Browse files Browse the repository at this point in the history
307-insights-api-added
  • Loading branch information
KushalRaj committed May 24, 2021
2 parents 27517e6 + 518b1ef commit 1586a4f
Show file tree
Hide file tree
Showing 4 changed files with 128 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(), name="insights_view"),
path("", include("country.urls")),
path("api-auth/", include("rest_framework.urls")),
path("cms/", include(wagtailadmin_urls)),
Expand Down
5 changes: 5 additions & 0 deletions visualization/tests/test_urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
FilterParams,
GlobalOverView,
GlobalSuppliersView,
InsightsView,
MonopolizationView,
ProductDistributionView,
ProductFlowView,
Expand Down Expand Up @@ -204,3 +205,7 @@ def test_product_flow_view_url_is_resolved(self):
def test_supplier_flow_view_url_is_resolved(self):
url = reverse("supplier_flow_view", args=["1"])
self.assertEquals(resolve(url).func.view_class, SupplierFlowView)

def test_insights_view_url_is_resolved(self):
url = reverse("insights_view")
self.assertEquals(resolve(url).func.view_class, InsightsView)
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 1586a4f

Please sign in to comment.