Commit 81473a67 authored by Filip Štamcar's avatar Filip Štamcar
Browse files

Store generated documents in database

No related merge requests found
Pipeline #9504 failed with stages
in 1 minute and 7 seconds
Showing with 78 additions and 9 deletions
+78 -9
......@@ -16,4 +16,4 @@ PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"]
SEND_EMAIL_CONFIRMATIONS = False
# FIX: this should be looked at at some point
INSTALLED_APPS.remove("rest_registration")
# INSTALLED_APPS.remove("rest_registration")
from django.contrib import admin
from django.contrib import admin, messages
from django.http import HttpResponse
from .models import Document
# Register your models here.
class DocumentAdmin(admin.ModelAdmin):
list_display = ["datetime", "successful"]
fields = ["datetime", "source"]
actions = ["download"]
@admin.action(description="Download rendered document")
def download(self, request, queryset):
if len(queryset) != 1:
messages.error(request, "Exactly one successful document must be selected")
return
if not queryset[0].successful():
messages.error(request, "Only successfully rendered documents can be downloaded")
return
response = HttpResponse(queryset[0].output, content_type="application/pdf")
response["Content-Disposition"] = 'attachment; filename="report.pdf"'
return response
admin.site.register(Document, DocumentAdmin)
# Generated by Django 4.2 on 2023-08-07 14:48
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Document",
fields=[
("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("datetime", models.DateTimeField()),
("source", models.TextField()),
("output", models.BinaryField(null=True)),
],
),
]
from django.db import models
class Document(models.Model):
datetime = models.DateTimeField()
source = models.TextField()
output = models.BinaryField(null=True)
def successful(self):
return self.output is not None
import datetime
import logging
import os
import subprocess
import tempfile
from django.core.exceptions import BadRequest
from django.http import FileResponse
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiResponse, extend_schema
from django.http import HttpResponse
from drf_spectacular.utils import extend_schema
from rest_framework import parsers, viewsets
from rest_framework.decorators import action
from utils.decorators import file_response
from utils.renderers import BinaryRenderer
from .models import Document
logger = logging.getLogger(__name__)
......@@ -32,10 +34,14 @@ class LatexViewSet(viewsets.GenericViewSet):
@action(detail=False, methods=["post"], renderer_classes=[BinaryRenderer])
def generate_pdf(self, request, pk=None):
with tempfile.TemporaryDirectory(prefix="latex-renderer-") as directory:
document = Document(datetime=datetime.datetime.now(tz=datetime.timezone.utc))
try:
# Store uploaded file to temporary directory
with open(os.path.join(directory, "report.tex"), "wb") as source:
source.write(request.FILES.get("file").read())
with open(os.path.join(directory, "report.tex"), "wb") as sourcefile:
source = request.FILES.get("file").read()
document.source = source.decode()
sourcefile.write(source)
except AttributeError as error:
logger.warning(error, exc_info=error)
raise BadRequest("Failed to store uploaded file")
......@@ -44,12 +50,19 @@ class LatexViewSet(viewsets.GenericViewSet):
# Convert TEX to PDF
generate_pdf_report(directory)
except subprocess.CalledProcessError as error:
document.save()
logger.warning(error, exc_info=error)
raise BadRequest("Failed to render uploaded file")
# Return the rendered PDF file
filename = os.path.join(directory, "report.pdf")
response = FileResponse(open(filename, "rb"), content_type="application/pdf")
# Store result in database
with open(filename, "rb") as outputfile:
document.output = outputfile.read()
document.save()
# Return the rendered PDF file
response = HttpResponse(document.output, content_type="application/pdf")
response["Content-Disposition"] = 'attachment; filename="report.pdf"'
return response
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment