Skip to main content

Flask-Statistics

Flask-Statistics is an extensions that collects data from requests send to the server to then display statistics like response-time, hits, unique hits, etc.

Installation

You can install the extensions with pip:

$ pip install flask-statistics

Usage

Below is a small example on how to use the extension.

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_statistics import Statistics

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///database.db"

db = SQLAlchemy(app)

class Request(db.Model):
    __tablename__ = "request"

    index = db.Column(db.Integer, primary_key=True, autoincrement=True)
    response_time = db.Column(db.Float)
    date = db.Column(db.DateTime)
    method = db.Column(db.String)
    size = db.Column(db.Integer)
    status_code = db.Column(db.Integer)
    path = db.Column(db.String)
    user_agent = db.Column(db.String)
    remote_address = db.Column(db.String)
    exception = db.Column(db.String)
    referrer = db.Column(db.String)
    browser = db.Column(db.String)
    platform = db.Column(db.String)
    mimetype = db.Column(db.String)

statistics = Statistics(app, db, Request)

@app.route("/")
def index():
    return "Hello World!"

if  __name__ == "__main__":
    app.run()

The script above sets up a basic SQLAlchemy Database. When initalizing the statistics extensions, you will have to provide a model (here: Request) to store the data in.

Now, whenever a user requests an endpoint, it will be stored in the defined model.

If you are in debug mode and an exception occures, teardown of the request will not happen and therefore it won't be stored in the database. If you want to teardown it by force, set PRESERVE_CONTEXT_ON_EXCEPTION to False in the config.

Things that are stored

Key Type Description
response_time float The time it took the server to process the request.
date datetime.datetime The date the request was send to the server (in UTC).
method str The HTTP method that was used (e.g. GET, POST, ..).
size int The body size in bytes that was send to the client.
status_code int The status code that was returned by the request.
user_agent str The User-Agent that was send with the request.
remote_address str The ip address of the client.
exception str If an error occured, this field will have the error message and the status_code will automatically be 500.
Example: ZeroDivisionError('division by zero')
referrer str Link to the website that referred the user to the endpoint.
browser str The browser that was used to send the request.
Example: firefox 72.0
platform str Operating System the request was send from.
mimetype str Mimetype of the response send to the client (e.g. html/text).

View the statistics

Flask-Statistics will add a blueprint with the prefix ../statistics to your app.

preview_image

Config

Name Type Description Default
STATISTICS_DEFAULT_DATE_SPAN datetime.timedelta If no date was selected, it will be set to today as end and today - option as start. datetime.timedelta(days=7)

Protect the route

Flask-Statistics accepts a fourth argument: A function that is called before any requests to the statistics blueprint.

...

def check_if_user_is_allowed():
    # check if user is allowed to
    # e.g. JWT Token, Flask Login etc.
    # ...
    if not allowed:
        return redirect(url_for("index"))

statistics = Statistics(app, db, Request, check_if_user_is_allowed)

There you can check if the user has the required permissions to view the statistics. If not, redirect him to another page.

Disable statistics

If a user has opt-out, request record can be disabled with custom function disable_f.

statistics = Statistics(app, db, Request, disable_f= lambda: current_user.has_optout() )

or

def has_disable_cookie():
    return request.cookies.get('disable_stat') == 'True'

statistics = Statistics(app, db, Request, disable_f=has_disable_cookie )

Metadata

Release files for flask-statistics 1.0.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for flask-statistics 1.0.2
File Size Uploaded Provenance Actions
flask-statistics-1.0.2.tar.gz 10.4 kB Without provenance Details for flask-statistics-1.0.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for flask-statistics 1.0.2
File Interpreter ABI Platform Actions
flask_statistics-1.0.2-py3-none-any.whl Python 3 none any Details for flask_statistics-1.0.2-py3-none-any.whl

Total release size: 21.8 kB

Release files / flask-statistics-1.0.2.tar.gz

Download URL flask-statistics-1.0.2.tar.gz
Size 10.4 kB
Tags Source
SHA-256 checksum
How to use checksums
9f238767c0a0b39446180196761d1e8e9fe5a644268aa9465430446acd1c1bf0
BLAKE2b-256 checksum
How to use checksums
de315044f9b42ee8f62b9ddba0ed763ffdc5a584710fa7dfd9a36ec905dc143e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/47.1.1 requests-toolbelt/0.9.1 tqdm/4.48.2 CPython/3.8.3

Release files / flask_statistics-1.0.2-py3-none-any.whl

Download URL flask_statistics-1.0.2-py3-none-any.whl
Size 11.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
cc052049661ed9d166788050f134eb49d4d224aae57fec313da8b1b6c8cc207b
BLAKE2b-256 checksum
How to use checksums
d8982f78aa45fa0f90999fa8727ddbbfdba6ed7b12a9b1f2f799b88fcd749195
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/47.1.1 requests-toolbelt/0.9.1 tqdm/4.48.2 CPython/3.8.3

Security for flask-statistics 1.0.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page