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)
null
flask-apispec MIT flask-apispec (🥉24 · ⭐ 520) - Build and document REST APIs with Flask and apispec. MIT

flask-apispec flask-apispec is a lightweight tool for building REST APIs in Flask. flask-apispec uses webargs for request parsing, marshmallow for res

Joshua Carp 617 Dec 30, 2022
Small flask based opds catalog designed to serve a directory via OPDS

teenyopds Small flask based opds catalog designed to serve a directory via OPDS, it has currently only been verified to work with KyBook 3 on iOS but

Adam Furbee 4 Jul 14, 2022
SQLAlchemy database migrations for Flask applications using Alembic

Flask-Migrate Flask-Migrate is an extension that handles SQLAlchemy database migrations for Flask applications using Alembic. The database operations

Miguel Grinberg 2.2k Dec 28, 2022
Quick and simple security for Flask applications

Note This project is non maintained anymore. Consider the Flask-Security-Too project as an alternative. Flask-Security It quickly adds security featur

Matt Wright 1.6k Dec 19, 2022
Socket.IO integration for Flask applications.

Flask-SocketIO Socket.IO integration for Flask applications. Installation You can install this package as usual with pip: pip install flask-socketio

Miguel Grinberg 4.9k Jan 2, 2023
Socket.IO integration for Flask applications.

Flask-SocketIO Socket.IO integration for Flask applications. Installation You can install this package as usual with pip: pip install flask-socketio

Miguel Grinberg 4.1k Feb 17, 2021
flask-reactize is a boostrap to serve any React JS application via a Python back-end, using Flask as web framework.

flask-reactize Purpose Developing a ReactJS application requires to use nodejs as back end server. What if you want to consume external APIs: how are

Julien Chomarat 4 Jan 11, 2022
Flask-Discord-Bot-Dashboard - A simple discord Bot dashboard created in Flask Python

Flask-Discord-Bot-Dashboard A simple discord Bot dashboard created in Flask Pyth

Ethan 8 Dec 22, 2022
flask extension for integration with the awesome pydantic package

Flask-Pydantic Flask extension for integration of the awesome pydantic package with Flask. Installation python3 -m pip install Flask-Pydantic Basics v

null 249 Jan 6, 2023
Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application.

Flask-Bcrypt Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application. Due to the recent increased prevelance of

Max Countryman 310 Dec 14, 2022
Flask-Rebar combines flask, marshmallow, and swagger for robust REST services.

Flask-Rebar Flask-Rebar combines flask, marshmallow, and swagger for robust REST services. Features Request and Response Validation - Flask-Rebar reli

PlanGrid 223 Dec 19, 2022
Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application.

Flask-Bcrypt Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application. Due to the recent increased prevelance of

Max Countryman 282 Feb 11, 2021
Flask-Starter is a boilerplate starter template designed to help you quickstart your Flask web application development.

Flask-Starter Flask-Starter is a boilerplate starter template designed to help you quickstart your Flask web application development. It has all the r

Kundan Singh 259 Dec 26, 2022
Brandnew-flask is a CLI tool used to generate a powerful and mordern flask-app that supports the production environment.

Brandnew-flask is still in the initial stage and needs to be updated and improved continuously. Everyone is welcome to maintain and improve this CLI.

brandonye 4 Jul 17, 2022
Flask Project Template A full feature Flask project template.

Flask Project Template A full feature Flask project template. See also Python-Project-Template for a lean, low dependency Python app. HOW TO USE THIS

Bruno Rocha 96 Dec 23, 2022
A Fast API style support for Flask. Gives you MyPy types with the flexibility of flask

Flask-Fastx Flask-Fastx is a Fast API style support for Flask. It Gives you MyPy types with the flexibility of flask. Compatibility Flask-Fastx requir

Tactful.ai 18 Nov 26, 2022
Flask-app scaffold, generate flask restful backend

Flask-app scaffold, generate flask restful backend

jacksmile 1 Nov 24, 2021
Flask pre-setup architecture. This can be used in any flask project for a faster and better project code structure.

Flask pre-setup architecture. This can be used in any flask project for a faster and better project code structure. All the required libraries are already installed easily to use in any big project.

Ajay kumar sharma 5 Jun 14, 2022
Pf-flask-rest-com - Flask REST API Common Implementation by Problem Fighter Library

In the name of God, the Most Gracious, the Most Merciful. PF-Flask-Rest-Com Docu

Problem Fighter 3 Jan 15, 2022