Sitemaps are a way to tell Google about pages on your site we might not otherwise discover.
So, This time, intorduce the way of generate sitemap.xml with Flask.
Codes are below:
- app.py
import os
from jinja2 import Environment, FileSystemLoader
@app.route("/sitemap.xml", methods=["GET"])
def sitemap():
"""Generate sitemap.xml"""
articles_qry = Articles.query()\
.filter(Articles.data_status==Articles.POSTED)\
.order(-Articles.postDate)
articles = articles_qry.fetch()
base_dir = os.path.realpath(os.path.dirname(__file__))
# Configure jinja for internal templates
env = Environment(
autoescape=True,
extensions=['jinja2.ext.i18n'],
loader=FileSystemLoader(
os.path.join(base_dir, 'templates')
)
)
url_root = request.url_root[:-1]
sitemap_xml = env.get_template("sitemap_template.xml").render(
mentions=mentions, url_root=url_root)
response= make_response(sitemap_xml)
response.headers["Content-Type"] = "application/xml"
return response
- sitemap_template.xml
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
{% for article in articles %}
<url>
<loc>{{url_root}}/show_blog?id={{article.key.urlsafe()}}</loc>
<lastmod>{{article.updatedate|datetimeformat('%Y-%m-%d')}}</lastmod>
</url>
{% endfor %}
</urlset>
As above, When you are using Jinja2 Template, you can use Jinja2 Custom Filters like datetimeformat.
- custom_filters.py
def datetimeformat(value, format='%A,%B %d,%Y'):
return value.strftime(format)
Now, possible to generate a sitemap.xml.
After deployed application, You need submit it to Google using Google Webmaster Tools.
The way of submitting sitemap.xml is according to Submitting Sitemaps.
Now that Google crawler will schedule crawling your site.:)
Comments
Add Comment