Atom Login Admin

Above the clouds

Generate sitemap.xml with Flask.

written on Friday,January 25,2013

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:

import os
from jinja2 import Environment, FileSystemLoader

@app.route("/sitemap.xml", methods=["GET"])
def sitemap():
  """Generate sitemap.xml"""
  articles_qry = Articles.query()\
  articles = articles_qry.fetch()
  base_dir = os.path.realpath(os.path.dirname(__file__))
  # Configure jinja for internal templates
  env = Environment(
        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="">
    {% for article in articles %}
        {% endfor %}

As above, When you are using Jinja2 Template, you can use Jinja2 Custom Filters like datetimeformat.

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.:)


Add Comment

This entry was tagged #Flask #Jinja2 #SEO