Skip to content

Instantly share code, notes, and snippets.

@Rigil-Kent Rigil-Kent/routes.py
Last active Oct 28, 2019

Embed
What would you like to do?
flask-sitemapxml
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 = datetime.now - 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(['https://yourdomain.com' + rule.rule, ten_days_ago])
# get dynamic routes for blog
posts = Post.query.order_by(Post.timestamp).all()
for post in posts:
url = "https://yourdomain.com" + url_for('blog_post', slug=post.slug)
modified_time = post.timestamp.date().isoformat()
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="http://www.sitemaps.org/schemas/sitemap/0.9">
{% for page in pages %}
<url>
<loc>{{page[0]|safe}}</loc>
<lastmod>{{page[1]}}</lastmod>
</url>
{% endfor %}
</urlset>
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.