Skip to main content

Moesif Middleware for Python WSGI based flatforms (Flask, Bottle & Others)

Project description

Moesif Middleware for Python WSGI based Frameworks

Built For Latest Version Language Versions Software License Source Code

WSGI middleware that logs incoming or outgoing API calls and sends to Moesif for API analytics and log analysis. Supports Python Frameworks built on WSGI such as Flask, Bottle, and Pyramid.

Source Code on GitHub

WSGI (Web Server Gateway Interface) is a standard (PEP 3333) that describes how a web server communicates with web applications. Many Python Frameworks are build on top of WSGI, such as Flask, Bottle, Pyramid etc. Moesif WSGI Middleware help APIs that are build on top of these Frameworks to easily integrate with Moesif.

How to install

pip install moesifwsgi

How to use

Flask

Wrap your wsgi_app with the Moesif middleware.

from moesifwsgi import MoesifMiddleware

moesif_settings = {
    'APPLICATION_ID': 'Your Moesif Application id',
    'LOG_BODY': True,
    # ... For other options see below.
}

app.wsgi_app = MoesifMiddleware(app.wsgi_app, moesif_settings)

Your Moesif Application Id can be found in the Moesif Portal. After signing up for a Moesif account, your Moesif Application Id will be displayed during the onboarding steps.

You can always find your Moesif Application Id at any time by logging into the Moesif Portal, click on the top right menu, and then clicking Installation.

For an example with Flask, see example in the /examples/flask folder of this repo.

Bottle

Wrap your bottle app with the Moesif middleware.

from moesifwsgi import MoesifMiddleware

app = bottle.Bottle()

moesif_settings = {
    'APPLICATION_ID': 'Your Moesif Application Id',
    'LOG_BODY': True,
    # ... For other options see below.
}

bottle.run(app=MoesifMiddleware(app, moesif_settings))

For an example with Bottle, see example in the /examples/bottle folder of this repo.

Pyramid

from pyramid.config import Configurator
from moesifwsgi import MoesifMiddleware

if __name__ == '__main__':
    config = Configurator()
    config.add_route('hello', '/')
    config.scan()
    app = config.make_wsgi_app()

    # configure your moesif settings
    moesif_settings = {
        'APPLICATION_ID': 'Your Moesif Application Id',
        'LOG_BODY': True,
        # ... For other options see below.
    }
    # Put middleware
    app = MoesifMiddleware(app, moesif_settings)

    server = make_server('0.0.0.0', 8080, app)
    server.serve_forever()

Other WSGI frameworks

If you are using a framework that is built on top of WSGI, it should work just by adding the Moesif middleware. Please read the documentation for your specific framework on how to add middleware.

Configuration options

APPLICATION_ID

(required), string, is obtained via your Moesif Account, this is required.

SKIP

(optional) (app, environ) => boolean, a function that takes a WSGI app and an environ, and returns true if you want to skip this particular event. The app is the original WSGI app instance, and the environ is a WSGI environ.

IDENTIFY_USER

(optional, but highly recommended) (app, environ) => string, a function that takes an app and an environ, and returns a string that is the user id used by your system. While Moesif tries to identify users automatically, but different frameworks and your implementation might be very different, it would be helpful and much more accurate to provide this function.

IDENTIFY_COMPANY

(optional) (app, environ) => string, a function that takes an app and an environ, and returns a string that is the company id for this event.

GET_METADATA

(optional) (app, environ) => dictionary, a function that takes an app and an environ, and returns a dictionary (must be able to be encoded into JSON). This allows your to associate this event with custom metadata. For example, you may want to save a VM instance_id, a trace_id, or a tenant_id with the request.

GET_SESSION_TOKEN

(optional) (app, environ) => string, a function that takes an app and an environ, and returns a string that is the session token for this event. Again, Moesif tries to get the session token automatically, but if you setup is very different from standard, this function will be very help for tying events together, and help you replay the events.

MASK_EVENT_MODEL

(optional) (EventModel) => EventModel, a function that takes an EventModel and returns an EventModel with desired data removed. The return value must be a valid EventModel required by Moesif data ingestion API. For details regarding EventModel please see the Moesif Python API Documentation.

DEBUG

(optional) boolean, a flag to see debugging messages.

LOG_BODY

(optional) boolean, default True, Set to False to remove logging request and response body.

CAPTURE_OUTGOING_REQUESTS

boolean, Default False. Set to True to capture all outgoing API calls from your app to third parties like Stripe or to your own dependencies while using Requests library. The options below is applied to outgoing API calls. When the request is outgoing, for options functions that take request and response as input arguments, the request and response objects passed in are Requests request or response objects.

SKIP_OUTGOING

(optional) (req, res) => boolean, a function that takes a Requests request and response, and returns true if you want to skip this particular event.

IDENTIFY_USER_OUTGOING

(optional, but highly recommended) (req, res) => string, a function that takes Requests request and response, and returns a string that is the user id used by your system. While Moesif tries to identify users automatically, but different frameworks and your implementation might be very different, it would be helpful and much more accurate to provide this function.

IDENTIFY_COMPANY_OUTGOING

(optional) (req, res) => string, a function that takes Requests request and response, and returns a string that is the company id for this event.

GET_METADATA_OUTGOING

(optional) (req, res) => dictionary, a function that takes Requests request and response, and returns a dictionary (must be able to be encoded into JSON). This allows to associate this event with custom metadata. For example, you may want to save a VM instance_id, a trace_id, or a tenant_id with the request.

GET_SESSION_TOKEN_OUTGOING

(optional) (req, res) => string, a function that takes Requests request and response, and returns a string that is the session token for this event. Again, Moesif tries to get the session token automatically, but if you setup is very different from standard, this function will be very help for tying events together, and help you replay the events.

LOG_BODY_OUTGOING

(optional) boolean, default True, Set to False to remove logging request and response body.

Example:

def identifyUser(app, environ):
    # return the user id here
    return "my_user_id"

def identifyCompany(app, environ):
    # return the company id here
    return "my_company_id"

def should_skip(app, environ):
    if "healthprobe" in environ.get('PATH_INFO', ''):
        return True
    else:
        return False

def get_session(app, environ):
    # extract session id from environ.
    return "session_id"

def mask_event(eventmodel):
    # do something to remove sensitive fields
    # be sure not to remove any required fields.
    return eventmodel

def get_metadata(app, environ):
    return { 'foo' : 'some data', 'bar' : 'another data', }

moesif_settings = {
    'APPLICATION_ID': 'Your Moesif Application Id',
    'DEBUG': False,
    'LOG_BODY': True,
    'IDENTIFY_USER': identifyUser,
    'IDENTIFY_COMPANY': identifyCompany,
    'GET_SESSION_TOKEN': get_token,
    'SKIP': should_skip,
    'MASK_EVENT_MODEL': mask_event,
    'GET_METADATA': get_metadata,
    'CAPTURE_OUTGOING_REQUESTS': False
}

app.wsgi_app = MoesifMiddleware(app.wsgi_app, moesif_settings)

Update User

update_user method

A method is attached to the moesif WSGI middleware object to update the user profile or metadata. The metadata field can be any custom data you want to set on the user. The user_id field is required.

update_user = MoesifMiddleware(app, moesif_settings).update_user({
        'user_id': '12345',
        'company_id': '67890',
        'metadata': {'email': 'abc@email.com', 'name': 'abcde', 'image': '123'},
        'campaign': {'utm_source': 'Newsletter', 'utm_medium': 'Email'}
    })

update_users_batch method

A method is attached to the moesif WSGI middleware object to update the users profile or metadata in batch. The metadata field can be any custom data you want to set on the user. The user_id field is required.

update_users_batch = MoesifMiddleware(app, moesif_settings).update_users_batch([UserModel.from_dictionary({
        'user_id': '12345',
        'company_id': '67890',
        'metadata': {'email': 'abc@email.com', 'name': 'abcde', 'image': '123'}
    }), UserModel.from_dictionary({
        'user_id': '1234',
        'company_id': '6789',
        'metadata': {'email': 'abc@email.com', 'name': 'abcde', 'image': '123'}
    })])

Update Company

update_company method

A method is attached to the moesif WSGI middleware object to update the company profile or metadata. The metadata field can be any custom data you want to set on the company. The company_id field is required.

update_company = MoesifMiddleware(app, moesif_settings).update_company({
        'company_id': '12345',
        'company_domain': 'acmeinc.com',
        'metadata': {'email': 'abc@email.com', 'name': 'abcde', 'image': '123'},
        'campaign': {'utm_source': 'Adwords', 'utm_medium': 'Twitter'}
    })

update_companies_batch method

A method is attached to the moesif WSGI middleware object to update the companies profile or metadata in batch. The metadata field can be any custom data you want to set on the company. The company_id field is required.

update_companies_batch = MoesifMiddleware(app, moesif_settings).update_companies_batch([CompanyModel.from_dictionary({
        'company_id': '12345',
        'company_domain': 'nowhere.com',
        'metadata': {'email': 'abc@email.com', 'name': 'abcde', 'image': '123'}
    }), CompanyModel.from_dictionary({
        'company_id': '67890',
        'company_domain': 'acmeinc.com',
        'metadata': {'email': 'abc@email.com', 'name': 'abcde', 'image': '123'}
    })])

Other integrations

To view more documentation on integration options, please visit the Integration Options Documentation.

Project details


Download files

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

Source Distribution

moesifwsgi-1.2.2.tar.gz (20.6 kB view details)

Uploaded Source

Built Distribution

moesifwsgi-1.2.2-py2.py3-none-any.whl (18.4 kB view details)

Uploaded Python 2 Python 3

File details

Details for the file moesifwsgi-1.2.2.tar.gz.

File metadata

  • Download URL: moesifwsgi-1.2.2.tar.gz
  • Upload date:
  • Size: 20.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.32.2 CPython/3.7.5

File hashes

Hashes for moesifwsgi-1.2.2.tar.gz
Algorithm Hash digest
SHA256 1f43c95c538926a02ec64f0f53c7f526cdf6ed2155ccd0b64e5f8a2d191f31ac
MD5 1b1ec108261e8e6ad163e0025d5dea65
BLAKE2b-256 35a0e1176a05179215a6f5562fbd677b22ee8c1c89226c2483fc358fc1d1c311

See more details on using hashes here.

Provenance

File details

Details for the file moesifwsgi-1.2.2-py2.py3-none-any.whl.

File metadata

  • Download URL: moesifwsgi-1.2.2-py2.py3-none-any.whl
  • Upload date:
  • Size: 18.4 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.32.2 CPython/3.7.5

File hashes

Hashes for moesifwsgi-1.2.2-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 a8fbb634886cafb30274ae5724a3626d17a5705ade1f382202246d46f7d09301
MD5 b8e87a73dd0ff9f31791a62efd1f535f
BLAKE2b-256 11c78a73b1424acd1b80dd2cca2df32dfa934c86f4a5da030ca149e15f222c60

See more details on using hashes here.

Provenance

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page