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 basic JSON-RPC implementation for your Flask-powered sites

Flask JSON-RPC A basic JSON-RPC implementation for your Flask-powered sites. Some reasons you might want to use: Simple, powerful, flexible and python

Cenobit Technologies 272 Jan 04, 2023
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
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
Forum written for learning purposes in flask and sqlalchemy

Flask-forum forum written for learning purposes using SQLalchemy and flask How to install install requirements pip install sqlalchemy flask clone repo

Kamil 0 May 23, 2022
Heroku Flask Setup

Heroku Flask Setup

Abhimanyu Haralukallu 0 Dec 07, 2021
Full text search for flask.

flask-msearch Installation To install flask-msearch: pip install flask-msearch # when MSEARCH_BACKEND = "whoosh" pip install whoosh blinker # when MSE

honmaple 197 Dec 29, 2022
Freezes a Flask application into a set of static files.

Frozen-Flask Freezes a Flask application into a set of static files. The result can be hosted without any server-side software other than a traditiona

Frozen Flask 737 Dec 19, 2022
Example Flask application illustrating some of my common practices

Overholt Overholt is an example Flask application illustrating some of my common practices Development Environment At the bare minimum you'll need the

Matt Wright 1.6k Dec 15, 2022
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
Flask Application Structure with MongoDB

This application aims to serve as a template for APIs that intend to use mongoengine and flask-restx

Tiago Franco 5 Jun 25, 2022
Companion code to my O'Reilly book "Flask Web Development", second edition.

Flasky This repository contains the source code examples for the second edition of my O'Reilly book Flask Web Development. The commits and tags in thi

Miguel Grinberg 8k Dec 27, 2022
A flask template with Bootstrap 4, asset bundling+minification with webpack, starter templates, and registration/authentication.

cookiecutter-flask A Flask template for cookiecutter. (Supports Python ≥ 3.6) See this repo for an example project generated from the most recent vers

4.3k Jan 06, 2023
A service made with Flask and Python to help you find the weather of your favorite cities.

Weather-App A service made with Flask and Python to help you find the weather of your favorite cities. Features Backend using Flask and Jinja Weather

Cauã Rinaldi 1 Nov 17, 2022
A simple example using Flask inside a container

This is a simple example of how create a container for a Python Flask Web Application using Docker.

Fazt Web 8 Aug 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
docker-compose uWSGI nginx flask

docker-compose uWSGI nginx flask Note that this was tested on CentOS 7 Usage sudo yum install docker

Abdolkarim Saeedi 3 Sep 11, 2022
A simple demo of using aiogram + async sqlalchemy 1.4+

aiogram-and-sqlalchemy-demo A simple demo of using aiogram + async sqlalchemy 1.4+ Used tech: aiogram SQLAlchemy 1.4+ PostgreSQL as database asyncpg a

Aleksandr 68 Dec 31, 2022
A Python chat app built with Flask that runs in the browser.

A Python chat app built with Flask that runs in the browser. Designed for local area networks that are not connected to the Internet.

Leonard Kleber 1 Dec 23, 2021
Flask extension for Pusher

Flask-Pusher Flask extension for Pusher. It is a thin wrapper around the official client, binding Flask app to Pusher client. Installation Install Fla

Iuri de Silvio 9 May 29, 2021
:rocket: Generate a Postman collection from your Flask application

flask2postman A tool that creates a Postman collection from a Flask application. Install $ pip install flask2postman Example Let's say that you have a

Numberly 137 Nov 08, 2022