Skip to content

Instantly share code, notes, and snippets.

@Rigil-Kent Rigil-Kent/

Last active May 31, 2020
What would you like to do?
from datetime import datetime, timedelta
from flask import current_app, make_response, render_template
from app.models import Post
@app.route('/sitemap.xml', methods=['GET'])
def sitemap():
'''Generate sitemap.xml iterating over static and dynamic routes to make a list of urls and date modified'''
pages = []
ten_days_ago = - timedelta(days=10)
# get static routes
for rule in current_app.url_map.iter_rules():
# check for a 'GET' request and that the length of arguments is = 0 and if you have an admin area that the rule does not start with '/admin'
if 'GET' in rule.methods and len(rule.arguments) == 0 and not rule.rule.startswith('/admin'):
pages.append(['' + rule.rule, ten_days_ago])
# get dynamic routes for blog
posts = Post.query.order_by(Post.timestamp).all()
for post in posts:
url = "" + url_for('blog_post', slug=post.slug)
modified_time =
pages.append([url, modified_time])
sitemap_template = render_template('sitemap_template.xml', pages=pages)
response = make_response(sitemap_template)
response.headers["Content-Type"] = "application/xml"
return response
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="">
{% for page in pages %}
{% endfor %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.