文章内容

2022/4/21 11:29:04,作 者: 黄兵

Flask 如何发送 xml 文档

最近使用 Flask 生成站点地图,站点地图一般是 xml 文件,但是使用模板生成的发送的时候却是 html 页面,为了解决这个问题,使用 flask Response 来定义发送的文件类型,示例代码如下:

from flask import render_template, current_app, Response

@main.route('/sitemap.xml')
@lru_cache(maxsize=512)
def site_map():
    articles = Article.query.order_by(Article.create_time.desc()).all()
    articles_info = []
    for item in articles:
        query_category = Category.query.filter_by(id=item.category_id).first()
        articles_info.append({'category': query_category.link_text, 'url': item.link_text,
                              'create_time': item.create_time.date()})
    sitemap_template = render_template('sitemap/sitemap_template.xml', articles=articles_info,
                                       base_url=current_app.config['ORIGINAL_URL'])
    return Response(sitemap_template, mimetype='application/xml')

实际的 Content-Type 基于 mimetype 参数和字符集(默认为 UTF-8)。

了解更多信息,可以查看:响应(和请求)对象记录的文档


参考资料:

1、Python Flask, how to set content type


黄兵个人博客原创。

转载请注明出处:黄兵个人博客 - Flask 如何发送 xml 文档

分享到:

发表评论

评论列表