Представление Django Rest Framework для возврата созданных файлов - PullRequest
0 голосов
/ 19 декабря 2018

У меня есть ViewSet в DRJ , который создает на сервере несколько файлов с python-docx , и я хочу, чтобы это представление возвращало такие файлы.

Это код моего представления:

class RoomingWordView(viewsets.ViewSet):
    def list(self, request, *args, **kwargs):
        from ReportsManagerApp.controllers import RoomingReportController

        start_date = request.query_params['start_date']
        end_date = request.query_params['end_date']
        confirmed = request.query_params.get('confirmed', None)

        try:
            agencies = request.query_params['agencies'].split(",")
        except:
            agencies = None

        try:
            cities = request.query_params['cities'].split(",")
        except:
            cities = None

        try:
            hotels = request.query_params['hotels'].split(",")
        except:
            hotels = None

        rooming_report_controller = RoomingReportController(start_date, end_date, confirmed, agencies, hotels, cities)
        context = rooming_report_controller.get_context()

        documents_to_return =[]
        for hotel, bookings in context['hotels'].items():
            documents_to_return.append(self.get_hotel_document(start_date, end_date, confirmed, hotel, bookings))

        return Response(documents_to_return)

    def get_hotel_document(self, start_date, end_date, confirmed, hotel, bookings):
        from docx import Document
        from docx.shared import Inches, Pt

        document = Document()

        section = document.sections[-1]
        section.left_margin = Inches(0.5)
        section.right_margin = Inches(0.5)

        style = document.styles['Normal']
        font = style.font
        font.name ='Arial'
        font.size = Pt(10)

        document.add_heading("EUROAMERICA TTOO INC")
        if confirmed:
            document.add_paragraph("ROOMING LIST DEL 01-12-2018 AL 31-01-2019 INCLUYE RESERVAS CONFIRMADAS")
        else:
            document.add_paragraph("ROOMING LIST DEL 01-12-2018 AL 31-01-2019")
        document.add_paragraph("Hotel: {}".format(hotel))

        table = document.add_table(rows=len(bookings), cols=10)
        hdr_cells = table.rows[0].cells
        hdr_cells[0].text = 'Booking'
        hdr_cells[1].text = 'Reservado a'
        hdr_cells[2].text = '# Pax'
        hdr_cells[3].text = 'Agencia'
        hdr_cells[4].text = 'Habs'
        hdr_cells[5].text = 'Hab./Plan'
        hdr_cells[6].text = 'Entrada'
        hdr_cells[7].text = 'Salida'
        hdr_cells[8].text = 'Confirmación'
        hdr_cells[9].text = 'Producción'

        for cell in table.rows[0].cells:
            paragraphs = cell.paragraphs
            for paragraph in paragraphs:
                for run in paragraph.runs:
                    run.underline = True

        for booking in bookings['bookings']:
            row_cells = table.add_row().cells
            row_cells[0].text = booking['booking']
            row_cells[1].text = "\n".join(booking['people'])
            row_cells[2].text = booking['pax']
            row_cells[3].text = booking['agency']
            row_cells[4].text = booking['rooms']
            row_cells[5].text = "{}\n{}".format(booking['room_type'], booking['plan_type'])
            row_cells[6].text = booking['check_in']
            row_cells[7].text = booking['check_out']
            row_cells[8].text = booking['confirmation']
            row_cells[9].text = str(booking['production'])

        for row in table.rows:
            for cell in row.cells:
                paragraphs = cell.paragraphs
                for paragraph in paragraphs:
                    for run in paragraph.runs:
                        font = run.font
                        font.size = Pt(8)

        document.save("Rooming {} {}-{}.docx".format(hotel, start_date, end_date))

        return document

Я хочу, чтобы представление возвращало файлы как таковые, а не ссылку на файлы, но я получаю ошибку Object of type 'Document' is not JSON serializable, ноЯ не могу найти, как поручить представлению вернуть файлы.

...