Python 使用Flask在一个请求中下载文件和渲染模板
在我的应用程序中,我呈现一个PDF文件,并将其作为响应传回。为此,我使用了flask_weasyprint的Python 使用Flask在一个请求中下载文件和渲染模板,python,flask,request,response,Python,Flask,Request,Response,在我的应用程序中,我呈现一个PDF文件,并将其作为响应传回。为此,我使用了flask_weasyprint的render_pdf,它正好做到了这一点: def render_pdf(html, stylesheets=None, download_filename=None): if not hasattr(html, 'write_pdf'): html = HTML(html) pdf = html.write_pdf(stylesheets=styleshe
render_pdf
,它正好做到了这一点:
def render_pdf(html, stylesheets=None, download_filename=None):
if not hasattr(html, 'write_pdf'):
html = HTML(html)
pdf = html.write_pdf(stylesheets=stylesheets)
response = current_app.response_class(pdf, mimetype='application/pdf')
if download_filename:
response.headers.add('Content-Disposition', 'attachment', filename=download_filename)
return response
我现在需要呈现一个模板+返回呈现的pdf作为下载。差不多
@app.route("/view")
def view() :
resp1 = render_pdf(HTML(string="<p>Render me!</p>"), download_filename = "test.pdf")
resp2 = render_template("test.html")
return resp1, resp2
@app.route(“/view”)
def view():
resp1=render_pdf(HTML(string=“render me!”),下载_filename=“test.pdf”)
resp2=render_模板(“test.html”)
返回resp1,resp2
有没有办法做到这一点?有什么解决方法吗?我不确定这在后端是否可以解决,您希望在一个请求之后发送两个http响应。有可能吗?(我真的不知道)客户不应该做出两个回答吗?(javascript) 一个选项是,在render_模板调用中返回。 也许是这样的?(未经测试): 或者只使用window.location.assign()函数生成第二个请求 或者将数据base64编码在href属性中
fileData = new Blob([pdf_data_here], { type: 'application/pdf' });
fileUrl = URL.createObjectURL(fileData);
window.location.assign(fileUrl);