IDDRS_API/search_tfidf/views.py

60 lines
2.2 KiB
Python
Raw Permalink Normal View History

2023-05-12 11:41:17 +00:00
from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
2023-11-20 14:31:13 +00:00
from .elasticSearch import eSearch
2023-07-31 07:58:36 +00:00
from rest_framework.decorators import api_view
from django.http import HttpResponse
from django.template.loader import get_template
from xhtml2pdf import pisa
2023-05-12 11:41:17 +00:00
# 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]
2023-11-21 14:20:57 +00:00
searchResults = eSearch(phrase)
2023-05-12 11:41:17 +00:00
return JsonResponse({"message": "Data received", "results":searchResults})
else:
2023-11-20 14:31:13 +00:00
#searchResults = cosine_similarity(phrase, title=False)
searchResults = eSearch(phrase)
2023-05-12 11:41:17 +00:00
return JsonResponse({"message": "Data received", "results":searchResults})
2023-07-31 07:58:36 +00:00
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 <pre>' + html + '</pre>')
#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)