from mimetypes import guess_type from django.contrib.auth.decorators import login_required from django.http.response import HttpResponseNotFound, HttpResponse from django.shortcuts import render from quiz.models import Quiz def quiz_as_file(request, id: int, filetype: str): try: assert filetype in ('pdf', 'csv', 'zip') quiz = Quiz.objects.get(id=int(id)) except AssertionError: return HttpResponseNotFound('Wrong filetype') except Quiz.DoesNotExist: return HttpResponseNotFound('Not found') mimetype, __ = guess_type(f'/tmp/a.{filetype}') _path = getattr(quiz, f'to_{filetype}')() with open(_path, 'rb') as _content: response = HttpResponse(content_type=mimetype) response['Content-Disposition'] = f'attachment; filename=quiz.{id}.{filetype}' response.write(_content.read()) return response @login_required(login_url='/admin/login/') def quiz_as_table(request, id): try: quiz = Quiz.objects.get(id=int(id)) except Quiz.DoesNotExist: return HttpResponseNotFound('Not found') return render(request, 'quiz/as_table.html', quiz.to_view()) @login_required(login_url='/admin/login/') def quiz_as_pdf(request, id): return quiz_as_file(request, id, 'pdf') @login_required(login_url='/admin/login/') def quiz_as_csv(request, id): return quiz_as_file(request, id, 'csv') @login_required(login_url='/admin/login/') def quiz_as_zip(request, id): return quiz_as_file(request, id, 'zip')