forked from TDTP/admin_transporte_backend
85 lines
3.1 KiB
Python
Executable File
85 lines
3.1 KiB
Python
Executable File
from rest_framework import viewsets
|
|
from rest_framework.decorators import action
|
|
from api import models, serializers
|
|
from django.http import HttpResponse, FileResponse
|
|
from django.core.files.storage import FileSystemStorage
|
|
from pathlib import Path
|
|
from decouple import config
|
|
import os
|
|
import mimetypes
|
|
import logging
|
|
|
|
class PersonaViewSet(viewsets.ModelViewSet):
|
|
queryset = models.Persona.objects.all()
|
|
serializer_class = serializers.PersonaSerializer
|
|
|
|
def destroy(self, request, pk=None):
|
|
return HttpResponse('No permitido eliminar', status=405)
|
|
|
|
def create(self, request):
|
|
try:
|
|
fs = FileSystemStorage(location = config('PHOTOS_UPLOADS','/tmp'))
|
|
fs.save(request.data['photo'], request.data['photo'])
|
|
|
|
return super().create(request)
|
|
except Exception as e:
|
|
if e.detail['rut']:
|
|
return HttpResponse(e.detail['rut'][0], status=400)
|
|
return HttpResponse(e, status=400)
|
|
|
|
def partial_update(self, request, pk=None):
|
|
try:
|
|
# indicar el nombre con que se guardara el archivo
|
|
archivo = request.data['photo']
|
|
extension = Path(archivo.name).suffix
|
|
nombre_archivo = f'{pk}{extension}'
|
|
|
|
# guardar el archivo en la carpeta
|
|
fs = FileSystemStorage(location = config('PHOTOS_UPLOADS','/tmp'))
|
|
|
|
# Sobrescribir el archivo si ya existe
|
|
if fs.exists(nombre_archivo):
|
|
fs.delete(nombre_archivo)
|
|
|
|
fs.save(nombre_archivo, archivo)
|
|
|
|
# proceder con guardar registro
|
|
return super().partial_update(request, pk)
|
|
except Exception as e:
|
|
return HttpResponse(e, status=400)
|
|
|
|
|
|
|
|
@action(detail=False, methods=['get'])
|
|
def photo(self, request, *args, **kwargs):
|
|
file_location = None
|
|
try:
|
|
rut = request.GET['id']
|
|
folder = config('PHOTOS_UPLOADS','/tmp')
|
|
|
|
file_location = os.path.join(folder, 'desconocido.jpg')
|
|
file_query = os.path.join(folder, f'{rut}.png')
|
|
if os.path.isfile(file_query):
|
|
file_location = file_query
|
|
else:
|
|
file_query = os.path.join(folder, f'{rut}.jpg')
|
|
if os.path.isfile(file_query):
|
|
file_location = file_query
|
|
else:
|
|
file_query = os.path.join(folder, f'{rut}.jpeg')
|
|
if os.path.isfile(file_query):
|
|
file_location = file_query
|
|
|
|
tipo_mime = mimetypes.guess_type(file_location)[0]
|
|
nombre_archivo = os.path.basename(file_location)
|
|
|
|
archivo = open(file_location, 'rb')
|
|
response = FileResponse(archivo)
|
|
response['Access-Control-Expose-Headers'] = 'Content-Disposition'
|
|
response['Content-Type'] = tipo_mime
|
|
response['Content-Disposition'] = f'inline; filename="{nombre_archivo}"'
|
|
return response
|
|
except Exception as err:
|
|
logging.error({ 'error': err, 'file_location': file_location })
|
|
return HttpResponse('Error al descargar archivo', status=500)
|