Skip to content

Instantly share code, notes, and snippets.

@mandarvaze
Created December 15, 2020 16:50
Show Gist options
  • Save mandarvaze/090c6975e8be0f594c0f28fb86e7cd18 to your computer and use it in GitHub Desktop.
Save mandarvaze/090c6975e8be0f594c0f28fb86e7cd18 to your computer and use it in GitHub Desktop.
Generate Sitemap based on python dict
import os
from datetime import datetime
from jinja2 import Template
base_url = 'http://example.com'
# Following can go into settings.py
sitemap_dict = {
'urls': [
{
'path': '/sign_up',
# it doesn't really change monthly, but yearly may be too much
# Valid values are https://www.sitemaps.org/protocol.html#changefreqdef
'changefreq': 'monthly',
'priority': '1.0' # We always want this
},
{
'path': '/terms',
# it doesn't really change monthly, but yearly may be too much
# Valid values are https://www.sitemaps.org/protocol.html#changefreqdef
'changefreq': 'monthly',
'priority': '1.0' # We always want this
},
{
'path': '/privacy',
# it doesn't really change monthly, but yearly may be too much
# Valid values are https://www.sitemaps.org/protocol.html#changefreqdef
'changefreq': 'monthly',
'priority': '1.0' # We always want this
},
]
}
sitemap_template = '''<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
{% for u in urls %}
<url>
<loc>{{ get_full_url(u['path']) }}</loc>
<lastmod>{{u['lastmod']}}</lastmod>
<changefreq>{{u['changefreq']}}</changefreq>
<priority>{{u['priority']}}</priority>
</url>
{% endfor %}
</urlset>'''
template = Template(sitemap_template)
# Fill the Sitemap Template and Write File
for url in sitemap_dict['urls']:
url['lastmod'] = datetime.now().isoformat(timespec='seconds')
# Render each row / column in the sitemap
sitemap_output = template.render(
urls=sitemap_dict['urls'],
get_full_url=lambda x: f'{base_url}{x}')
print(sitemap_output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment