
Flask应用:高效保存render_template渲染页面到服务器
在分布式测试环境中,将测试结果页面直接保存至服务器,方便后续分析和查阅。本文将详细介绍如何利用Flask框架,将render_template渲染的页面保存到服务器。
实现页面保存的关键在于Flask的response对象。具体步骤如下:
-
页面渲染: 首先,使用
render_template函数渲染HTML页面:<code class="python">html = render_template('test_results.html')</code> -
创建response对象: 将渲染后的HTML内容编码为UTF-8,并创建
response对象:<code class="python">response = make_response(html.encode('utf-8'))</code> -
设置响应头: 设置响应头,指定文件名和MIME类型,确保浏览器正确处理下载:
<code class="python">filename = 'test_results.html' response.headers['Content-Disposition'] = f'attachment; filename="{filename}"' response.mimetype = 'text/html'</code> -
返回response对象: 返回
response对象,触发浏览器下载:<code class="python">return response</code>
通过以上步骤,渲染后的页面将以附件形式下载,并保存到服务器指定位置。 filename和mimetype可根据实际页面内容进行调整。
<code><!-- 此处应显示保存的页面内容,但由于内容依赖于test_results.html模板,此处无法预知 --></code>










