Flask Sitemapper is a small Python 3 package that generates XML sitemaps for Flask applications.

Overview

Flask Sitemapper

Flask Sitemapper is a small Python 3 package that generates XML sitemaps for Flask applications. This allows you to create a nice and fully functional sitemap for your project with very minimal code, as demonstrated below. It is compatible with Flask blueprints.

Requirements

  • Python3
  • Flask
  • Jinja2

Installation

pip install flask-sitemapper

Usage

Initialising Flask Sitemapper

The sitemapper must be initialised with the app instance as shown below.

Flask Sitemapper requires SERVER_NAME to be specified in the Flask configuration.

By default, HTTPS will be used for all URLs in the sitemap. To change this, specify https=False when initialising the sitemapper.

import flask
from flask_sitemapper import Sitemapper

app = flask.Flask("test_app")

app.config["SERVER_NAME"] = "127.0.0.1:5000"

sitemapper = Sitemapper(app)

If you are using Flask blueprints, you can either list all URLs in a single sitemap by importing the sitemapper instance to your other files, or create multiple sitemaps for each blueprint by defining a sitemapper instance for each.

Adding URLs to the sitemap

Decorators are added to route functions to include their URLs in the sitemap. These must be included above the Flask decorators.

# Define the homepage route and include it in the sitemap
@sitemapper.include()
@app.route("/")
def r_home():
    return flask.render_template("index.html")

You can pass arguments to the decorator to include additional information in the sitemap. Whatever arguments you provide will be included in the URL entry as-is.

@sitemapper.include(
    lastmod = "2022-02-08",
    changefreq = "monthly",
    priority = 1.0,
)
@app.route("/about")
def r_about():
    return flask.render_template("about.html")

This example would appear in the sitemap as:

<url>
  <loc>https://127.0.0.1:5000/aboutloc>
  <lastmod>2022-02-08lastmod>
  <changefreq>monthlychangefreq>
  <priority>1.0priority>
url>

For routes where multiple URL paths are defined, the sitemap will only include the last path.

Store Page"">
@sitemapper.include()
@app.route("/shop")  # This won't be included
@app.route("/buy")  # This won't be included
@app.route("/store")  # This will be included
def r_store():
    return "

Store Page

"

Generating and serving the sitemap

To serve your sitemap, you must define a route function that returns sitemapper.generate(). Your sitemap will then be avaliable at the URL(s) you specify.

This route should be defined after all routes that are included in the sitemap.

@app.route("/sitemap.xml")
def r_sitemap():
    return sitemapper.generate()

The sitemap generated using these examples would look like this:

https://127.0.0.1:5000/ https://127.0.0.1:5000/about 2022-02-08 monthly 1.0 https://127.0.0.1:5000/store ">
xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"...>
  <url>
    <loc>https://127.0.0.1:5000/loc>
  url>
  <url>
    <loc>https://127.0.0.1:5000/aboutloc>
    <lastmod>2022-02-08lastmod>
    <changefreq>monthlychangefreq>
    <priority>1.0priority>
  url>
  <url>
    <loc>https://127.0.0.1:5000/storeloc>
  url>
urlset>
Comments
  • predefining SERVER_NAME doesn't allow for flask serving multiple domains

    predefining SERVER_NAME doesn't allow for flask serving multiple domains

    Hi there, When defining SERVER_NAME in the app config, a limitation is introduced if your same flask app serves multiple domains. Would it be possible to use the request.host element in the generator instead to generate the URLs when the sitemap is called?

    I tried to get it done myself, but I have to admit I'm getting lost here.

    good first issue 
    opened by Strahlemann 8
  • How to use with dynamic routes ?

    How to use with dynamic routes ?

    Hi,

    i want to use flask-sitemapper for static and some dynamic routes together with blueprints. I defined a instance of sitemapper in a separate file like describe in documentation and import this instance in every blueprint. In mainfile i initialize the instance with "app" after i registered the blueprints.

    This works well for all static routes like e.g. "/", "/about" etc. But it failed for all dynamic routes like:

    @blueprint_galleries.route("/gallery/<string:slug>", methods=['GET'])
    def gallery(slug):
        id, meta = get_gallery_id_and_meta_with_slug("galleries",slug)
        if id != False and meta != False:
            photo_details = get_gallery_photos("gallery",id)
            return render_template("gallery.html", photos=photo_details, metadata=meta)
        else:
            return render_template("404.html"), 404
    

    Error Message from werkzeug:

    werkzeug.routing.exceptions.BuildError: Could not build url for endpoint 'blueprint_galleries.gallery'. Did you forget to specify values ['slug']?

    I have no idea how i can solve this or use flask-sitemapper with dynamic routes. I don't found anything about it in documentation.

    Any help or hints would be great. Thanks in advanced!

    good first issue question 
    opened by NiTRoeSE 3
  • add support for deferred initialization and blueprint routes in SitemapperExtend class

    add support for deferred initialization and blueprint routes in SitemapperExtend class

    Thank you @h-janes for creating this amazing extension.

    This PR

    • introduced a deferred initialization to the extension, check init_app
    • added support for blueprint routes
      • no need to explicitely call sitemapper.add_endpoint for large or complex project
      • endpoint name can be found by traversing app.view_functions dict

    Note that blueprints must be registered before initializing sitemapper extension

    All changes are made to SitemapperExtended class, we can merge these into Sitemapper class later

    opened by renph 1
  • Fixes issue #2 and uses pre-defined arguments instead of **kwargs

    Fixes issue #2 and uses pre-defined arguments instead of **kwargs

    • To fix #2, URLs in the Sitemapper urls list are now stored as new URL objects rather than dicts, with methods that generate their URL loc and XML during sitemap generation. These changes are in sitemapper.py and templates.py

    • The Sitemapper methods include and add_endpoint previously accepted **kwargs but now only accept the pre-defined keyword arguments lastmod changefreqand priority

    • README.md has been improved and updated to reflect these changes.

    • A test has been added in test_server_name.py to ensure that the extension respects the SERVER_NAME if it is defined in the Flask configuration.

    • The version number has been incremented to 1.5.0 to reflect these changes and prepare for the next release.

    opened by h-janes 0
  • Dynamic URLS do not work.

    Dynamic URLS do not work.

    I tried getting the sitemapper working, but even with your code example for dynamic routes I still get an error:

    werkzeug.routing.exceptions.BuildError: Could not build url for endpoint 'blog_bp.r_user'. Did you forget to specify values ['user_id']?

    @sitemapper.include(url_variables={"user_id": [1, 2, 3]}) @blog_bp.route("/user/int:user_id") def r_user(user_id): return f"

    User #{user_id}

    "

    opened by deepdatadive 5
Releases(1.6.1)
  • 1.6.1(Jan 4, 2023)

  • 1.6.0(Dec 20, 2022)

    • Adds support for dynamic Flask routes (see wiki)
    • Now stores sitemap XML after the first request instead of generating it on each request
    • Tests have been improved
    • Documentation has been updated
    Source code(tar.gz)
    Source code(zip)
  • 1.5.1(Nov 28, 2022)

    This release adds support for Python datetime objects (as well as strings) for the lastmod argument, moves documentation from README.md to the GitHub wiki, and adds project URLs to the package metadata.

    Source code(tar.gz)
    Source code(zip)
  • 1.5.0(Nov 26, 2022)

    Main Changes in This Version

    • Now fully supports apps using multiple domains, resolving issue #2
    • Uses pre-defined arguments instead of **kwargs for lastmod, changefreq, and priority.
    • Adds functionality to serve sitemaps with GZIP.
    • Improved code comments, docstrings, and spelling.
    • Improves and updates README.md
    Source code(tar.gz)
    Source code(zip)
  • 1.4.1(Nov 13, 2022)

    Main Changes in This Version

    • Refactors the project
    • Changes build system to Poetry
    • Adds tests
    • Improves README
    • Adds option to gzip sitemaps
    • Improves code comments
    • Adds documentation for developers/contributors

    WARNING: From this version onwards, Flask Sitemapper requires Python >=3.7

    Version 1.4.0 was deleted shortly after release due to an incorrectly named __init__.py which meant the version could not be imported properly. Checks will be more thorough and versioning will be more consistent from now on.

    Source code(tar.gz)
    Source code(zip)
Owner
Python and web stuff (New account, lost old login)
Learn REST API with Flask, Mysql and Docker

Learn REST API with Flask, Mysql and Docker A project for you to learn to work a flask REST api with docker and the mysql database manager! Table of C

Aldo Matus 0 Jul 31, 2021
Neo4j Movies Example application with Flask backend using the neo4j-python-driver

Neo4j Movies Application: Quick Start This example application demonstrates how easy it is to get started with Neo4j in Python. It is a very simple we

Neo4j Examples 309 Dec 24, 2022
A swagger 2.0 spec extractor for flask

flask-swagger A Swagger 2.0 spec extractor for Flask You can now specify base path for yml files: app = Flask(__name__) @app.route("/spec") def spec(

Sling 457 Dec 02, 2022
A Flask application for Subdomain Enumeration

subdomainer-flask A Flask application for Subdomain Enumeration steps to be done git clone https://github.com/gokulapap/subdomainer-flask pip3 install

GOKUL A.P 7 Sep 22, 2022
Lux Academy & Data Science East Africa Python Boot Camp, Building and Deploying Flask Application Using Docker Demo App.

Flask and Docker Application Demo A Docker image is a read-only, inert template that comes with instructions for deploying containers. In Docker, ever

Harun Mbaabu Mwenda 11 Oct 29, 2022
Flask Web DRY full-stack framework by Problem Fighter

In the name of God, the Most Gracious, the Most Merciful. PF-Flask-Web Documentation Install and update using pip: pip install -U PF-Flask-Web Please

Problem Fighter 2 Jan 20, 2022
A multi-container docker application. Implemented and dockerized a web-based service leveraging Flask

Flask-based-web-service-with-Docker-compose A multi-container docker application. Implemented and dockerized a web-based service leveraging Flask. Des

Jayshree Rathi 1 Jan 15, 2022
Adds GraphQL support to your Flask application.

Flask-GraphQL Adds GraphQL support to your Flask application. Usage Just use the GraphQLView view from flask_graphql from flask import Flask from flas

GraphQL Python 1.3k Jan 03, 2023
Seamlessly serve your static assets of your Flask app from Amazon S3

flask-s3 Seamlessly serve the static assets of your Flask app from Amazon S3. Maintainers Flask-S3 is maintained by @e-dard, @eriktaubeneck and @SunDw

Edd Robinson 188 Aug 24, 2022
Serve angular production application from python flask backend. Quick and Easy

Serve angular production application from python flask backend. Quick and Easy

mark 1 Dec 01, 2022
a flask profiler which watches endpoint calls and tries to make some analysis.

Flask-profiler version: 1.8 Flask-profiler measures endpoints defined in your flask application; and provides you fine-grained report through a web in

Mustafa Atik 718 Dec 20, 2022
Another redis monitor by using flask, angular, socket.io

RedisPAPA we use redis info to monitor the redis usage. PAPA means a father who is monitoring the redis. accoding to the redis doc, it is be recommand

no13bus 393 Dec 30, 2022
Live Corona statistics and information site with flask.

Flask Live Corona Info Live Corona statistics and information site with flask. Tools Flask Scrapy Matplotlib How to Run Project Download Codes git clo

Mohammad Dori 5 Jul 15, 2022
A solid foundation for your flask app

Flask Foundation There is a cookiecutter version of this repo at https://github.com/JackStouffer/cookiecutter-Flask-Foundation. Documentation is locat

Jack Stouffer 1.3k Dec 11, 2022
Curso Desenvolvimento avançado Python com Flask e REST API

Curso Desenvolvimento avançado Python com Flask e REST API Curso da Digital Innovation One Professor: Rafael Galleani Conteudo do curso Introdução ao

Elizeu Barbosa Abreu 1 Nov 14, 2021
A simple barcode and QR code generator built in Python with Flask.

✨ Komi - Barcode & QR Generator ✨ A simple barcode and QR code generator built in Python with Flask. 📑 Table of Contents Usage Installation Contribut

Bonnie Fave 2 Nov 04, 2021
É uma API feita em Python e Flask que pesquisa informações em uma tabela .xlsx e retorna o resultado.

API de rastreamento de pacotes É uma API feita em Python e Flask que pesquisa informações de rastreamento de pacotes em uma tabela .xlsx e retorna o r

Marcos Beraldo Barros 4 Jun 27, 2021
HTTP security headers for Flask

Talisman: HTTP security headers for Flask Talisman is a small Flask extension that handles setting HTTP headers that can help protect against a few co

Google Cloud Platform 853 Dec 19, 2022
Telegram bot + Flask API ( Make Introduction pages )

Introduction-Page-Maker Setup the api Upload the flask api on your host Setup requirements Make pages file on your host and upload the css and js and

Plugin 9 Feb 11, 2022
Browsable web APIs for Flask.

Flask API Browsable web APIs for Flask. Status: This project is in maintenance mode. The original author (Tom Christie) has shifted his focus to API S

Flask API 1.3k Jan 05, 2023