Skip to main content

Flask Allowed Hosts

This extension provides a way to restrict access to your Flask application based on the incoming request's hostname or IP address or IP address range (network).

Features

  • Per-route configuration options.
  • Customize denied access behavior.
  • Two usage options: class-based or decorator-based.
  • Restrict access by hostname, IP address or IP address range (network).

Installation

Install the package using pip:

pip install flask-allowed-hosts

Usage

Class-Based Usage

  1. Initialize the AllowedHosts class.
  2. Define allowed hosts (optional).
  3. Define a function for denied access behavior (optional).
  4. Apply access control to routes using @allowed_hosts.limit() decorator (optional).

Example:

from flask import Flask, jsonify, abort
from flask_allowed_hosts import AllowedHosts

app = Flask(__name__)

ALLOWED_HOSTS = ["93.184.215.14", "api.example.com"]


def custom_on_denied():
    error = {"error": "Oops! Looks like you are not allowed to access this page!"}
    return jsonify(error), 403


allowed_hosts = AllowedHosts(app, allowed_hosts=ALLOWED_HOSTS, on_denied=custom_on_denied)


# Allows all incoming requests
@app.route("/api/public", methods=["GET"])
def public_endpoint():
    data = {"message": "This is public!"}
    return jsonify(data), 200


# Only allows incoming requests from "93.184.215.14" and "api.example.com"
@app.route("/api/private", methods=["GET"])
@allowed_hosts.limit()
def private_endpoint():
    data = {"message": "This is private!"}
    return jsonify(data), 200


# We can override the allowed_hosts list and the on_denied function for each route
@app.route("/api/private/secret", methods=["GET"])
@allowed_hosts.limit(allowed_hosts=["127.0.0.1"], on_denied=lambda: abort(404))
def secret_private_endpoint():
    data = {"message": "This is very private!"}
    return jsonify(data), 200


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

Decorator-Based Usage (Legacy)

Warning: This approach might cause unexpected behavior when combined with the class-based usage.

  1. Define allowed hosts (optional).
  2. Define a function for denied access behavior (optional).
  3. Apply access control to routes using @limit_hosts decorator.

Example:

from flask import Flask, jsonify
from flask_allowed_hosts import limit_hosts

app = Flask(__name__)

ALLOWED_HOSTS = ["93.184.215.14", "api.example.com"]


def custom_on_denied():
    error = {"error": "Custom Denied Response"}
    return jsonify(error), 403


# Allows all incoming requests
@app.route("/api/public", methods=["GET"])
def public_endpoint():
    data = {"message": "This is public!"}
    return jsonify(data), 200


# Only allows incoming requests from "93.184.215.14" and "api.example.com"
@app.route("/api/private", methods=["GET"])
@limit_hosts(allowed_hosts=ALLOWED_HOSTS, on_denied=custom_on_denied)
def private_endpoint():
    return jsonify({"message": "This is private!"}), 200

More Examples

You can find more examples in the examples directory.

Configuration

Initialization Parameters

  • app: The Flask application instance (optional).
  • allowed_hosts: List of allowed hosts (optional, defaults to None which allows all hosts).
  • on_denied: Function for denied access behavior (optional).

Flask Config and Environment Variables

Flask Configuration

The extension respects these configurations:

  • ALLOWED_HOSTS: List of allowed hosts in Flask config.
  • ALLOWED_HOSTS_ON_DENIED: Function for denied access behavior in Flask config.

Precedence: Values provided during initialization override Flask config values.

Environment Variables

You can enable debug mode by setting the ALLOWED_HOSTS_DEBUG environment variable to True:

export ALLOWED_HOSTS_DEBUG="True"

This will print helpful debug messages to the console.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Support

If you have any questions or feedback, please feel free to open an issue or a pull request.

License

This project is licensed under the [MIT] License - see the LICENSE.md file for details.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

flask_allowed_hosts-1.2.0.tar.gz (6.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

flask_allowed_hosts-1.2.0-py3-none-any.whl (7.8 kB view details)

Uploaded Python 3

File details

Details for the file flask_allowed_hosts-1.2.0.tar.gz.

File metadata

  • Download URL: flask_allowed_hosts-1.2.0.tar.gz
  • Upload date:
  • Size: 6.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.0.0 CPython/3.12.2

File hashes

Hashes for flask_allowed_hosts-1.2.0.tar.gz
Algorithm Hash digest
SHA256 2cbd159b7dd1d01628f082b28c0ce9bceee5b3811f70fc77731dce53a3ac13ab
MD5 f063dd8eea00cc85284044f6825032e5
BLAKE2b-256 d8d42a785e5e44db51c0127530e7330d6a3d5c9ec0569daae56933acd6ecfeac

See more details on using hashes here.

File details

Details for the file flask_allowed_hosts-1.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for flask_allowed_hosts-1.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0d391121b9d4da46570a86cd70d9ae38fd74e356ce61d0faf07d807d1b61e82c
MD5 133267fd32648503d9f767cb52377aaa
BLAKE2b-256 0561a63d77e88bf255350395614b11c04158ad224f5e1a579153ee0089c94e8e

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

1.2.0 This release

2 files

1.1.2

2 files

1.1.1

2 files

1.1.0

2 files

1.0.4

2 files

1.0.3

2 files

1.0.2

2 files

1.0.1

2 files

1.0.0

2 files

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page