arangda 浏览43次 2020-02-10

flask-sitemap生成sitemap.xml

flask-sitemap是生成sitemap的flask扩展,官方文档地址【点击查看】

pipenv install flask-sitemap

需求

Flask-Sitemap需要下列依赖:

  • Flask
  • blinker
  • six

Flask-Sitemap需要python的版本 2.6, 2.7 or 3.3+

初始化flask-sitemap

from flask import Flask
from flask_sitemap import Sitemap
app = Flask('myapp')
sitemap = Sitemap(app=app)

又或者使用工厂模式:

app = Flask('myapp')
sitemap = Sitemap()
sitemap.init_app(app)

然后在routes.py路由文件中如下应用:

@sitemap.register_generator
def sitemap():
    posts = Post.query.all()
    categories = Category.query.all()
    import datetime
    now = datetime.datetime.now()
    yield 'main.home',{},now.strftime('%Y-%m-%dT%H:%M:%S'),'always',1.0
    for category in categories:
        yield 'posts.show_category',{'category_name':category.english_name},now.strftime('%Y-%m-%dT%H:%M:%S'),'always',0.9

    for post in posts:
        #posts.post是文章视图的endpoint,后面是其参数
        yield 'posts.post',{'path':post_url(post)}

打开http://www.arangda.com/sitemap.xml, 显示如下:

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" 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>http://www.arangda.com/</loc>
<lastmod>2020-02-10T13:41:23</lastmod>
<changefreq>always</changefreq>
<priority>1.0</priority>
</url>
<url>
<loc>http://www.arangda.com/python</loc>
<lastmod>2020-02-10T13:41:23</lastmod>
<changefreq>always</changefreq>
<priority>0.9</priority>
</url>
<url>
<loc>
http://www.arangda.com/python/2020/pip-is-configured-with-locations-that-require-tls-ssl-however-the-ssl-module-in-python-is-not-availa
</loc>
<lastmod>2020-02-08T02:30:43</lastmod>
<changefreq>monthly</changefreq>
<priority>0.8</priority>
</url>
</urlset>

上线后/sitemap.xml不能打开了,因为我设置了SERVER_NAME和301跳转到www子域名,而看flask-sitemap源码,其扩展注册蓝图时没有指定subdomain,将subdomain也设置为'www'后可以正常打开了。代码如下:

app.register_blueprint(
    self.blueprint,
    url_prefix=app.config.get('SITEMAP_BLUEPRINT_URL_PREFIX'),
    subdomain='www' #添加此行
)

如果有改进的地方,欢迎留言指正

0 条评论 最新

还没有评论哦.