Last active
May 31, 2020 03:47
-
-
Save Rigil-Kent/a7eb513cac39f0cedfe257567971322c to your computer and use it in GitHub Desktop.
flask-sitemapxml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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