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)
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 web application for a fake pizza store, built in Python with Flask and PostgreSQL.

✨ Pizza Pizza - Pizza Store ✨ A web application for a fake Pizza Store, the app let you create an account and order pizza, complements or drinks. Buil

Bonnie Fave 6 Dec 18, 2022
Simple flask api. Countdown to next train for each station in the subway system.

Simple flask api. Countdown to next train for each station in the subway system.

Kalyani Subbiah 0 Apr 17, 2022
retorna informações de pessoas que não existem

random-person-api API que entrega dados aleatórios sobre pessoas que (provavelmente) não existem. Como usar? Copie o link abaixo https://random-person

Miguel 3 Aug 09, 2022
A flask extension using pyexcel to read, manipulate and write data in different excel formats: csv, ods, xls, xlsx and xlsm.

Flask-Excel - Let you focus on data, instead of file formats Support the project If your company has embedded pyexcel and its components into a revenu

247 Dec 27, 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
Flask RESTful Web services using API to communicate between client and server.

Welcome! Open up two terminals, one for client and for server each Terminal 1 Terminal 2 Now navigate to the CW2_code directory in both like so $ cd C

Sehra Elahi 1 Nov 23, 2021
The Snoopy boilerplate in flask framework for development enterprise application.

Snoopy What is snoopy! The "Snoopy" boilerplate in flask framework for development enterprise application. Motivation In my 10 years of development ex

Bekhzod 2 Sep 29, 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
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
Getting Started with Docker and Flask

Getting-Started-with-Docker-and-Flask Introduction Docker makes it easier, simpler and safer to build, deploy and manage applications in a docker cont

Phylis Jepchumba 1 Oct 08, 2021
Python web-app (Flask) to browse Tandoor recipes on the local network

RecipeBook - Tandoor Python web-app (Flask) to browse Tandoor recipes on the local network. Designed for use with E-Ink screens. For a version that wo

5 Oct 02, 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
A gRpc server like Flask (像Flask一样的gRpc服务)

Mask A gRpc server just like Flask. Install Mask support pypi packages, you can simply install by: pip install mask Document Mask manual could be fou

吴东 16 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
With Flask. Everything in a JSON.

Little Library REST API py 3.10 The only one requeriment it's to have Flask installed. To run this, in ./src/(if you're in PS): $env:FLASK_APP="app

Luis Quiñones Requelme 1 Dec 15, 2021
A caching extension for Flask

Flask-Caching Adds easy cache support to Flask. This is a fork of the Flask-Cache extension. Flask-Caching also includes the cache module from werkzeu

Peter Justin 774 Jan 02, 2023
A Cyberland server written in Python with Flask.

Cyberland What is Cyberland Cyberland is a textboard that offers no frontend. Most of the time, the user makes their own front end. The protocol, as f

Maxime Bouillot 9 Nov 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
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