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)
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
A tool for the game Politics And War. Saving players hours if searching for targets they can engage with.

A tool for the game Politics And War. Saving players hours if searching for targets they can engage with.

1 Dec 19, 2021
Adds SQLAlchemy support to Flask

Flask-SQLAlchemy Flask-SQLAlchemy is an extension for Flask that adds support for SQLAlchemy to your application. It aims to simplify using SQLAlchemy

The Pallets Projects 3.9k Dec 29, 2022
Rate Limiting extension for Flask

Flask-Limiter Flask-Limiter provides rate limiting features to flask routes. It has support for a configurable backend for storage with current implem

Ali-Akber Saifee 922 Jan 08, 2023
A boilerplate Flask API for a Fullstack Project :rocket:

Flask Boilerplate to quickly get started with production grade flask application with some additional packages and configuration prebuilt.

Yasser Tahiri 32 Dec 24, 2022
Flask app for deploying DigitalOcean droplet using Pulumi.

Droplet Deployer Simple Flask app which deploys a droplet onto Digital ocean. Behind the scenes there's Pulumi being used. Background I have been Terr

Ahmed Sajid 1 Oct 30, 2021
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 Python, Flask login system

Python Login System This is a basic login + authenticason system for flask using Flask_Login and Flask_SQLAlchemy Get started on your own To use this

MrShoe 0 Feb 02, 2022
Rich implementation for Flask

Flask Rich Implements the Rich programming library with Flask. All features are toggleable, including: Better logging Colorful tracebacks Usage Import

BD103 13 Jun 06, 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
Boilerplate template formwork for a Python Flask application with Mysql,Build dynamic websites rapidly.

Overview English | 简体中文 How to Build dynamic web rapidly? We choose Formwork-Flask. Formwork is a highly packaged Flask Demo. It's intergrates various

aswallz 81 May 16, 2022
The Coodesh Python Backend Challenge (2021) written in Flask

Coodesh Back-end Challenge 🏅 2021 ID: 917 The Python Back-end Coodesh Challenge Description This API automatically retrieves users from the RandomUse

Marcus Vinicius Pereira 1 Oct 20, 2021
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
Learn python and flask,just a tony blog system

flaskblog Learn python and flask,just a tony blog system based on flask and mysql It is similar to cleanblog, a blog system based on flask and mongoen

shin 174 Dec 01, 2022
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
Sample Dockerized flask app deployed on Kubernetes on Azure using AKS

Sample Dockerized flask app deployed on Kubernetes on Azure using AKS

Ahmed khémiri 22 Sep 08, 2021
An easy way to build your flask skeleton.

Flider What is Flider Flider is a lightweight framework that saves you time by creating a MVC compliant file structure and includes basic commonly use

Trevor Engen 8 Nov 17, 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
: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
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