У меня есть этот 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