Skip to content

Commit

Permalink
added export option in CSV
Browse files Browse the repository at this point in the history
  • Loading branch information
vishalanandl177 committed Apr 12, 2022
1 parent 89b1fce commit 4e8b4c1
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 7 deletions.
7 changes: 3 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# DRF API Logger
![version](https://img.shields.io/badge/version-1.0.10-blue.svg)
![version](https://img.shields.io/badge/version-1.1.10-blue.svg)
[![Downloads](https://static.pepy.tech/personalized-badge/drf-api-logger?period=total&units=none&left_color=black&right_color=orange&left_text=Downloads%20Total)](http://pepy.tech/project/drf-api-logger)
[![Downloads](https://static.pepy.tech/personalized-badge/drf-api-logger?period=month&units=none&left_color=black&right_color=orange&left_text=Downloads%20Last%20Month)](https://pepy.tech/project/drf-api-logger)
[![Downloads](https://static.pepy.tech/personalized-badge/drf-api-logger?period=week&units=none&left_color=black&right_color=orange&left_text=Downloads%20Last%20Week)](https://pepy.tech/project/drf-api-logger)
Expand Down Expand Up @@ -191,9 +191,8 @@ DRF_API_LOGGER_METHODS = ['GET', 'POST', 'DELETE', 'PUT'] # Default to empty li
```

### Want to see the API information in local timezone? (Optional)
You can also identify slow APIs by specifying `DRF_API_LOGGER_TIMEDELTA` in settings.py.
It is going to display the API request time after adding the timedelta specified in the settings.py file.
It won't change the Database timezone.
You can also change the timezone by specifying `DRF_API_LOGGER_TIMEDELTA` in settings.py.
It won't change the Database timezone. It will still remain UTC or the timezone you have defined.
```python
DRF_API_LOGGER_TIMEDELTA = 330 # UTC + 330 Minutes = IST (5:Hours, 30:Minutes ahead from UTC)
# Specify in minutes.
Expand Down
40 changes: 38 additions & 2 deletions drf_api_logger/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,32 @@
from django.conf import settings
from django.contrib import admin
from django.db.models import Count
from django.http import HttpResponse

from drf_api_logger.utils import database_log_enabled

if database_log_enabled():
from drf_api_logger.models import APILogsModel
from django.utils.translation import gettext_lazy as _
import csv


class ExportCsvMixin:
def export_as_csv(self, request, queryset):
meta = self.model._meta
field_names = [field.name for field in meta.fields]

response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename={}.csv'.format(meta)
writer = csv.writer(response)

writer.writerow(field_names)
for obj in queryset:
row = writer.writerow([getattr(obj, field) for field in field_names])

return response

export_as_csv.short_description = "Export Selected"

class SlowAPIsFilter(admin.SimpleListFilter):
title = _('API Performance')
Expand Down Expand Up @@ -54,7 +75,9 @@ def queryset(self, request, queryset):

return queryset

class APILogsAdmin(admin.ModelAdmin):
class APILogsAdmin(admin.ModelAdmin, ExportCsvMixin):

actions = ["export_as_csv"]

def __init__(self, model, admin_site):
super().__init__(model, admin_site)
Expand Down Expand Up @@ -83,6 +106,7 @@ def added_on_time(self, obj):
exclude = ('added_on',)

change_list_template = 'charts_change_list.html'
change_form_template = 'change_form.html'
date_hierarchy = 'added_on'

def changelist_view(self, request, extra_context=None):
Expand All @@ -108,7 +132,19 @@ def changelist_view(self, request, extra_context=None):
return response

def get_queryset(self, request):
return super(APILogsAdmin, self).get_queryset(request)
drf_api_logger_default_database = 'default'
if hasattr(settings, 'DRF_API_LOGGER_DEFAULT_DATABASE'):
drf_api_logger_default_database = settings.DRF_API_LOGGER_DEFAULT_DATABASE
return super(APILogsAdmin, self).get_queryset(request).using(drf_api_logger_default_database)

def changeform_view(self, request, object_id=None, form_url='', extra_context=None):
if request.GET.get('export', False):
drf_api_logger_default_database = 'default'
if hasattr(settings, 'DRF_API_LOGGER_DEFAULT_DATABASE'):
drf_api_logger_default_database = settings.DRF_API_LOGGER_DEFAULT_DATABASE
export_queryset = self.get_queryset(request).filter(pk=object_id).using(drf_api_logger_default_database)
return self.export_as_csv(request, export_queryset)
return super(APILogsAdmin, self).changeform_view(request, object_id, form_url, extra_context)

def has_add_permission(self, request, obj=None):
return False
Expand Down
8 changes: 8 additions & 0 deletions drf_api_logger/templates/change_form.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{% extends 'admin/change_form.html' %}

{% block submit_buttons_bottom %}
{{ block.super }}
<div class="submit-row">
<a href="?export=true">Export CSV</a>
</div>
{% endblock %}
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def get_long_desc():

setuptools.setup(
name="drf_api_logger",
version="1.0.10",
version="1.1.10",
author="Vishal Anand",
author_email="vishalanandl177@gmail.com",
description="An API Logger for your Django Rest Framework project.",
Expand Down

0 comments on commit 4e8b4c1

Please sign in to comment.