文章内容

2022/4/21 17:25:53,作 者: 黄兵

Flask 如何生成站点地图(sitemap)

最近在使用 Flask 生成站点地图,Flask 有一个可以生成站点地图的扩展,是 Flask-Sitemap,我测试了一下并不是很好用,所以没有采用。

我们看看站点地图的作用:

站点地图是网站开发人员帮助网站搜索结果排名最容易被忽视的工具之一,而以正确的方式创建网站地图将提高您网站的性能。如果您的站点设计正确,您只需几行代码即可生成完整的站点地图。更好的是,当您添加新内容时,它会自动添加到您的站点地图中。

之后只能自己通过手动的方式创建站点地图,首先我们创建一个站点地图的模板,站点地图的要求,可以参考 1,下面是站点地图的模板代码示例:

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
<url>
<loc>{{ base_url }}</loc>
<lastmod>2022-04-21T02:32:42+00:00</lastmod>
<changefreq>daily</changefreq>
</url>
{% for article in articles %}
<url>
<loc>{{ base_url }}/{{ article.category }}/{{ article.url }}</loc>
<lastmod>{{ article.create_time }}</lastmod>
<changefreq>weekly</changefreq>
</url>
{% endfor %}
</urlset>

通过循环文章创建每个 url 元素。

我们继续看一下后端的代码:

@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')

首先是定义了路由,之后使用了一个缓存,获取所有的文章,这个文章多了可能会影响性能,以后如果文章多了,直接将 sitemap.xml 写文件就好了。

当然站点地图也有限制,比如:单个文件的大小必须小于 50 MB,并且单个文件最多只能包含 50,000 个 url。

以上就是关于在 Flask 中如何创建站点地图的全部内容,如果大家有任何疑问,欢迎下面留言。


参考资料:

1、创建和提交站点地图

2、Why You Need a Sitemap and How to Create One with Flask


黄兵个人博客原创。

转载请注明出处:黄兵个人博客 - Flask 如何生成站点地图(sitemap)

分享到:

发表评论

评论列表