2024-01-29 20:18:11 -03:00
|
|
|
|
|
|
|
from rest_framework import viewsets
|
|
|
|
from rest_framework.decorators import action
|
|
|
|
from django_filters.rest_framework import DjangoFilterBackend
|
2024-02-01 02:41:33 -03:00
|
|
|
from django.core.files.storage import FileSystemStorage
|
|
|
|
from django.http import FileResponse, HttpResponse
|
|
|
|
from api import models , serializers
|
|
|
|
from decouple import config
|
2024-02-01 03:18:02 -03:00
|
|
|
import os
|
2024-02-01 02:41:33 -03:00
|
|
|
import logging
|
2024-01-29 20:18:11 -03:00
|
|
|
|
|
|
|
class GtfsArchivoViewSet(viewsets.ModelViewSet):
|
|
|
|
queryset = models.GtfsArchivo.objects.all()
|
|
|
|
serializer_class = serializers.GtfsArchivoSerializer
|
|
|
|
filter_backends = [DjangoFilterBackend]
|
2024-01-29 22:20:08 -03:00
|
|
|
filterset_fields = ['id_gtfs', 'id_red', 'archivo','valid_from','created','usuario','vigente','status']
|
2024-01-29 20:18:11 -03:00
|
|
|
|
|
|
|
|
|
|
|
def create(self, request, *args, **kwargs):
|
2024-02-14 23:12:58 -03:00
|
|
|
fs = FileSystemStorage(location = config('GTFS_UPLOADS','/tmp'))
|
2024-02-01 02:41:33 -03:00
|
|
|
|
2024-02-01 03:18:02 -03:00
|
|
|
fileUp = fs.save(request.data['archivo'], request.data['binario'])
|
2024-02-01 02:41:33 -03:00
|
|
|
request.data['ruta_archivo'] = fileUp
|
|
|
|
|
|
|
|
return super().create(request, *args, **kwargs)
|
|
|
|
|
|
|
|
@action(detail=False, methods=['get'])
|
|
|
|
def download(self, request, *args, **kwargs):
|
|
|
|
try:
|
|
|
|
id = request.GET['id']
|
|
|
|
registro = models.GtfsArchivo.objects.filter(id_gtfs = id).first()
|
|
|
|
|
|
|
|
folder = config('GTFS_UPLOADS','/tmp')
|
|
|
|
file_location = os.path.join(folder, registro.ruta_archivo)
|
2024-02-01 03:18:02 -03:00
|
|
|
|
2024-02-01 02:41:33 -03:00
|
|
|
archivo = open(file_location, 'rb')
|
|
|
|
response = FileResponse(archivo)
|
|
|
|
response['Access-Control-Expose-Headers'] = 'Content-Disposition'
|
|
|
|
response['Content-Type'] = 'application/zip'
|
|
|
|
response['Content-Disposition'] = f'attachment; filename="{registro.archivo}"'
|
|
|
|
return response
|
|
|
|
except Exception as err:
|
|
|
|
logging.error({ 'error': err })
|
|
|
|
return HttpResponse('Error al descargar archivo', status=500)
|