Flask-Track-Usage 1.1.0

Basic metrics tracking for your Flask application. This focuses more on ip addresses/locations rather than tracking specific users pathing through an application. No extra cookies or javascript is used for usage tracking.

  • Simple. It’s a Flask extension.
  • Supports either include or exempt for views.
  • Provides lite abstraction for data retrieval.
  • Optional freegeoip.net integration including custom freegeoip installs.
  • Multiple storage options.

Installation

Warning

1.1.x releases are not 100% backwards compatible with the 1.x.x nor 0.0.x series of releases.

Requirements

Via pip

$ pip install Flask-Track-Usage

Via source

$ python setup.py install

Usage

# Create the Flask 'app'
from flask import Flask
app = Flask(__name__)

# Set the configuration items manually for the example
app.config['TRACK_USAGE_USE_FREEGEOIP'] = False
# You can use a different instance of freegeoip like so
# app.config['TRACK_USAGE_FREEGEOIP_ENDPOINT'] = 'https://example.org/api/'
app.config['TRACK_USAGE_INCLUDE_OR_EXCLUDE_VIEWS'] = 'include'

# We will just print out the data for the example
from flask.ext.track_usage import TrackUsage
from flask.ext.track_usage.storage.printer import PrintStorage

# Make an instance of the extension
t = TrackUsage(app, PrintStorage())

# Make an instance of the extension
t = TrackUsage(app, storage)

# Include the view in the metrics
@t.include
@app.route('/')
def index():
    return "Hello"

# Run the application!
app.run(debug=True)

Blueprint Support

Blueprints can be included or excluded from Flask-TrackUsage in their entirety.

Include

# ...
app.config['TRACK_USAGE_INCLUDE_OR_EXCLUDE_VIEWS'] = 'include'

# Make an instance of the extension
t = TrackUsage(app, PrintStorage())

from my_blueprints import a_bluprint

# Now ALL of a_blueprint's views will be in the include list
t.include_blueprint(a_blueprint)

Exclude

# ...
app.config['TRACK_USAGE_INCLUDE_OR_EXCLUDE_VIEWS'] = 'exclude'

# Make an instance of the extension
t = TrackUsage(app, PrintStorage())

from my_blueprints import a_bluprint

# Now ALL of different_blueprints will be in the exclude list
t.exclude_blueprint(a_blueprint)

Configuration

TRACK_USAGE_USE_FREEGEOIP

Values: True, False

Default: False

TRACK_USAGE_FREEGEOIP_ENDPOINT

Values: URL

Default: http://freegeoip.net/json/

Turn FreeGeoIP integration on or off

TRACK_USAGE_INCLUDE_OR_EXCLUDE_VIEWS

Values: include, exclude

Default: exclude

If views should be included or excluded by default.

  • When set to exclude each routed view must be explicitly included via decorator or blueprint include method. If a routed view is not included it will not be tracked.
  • When set to include each routed view must be explicitly excluded via decorator or blueprint exclude method. If a routed view is not excluded it will be tracked.

Storage

The following are built in, ready to use storage backends.

Note

Inputs for set_up should be passed in __init__ when creating a storage instance

printer.PrintStorage

class flask_track_usage.storage.printer.PrintStorage(*args, **kwargs)

Simply prints out the data it gets. Not really storage proper. Helpful for testing.

get_usage(start_date=None, end_date=None, limit=500, page=1)

Returns simple usage information by criteria in a standard list form.

Note

limit is the amount if items returned per page. If page is not incremented you will always receive the first limit amount of results.

Parameters:
  • start_date: datetime.datetime representation of starting date
  • end_date: datetime.datetime representation of ending date
  • limit: The max amount of results to return
  • page: Result page number limited by limit number in a page

New in version 1.0.0: The page parameter.

set_up(*args, **kwargs)

Sets up the created instance. Should be overridden.

Parameters:
  • args: All non-keyword arguments.
  • kwargs: All keyword arguments.
store(data)

Executed on “function call”.

Parameters:
  • data: Data to store.

mongo.MongoPiggybackStorage

class flask_track_usage.storage.mongo.MongoPiggybackStorage(*args, **kwargs)

Uses a pymongo collection to store data.

get_usage(start_date=None, end_date=None, limit=500, page=1)

Returns simple usage information by criteria in a standard list form.

Note

limit is the amount if items returned per page. If page is not incremented you will always receive the first limit amount of results.

Parameters:
  • start_date: datetime.datetime representation of starting date
  • end_date: datetime.datetime representation of ending date
  • limit: The max amount of results to return
  • page: Result page number limited by limit number in a page

New in version 1.0.0: The page parameter.

set_up(collection)

Sets the collection.

Parameters:
  • collection: A pymongo collection (not database or connection).
store(data)

Executed on “function call”.

Parameters:
  • data: Data to store.

Changed in version 1.1.0: xforwardfor item added directly after remote_addr

mongo.MongoStorage

class flask_track_usage.storage.mongo.MongoStorage(*args, **kwargs)

Creates it’s own connection for storage.

get_usage(start_date=None, end_date=None, limit=500, page=1)

Returns simple usage information by criteria in a standard list form.

Note

limit is the amount if items returned per page. If page is not incremented you will always receive the first limit amount of results.

Parameters:
  • start_date: datetime.datetime representation of starting date
  • end_date: datetime.datetime representation of ending date
  • limit: The max amount of results to return
  • page: Result page number limited by limit number in a page

New in version 1.0.0: The page parameter.

set_up(database, collection, host='127.0.0.1', port=27017, username=None, password=None)

Sets the collection.

Parameters:
  • database: Name of the database to use.
  • collection: Name of the collection to use.
  • host: Host to conenct to. Default: 127.0.0.1
  • port: Port to connect to. Default: 27017
  • username: Optional username to authenticate with.
  • password: Optional password to authenticate with.
store(data)

Executed on “function call”.

Parameters:
  • data: Data to store.

Changed in version 1.1.0: xforwardfor item added directly after remote_addr

sql.SQLStorage

Warning

This storage is not backwards compatible with sql.SQLStorage 1.0.x

class flask_track_usage.storage.sql.SQLStorage(*args, **kwargs)

Uses SQLAlchemy to connect to various databases such as SQLite, Oracle, MySQL, Postgres, etc. Please SQLAlchemy wrapper for full support and functionalities.

New in version 1.0.0: SQLStorage was added.

Changed in version 1.1.0: Initialization no longer accepts a connection string.

Changed in version 1.1.0: A SQLAlchemy engine instance can optionally be passed in.

Changed in version 1.1.0: A SQLAlchemy metadata instance can optionally be passed in.

get_usage(start_date=None, end_date=None, limit=500, page=1)

Returns simple usage information by criteria in a standard list form.

Note

limit is the amount if items returned per page. If page is not incremented you will always receive the first limit amount of results.

Parameters:
  • start_date: datetime.datetime representation of starting date
  • end_date: datetime.datetime representation of ending date
  • limit: The max amount of results to return
  • page: Result page number limited by limit number in a page

New in version 1.0.0: The page parameter.

set_up(engine=None, metadata=None, table_name='flask_usage', db=None)

Sets the SQLAlchemy database. There are two ways to initialize the SQLStorage: 1) by passing the SQLAlchemy engine and metadata instances or 2) by passing the Flask-SQLAlchemy’s SQLAlchemy object db.

Parameters:
  • engine: The SQLAlchemy engine object

  • metadata: The SQLAlchemy MetaData object

  • table_name: Table name for storing the analytics. Defaults to flask_usage.

  • db: Instead of providing the engine, one can optionally

    provide the Flask-SQLAlchemy’s SQLALchemy object created as SQLAlchemy(app).

Changed in version 1.1.0: xforwardfor column added directly after remote_addr

store(data)

Executed on “function call”.

Parameters:
  • data: Data to store.

Changed in version 1.1.0: xforwardfor column added directly after remote_addr

Retrieving Data

All storage backends, other than printer.PrintStorage, provide get_usage.

class flask_track_usage.storage.Storage(*args, **kwargs)

Subclass for a more intellegent storage callable.

get_usage(start_date=None, end_date=None, limit=500, page=1)

Returns simple usage information by criteria in a standard list form.

Note

limit is the amount if items returned per page. If page is not incremented you will always receive the first limit amount of results.

Parameters:
  • start_date: datetime.datetime representation of starting date
  • end_date: datetime.datetime representation of ending date
  • limit: The max amount of results to return
  • page: Result page number limited by limit number in a page

New in version 1.0.0: The page parameter.

Results that are returned from all instances of get_usage should always look like this:

[
    {
            'url': str,
            'user_agent': {
                'browser': str,
                'language': str,
                'platform': str,
                'version': str,
            },
            'blueprint': str,
            'view_args': dict or None
            'status': int,
            'remote_addr': str,
            'xforwardedfor': str,
            'authorization': bool
            'ip_info': str or None,
            'path': str,
            'speed': float,
            'date': datetime,
    },
    {
        ....
    }
]

Changed in version 1.1.0: xforwardfor item added directly after remote_addr