from django.shortcuts import render from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt import json from .elasticSearch import eSearch from rest_framework.decorators import api_view from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa # get the submetted search phrase from the front-end @csrf_exempt def get_input(request): if request.method == "POST": # data is a json object that holds the searched phrase in a key # called phrase data = json.loads(request.body.decode('utf-8')) if data is not None: phrase = data['data']['phrase'] print(phrase) if phrase[0] == '"' and phrase[-1] == '"': phrase = phrase[1:-1] searchResults = eSearch(phrase) return JsonResponse({"message": "Data received", "results":searchResults}) else: #searchResults = cosine_similarity(phrase, title=False) searchResults = eSearch(phrase) return JsonResponse({"message": "Data received", "results":searchResults}) return JsonResponse({"message": "Invalid request"}) @csrf_exempt @api_view(['POST']) def exportPDF(request): if request.method == "POST": filteredResults = request.data['params']['filteredResults'] phrase = request.data['params']['phrase'] template = get_template('export/outputPDF.html') html = template.render({'results': filteredResults, 'phrase': phrase}) #html = template.render() response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="output.pdf"' try: pisa_status = pisa.CreatePDF(html, dest=response) if pisa_status.err: return HttpResponse('We had some errors
' + html + '
') #response['Content-Type'] = 'application/pdf' # Set the Content-Type after generating the PDF print(response) return response except Exception as e: return HttpResponse(f'Error generating PDF: {str(e)}', status=500)