Плохой запрос с остальной частью фреймворка JavaScript запрашивает PDF-файл - PullRequest
0 голосов
/ 21 июня 2019

У меня есть этот javascript (на самом деле coffeescript, но в конце концов это одно и то же), и у меня есть этот код Python, который получает код и возвращает PDF, однако. Он получает неправильный код запроса, и pdf не работает, я знаю, что сервер правильно получает строку html, и pdf-код работает, потому что тот же рендер, что и рендеринг таблицы. Итак, я предполагаю, что проблема с JavaScript. Но в чем может быть проблема?

Я в основном пытался переписать код и пытался преобразовать его в запрос get. Тем не менее, HTML-код, который я посылаю, легко взорвал лимит URL. То, чего я не знал, существовало.

Вот код Python на сервере рендера:

class CustomPdfResponse(CustomHtmlRender):
    media_type = "application/pdf"
    format = "pdf"

    def get_pdf(self, html_string):
        url = 'http://localhost:9288/'
        pdf_name = "test.pdf"
        header = {"pdf-options": "landscape"}

        return requests.post(url + pdf_name, data=html_string, headers=header)

    def render(self, data, accepted_media_type=None, renderer_context=None, **kwargs):
        graphics = renderer_context['request'].query_params.get("graphics", False)
        title = renderer_context['request'].query_params.get("title").strip()
        title = title.replace("\n", "").encode('ascii', 'xmlcharrefreplace').decode("utf-8")

        filter_context = renderer_context['request'].query_params.get("date_filter").strip()
        filter_context = filter_context.replace("\n", "").encode('ascii', 'xmlcharrefreplace')
        filter_context = filter_context.decode("utf-8")

        if not graphics:
            if not isinstance(data, DataFrame):
                data = data["results"]

            table, is_multi_index = self.get_table(data, renderer_context, without_perms = True)
            table = str(table.replace("\n", "").encode('ascii', 'xmlcharrefreplace').decode("utf-8")),
        else:
            graphics = renderer_context['request'].data.get("graphics")
            is_multi_index = False

        render_context = {
            'table': table if not graphics else False,
            'graphic': graphics,
            'title': title,
            'filter': filter_context,
            'is_multi_index': is_multi_index
        }

        html_string = render_to_string("pdf_template.html", context=render_context)
        print(html_string)

        return HttpResponse(self.get_pdf(html_string), content_type=accepted_media_type, status=200)

и вот файл coffeescript:

params =
    "graphics": "<h1>test</h1>"

d3.xhr(pdf_url.toString())
    .header("X-CSRFToken", document.csrf_cookie)
    .header("Content-Type", "application/json")
    .header("Accept", "application/pdf")
    .post JSON.stringify(params), (error, pdf_data) ->
        if error
            console.log(error)
        else
            a = document.createElement("a")
            file = new Blob [pdf_data.response], "type": "application/pdf"
            url = URL.createObjectURL(file)
            a.href = url
            a.download = "#{params['title']} #{params['filter']}.pdf"
            document.body.appendChild(a)
            a.click()
            setTimeout -
                document.body.removeChild(a)
                window.URL.revokeObjectURL(url)
            , 0

1 Ответ

0 голосов
/ 23 июня 2019

Я просто сделал новый взгляд на графику.Я до сих пор понятия не имел, в чем проблема, но как только я сделал это представление:

class PDFExport(View):
    def post(self, request):
        params = json.loads(request.body)
        graphics = params.get("graphics", False)
        title = params.get("title", False)
        filter_context = params.get("filter", False)
        is_debug = params.get("is_debug", False)

        if not graphics:
            raise ValueError("Graphics is not defined in the request body")

        exported_pdf = export_str_to_pdf(
            graphics,
            title,
            filter_context,
            is_debug=is_debug,
            convert_to_base64=True
        )
        return HttpResponse(exported_pdf)

С помощью этого кода для создания PDF из шаблона:

def export_str_to_pdf(input_str, title, filter_context, is_debug=False, convert_to_base64=False, **kwargs):
    with open(staticfiles_storage.path('css/pdf.css')) as pdf_css_content:
        pdf_css = pdf_css_content.read()

    with open(staticfiles_storage.path('css/nvd3.css')) as graphic_css_content:
        graphic_css = graphic_css_content.read()

    is_multi_index = kwargs.pop("is_multi_index", False)

    input_str = input_str.strip()
    input_str = input_str.replace("\n", "").encode('ascii', 'xmlcharrefreplace').decode("utf-8")

    if title:
        title = title.strip()
        title = title.replace("\n", "").encode('ascii', 'xmlcharrefreplace').decode("utf-8")

    if filter_context:
        filter_context = filter_context.strip()
        filter_context = filter_context.replace("\n", "").encode('ascii', 'xmlcharrefreplace')
        filter_context = filter_context.decode("utf-8")

    render_context = {
        'pdf_css': pdf_css,
        'graphic_css': graphic_css,
        'input_str': input_str,
        'title': title,
        'filter': filter_context,
        'is_multi_index': is_multi_index
    }
    html_string = render_to_string("pdf_template.html", context=render_context)
    if is_debug:
        returned_pdf = html_string
    else:
        returned_pdf = get_pdf(html_string)

    return base64.b64encode(returned_pdf) if convert_to_base64 and not is_debug else returned_pdf

Все работает

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...