-->
With an Example: How To Create an XML Sitemap Flask Python?

With an Example: How To Create an XML Sitemap Flask Python?

Back to top

Updated by Ashirafu Kibalama on April 19, 2024

Simplifying Website Organization: A Step-by-Step Guide to Creating an XML Sitemap with Flask in Python







#Our sample website:








#Sample Code:



from flask import Flask, render_template, url_for
from datetime import datetime
from xml.etree.ElementTree import Element, SubElement, tostring
from xml.dom import minidom


# OTHER CODES IN BETWEEN

@app.route('/')
def get_all_blog_posts():
result = db.session.execute(db.select(Posts))
posts = result.scalars().all()
return render_template("index.html", all_posts=posts)


@app.route("/post/<int:post_id>")
def show_post(post_id):
post_to_be_shown = db.get_or_404(Posts, post_id)

return render_template("post.html", post=post_to_be_shown)


# OTHER CODES IN BETWEEN

@app.route("/about")
def about():
return render_template("about.html")


@app.route("/contact")
def contact():
return render_template("contact.html")


if __name__ == "__main__":
app.run(debug=False)


Creating an XML sitemap is an effective way to enhance website navigability and search engine discoverability.


We will guide you through creating an XML sitemap using Flask, a popular and flexible Python web framework. 


By the end of this tutorial, you will have acquired the knowledge and tools to seamlessly integrate an XML sitemap into your Flask-powered websites, enhancing the discoverability and accessibility of your web content.


5 Steps To Create an XML Sitemap Flask Python


Step 1) Needed requirements:


For example:



from flask import Flask, render_template, url_for
from datetime import datetime
from xml.etree.ElementTree import Element, SubElement, tostring
from xml.dom import minidom




Step 2) Create a function to calculate the priority score:


# Function to calculate priority based on post content
def calculate_priority(post):
# Example: Calculate priority based on the length of the post body
# Adjust the logic as needed
if len(post.body) < 500:
return "0.65"
elif len(post.body) < 1000:
return "0.75"
else:
return "1.0"



This Python function, calculate_priority(post), determines the priority of a post based on the length of its body text. Here's a breakdown of how it works:

  1. The function takes a post object as input.
  2. It accesses the body attribute of the post object, which presumably contains the text content of the post.
  3. It then compares the length of the post's body text to certain thresholds:
    • If the length is less than 500 characters, it returns a priority value of "0.65".
    • If the length is between 500 and 999 characters, it returns a priority value of "0.75".
    • If the length is 1000 characters or more, it returns a priority value of "1.0".


This function assigns higher priority to posts with longer body texts, with a higher threshold for even longer texts. 


The priority values returned (0.65, 0.75, and 1.0) are arbitrary and could be adjusted based on the application's requirements.


Step 3) Create a function to generate an XML sitemap:



# Function to generate XML sitemap
def generate_sitemap():
# Create the root element
root = Element('urlset', xmlns="http://www.sitemaps.org/schemas/sitemap/0.9")

# List of routes in your Flask application
routes = ['/', '/about', '/contact', ] # Add more routes as needed

# Add specific post URLs
posts = Posts.query.all() # Fetch all posts from the database
for post in posts:
url = SubElement(root, 'url')
loc = SubElement(url, 'loc')
loc.text = url_for('show_post', post_id=post.id, _external=True) # Generates the URL for the post

# Add lastmod element
lastmod = SubElement(url, 'lastmod')
lastmod.text = datetime.now().isoformat()

# Calculate priority dynamically
priority_value = calculate_priority(post)
priority = SubElement(url, 'priority')
priority.text = priority_value

# Loop through each route and create XML elements for them
for route in routes:
url = SubElement(root, 'url')
loc = SubElement(url, 'loc')
loc.text = f"https://pythonexample.online{route}" # Update with your actual domain

# Add lastmod element
lastmod = SubElement(url, 'lastmod')
lastmod.text = datetime.now().isoformat()

# Add priority element (you can set a default priority for routes)
priority = SubElement(url, 'priority')
priority.text = "0.78" # Default priority for routes

# Generate pretty XML
xml_content = minidom.parseString(tostring(root)).toprettyxml(indent=" ")

return xml_content



This Python function, generate_sitemap(), creates an XML sitemap for a web application, typically a Flask application. Here's a breakdown of how it works:

  1. According to the Sitemap Protocol, it begins by creating the XML document's root element, <urlset>. The xmlns attribute specifies the XML namespace.
  2. It defines a list of routes in the Flask application. These paths will be included in the sitemap, and more routes can be added as needed.
  3. It fetches all posts from the database using Posts.query.all(). This assumes there's a Posts model or table in the database.    
  4. For each post, it creates a <url> element with a <loc> child element containing the URL of the post. The URL is generated using url_for('show_post', post_id=post.id, _external=True). The _external=True parameter ensures that absolute URLs are generated.
  5. It adds a <lastmod> element to indicate the last modification time of the post. In this implementation, the current time is the last modification time using datetime.now().isoformat().
  6. It calculates the priority for each post dynamically using the calculate_priority() function, which is assumed to be defined elsewhere in (Step 2)).
  7. It creates a <priority> element for each post and sets its value based on the calculated priority.
  8. It then loops through each route defined in the Flask application and creates <url> elements for them similarly. These route URLs are hard-coded with a default domain (https://pythonexample.online) for demonstration purposes.
  9. It sets a default priority of "0.78" for route URLs.
  10. Finally, it generates a pretty XML representation of the sitemap using minidom.parseString(tostring(root)).toprettyxml(indent=" ") and returns it.

This function effectively generates an XML sitemap that includes a Flask application's posts and routes, URLs, last modification times, and priorities.


Step 4) Create a route to serve the XML sitemap:



# Route to serve the XML sitemap
@app.route('/sitemap.xml')
def sitemap():
xml_content = generate_sitemap()

return render_template('sitemap.xml', xml_content=xml_content)



This code snippet defines a route in a Flask application to serve an XML sitemap. Here's how it works:

  1. @app.route('/sitemap.xml'): This decorator defines a route in the Flask application with the URL path '/sitemap.xml'. When a user visits this URL path '/sitemap.xml', the function immediately below will be executed.
  2. def sitemap(): This function executes when a request is made to '/sitemap.xml'. It doesn't take any parameters.
  3. xml_content = generate_sitemap(): This line calls the generate_sitemap() function, which we discussed earlier. This function generates the XML content of the sitemap.
  4. return render_template('sitemap.xml', xml_content=xml_content): This line renders a template named 'sitemap.xml', passing the generated XML content (xml_content) as a variable to the template. The render_template() function is a Flask function used to render templates. Here, it renders an XML template.

In summary, when a user accesses '/sitemap.xml', Flask will execute the sitemap() function, which generates the XML sitemap content using the generate_sitemap() function and then renders the 'sitemap.xml' template, passing the generated XML content to it. The template will then be sent back as the response to the user's request, effectively serving the XML sitemap.



Step 5) Create the sitemap template:



<!-- sitemap.xml -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title> </title>
</head>
<body>
<pre>{{ xml_content }}</pre>
</body>
</html>




The <pre>{{ xml_content }}</pre>: 

This pre-tag is a preformatted text element which preserves whitespace and line breaks. The {{ xml_content }} is a placeholder for dynamic content generated by the Flask application. 


It's typically replaced with the XML content of the sitemap generated by the Flask route. 


This HTML template wraps XML content within an HTML page. It ensures that the XML sitemap is presented in a readable format to users who access the designated URL for the sitemap, providing a user-friendly interface for viewing its contents.



Conclusion:

Creating an XML sitemap for a Flask app in Python can improve website indexing and SEO. 


Follow these steps to generate a comprehensive sitemap with static routes and dynamic content. 


Leveraging Flask's routing capabilities and Python's XML processing libraries can help developers automate sitemap generation and improve user experience. 


A practical example demonstrates implementing XML sitemaps in Flask apps and optimizing websites for better visibility and user engagement.


"Please review the post and kindly provide your suggestions to help us improve. Your feedback is valuable and highly appreciated. 


"If you need more help, please let me know. I am always here to assist you."


Thank you, and happy coding!"


Related Posts:


How Do I Add or Connect a Flask Python Website To Google Search Console? 


How Do I Add or Connect Google Analytics to a Flask Python Website? 


A Beginner's Complete Guide: Deploy Flask App with SQLite/ PostgreSQL Database on cPanel/ shared hosting 


How To Fix: The Database Is Created Outside Of The Instance Folder Flask Python


With an Example: How To Automatically Add Canonical Links to The Website Flask Python