Skip to content

Commit

Permalink
serializes edge data as csv and json (#260)
Browse files Browse the repository at this point in the history
  • Loading branch information
csae8092 authored Nov 25, 2024
1 parent 1257273 commit ec9dc70
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
7 changes: 7 additions & 0 deletions network/templates/network/list_view.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,13 @@
<h1 class="display-1 text-center">
<i class="bi bi-share"> Beziehungen</i>
</h1>
<div class="text-center">
<h2>Download</h2>
<div class="btn-group" role="group" class="text-end">
<a type="button" class="btn btn-outline-primary" href="{% url 'network:data' %}{% querystring %}&format=csv">CSV</a>
<a type="button" class="btn btn-outline-primary" href="{% url 'network:data' %}{% querystring %}&format=json">JSON</a>
</div>
</div>

<div class="row pt-4">
<div class="col-md-4" id="searchpane">
Expand Down
3 changes: 2 additions & 1 deletion network/urls.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from django.urls import path
from network.views import EdgeListViews
from network.views import EdgeListViews, network_data


app_name = "network"
urlpatterns = [
path("edges/", EdgeListViews.as_view(), name="edges_browse"),
path("csv/", network_data, name="data"),
]
33 changes: 33 additions & 0 deletions network/views.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
import pandas as pd
import json
from django.http import HttpResponse, JsonResponse


from browsing.browsing_utils import (
GenericListView,
)
Expand All @@ -21,3 +26,31 @@ class EdgeListViews(GenericListView):
]
enable_merge = False
template_name = "network/list_view.html"


def network_data(request):
values_list = [x.name for x in Edge._meta.get_fields()]
qs = EdgeListFilter(request.GET, queryset=Edge.objects.all()).qs
items = list(qs.values_list(*values_list))
df = pd.DataFrame(items, columns=values_list)
response = HttpResponse(
content_type="text/csv",
)
format = request.GET.get("format", "csv")
if format not in ["csv", "json"]:
format = "csv"
if format == "csv":
response = HttpResponse(
content_type="text/csv",
headers={"Content-Disposition": 'attachment; filename="relations.csv"'},
)
df.to_csv(response, index=False)
else:
df = df.set_index("edge_id")
df["start_date"] = pd.to_datetime(df["start_date"], errors="coerce")
df["end_date"] = pd.to_datetime(df["end_date"], errors="coerce")
df["start_date"] = df["start_date"].dt.strftime("%Y-%m-%d").fillna("")
df["end_date"] = df["end_date"].dt.strftime("%Y-%m-%d").fillna("")
out = df.to_json(orient="index", force_ascii=False)
response = JsonResponse(json.loads(out))
return response

0 comments on commit ec9dc70

Please sign in to comment.