Skip to main content

Moesif Middleware for Python Tornado based platforms

Project description

Moesif Middleware for Python Tornado based Frameworks

Built For Latest Version Language Versions Software License Source Code

Tornado middleware that automatically logs incoming API calls and sends to Moesif for API analytics and monitoring. Supports Python Frameworks built on Tornado.

Source Code on GitHub

How to install

pip install moesiftornado

How to use

from moesiftornado import MoesifMiddleware
import tornado.web
import json

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write(json.dumps({ "msg": "Hello, world" }))

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

# Create a moesif middleware
middleware = MoesifMiddleware(moesif_config)
# Set the log_function to middleware.log_event to log the events to Moesif
application = tornado.web.Application([(r"/", MainHandler)], log_function=middleware.log_event)

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 API Keys.

Configuration options

APPLICATION_ID

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

SKIP

(optional) (handler) => boolean, a function that takes a Request handler, and returns true if you want to skip this particular event.

IDENTIFY_USER

(optional, but highly recommended) (handler) => string, a function that takes a Request handler, 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) (handler) => string, a function that takes a Request handler, and returns a string that is the company id for this event.

GET_METADATA

(optional) (handler) => dictionary, a function that takes a Request handler, 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) (handler) => string, a function that takes a Request handler, 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 helpful 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.

BATCH_SIZE

(optional) int, default 25, Maximum batch size when sending to Moesif.

AUTHORIZATION_HEADER_NAME

(optional) string, A request header field name used to identify the User in Moesif. Default value is authorization. Also, supports a comma separated string. We will check headers in order like "X-Api-Key,Authorization".

AUTHORIZATION_USER_ID_FIELD

(optional) string, A field name used to parse the User from authorization header in Moesif. Default value is sub.

Example:

from moesiftornado import MoesifMiddleware
import tornado.web

def identify_user(handler):
    # Your custom code that returns a user id string
    return "my_user_id"

def identify_company(handler):
    # Your custom code that returns a company id string
    return "my_company_id"

def get_token(handler):
    # Your custom code that returns a string for session/API token
    return "XXXXXXXXXXXXXX"

def should_skip(handler):
    # Your custom code that returns true to skip logging
    return "health/probe" in handler.request.full_url()

def mask_event(event_model):
    # Your custom code to change or remove any sensitive fields
    if 'password' in event_model.request.body:
        event_model.request.body['password'] = None
    return event_model

def get_metadata(handler):
    return {
        'datacenter': 'westus',
        'deployment_version': 'v1.2.3',
    }

moesif_config = {
    'APPLICATION_ID': 'Your Moesif Application Id',
    'LOG_BODY': True,
    'DEBUG': False,
    'IDENTIFY_USER': identify_user,
    'IDENTIFY_COMPANY': identify_company,
    'GET_SESSION_TOKEN': get_token,
    'SKIP': should_skip,
    'MASK_EVENT_MODEL': mask_event,
    'GET_METADATA': get_metadata,
}

middleware = MoesifMiddleware(moesif_config)
application = tornado.web.Application([(r"/", MainHandler)], log_function=middleware.log_event)

Update User

Update A Single User

Create or update a user profile in Moesif. The metadata field can be any customer demographic or other info you want to store. Only the user_id field is required. For details, visit the Python API Reference.

from moesiftornado import MoesifMiddleware
middleware = MoesifMiddleware(moesif_config)

# Only user_id is required.
# Campaign object is optional, but useful if you want to track ROI of acquisition channels
# See https://www.moesif.com/docs/api#users for campaign schema
# metadata can be any custom object
user_profile = {
  'user_id': '12345',
  'company_id': '67890', # If set, associate user with a company object
  'campaign': {
    'utm_source': 'google',
    'utm_medium': 'cpc', 
    'utm_campaign': 'adwords',
    'utm_term': 'api+tooling',
    'utm_content': 'landing'
  },
  'metadata': {
    'email': 'john@acmeinc.com',
    'first_name': 'John',
    'last_name': 'Doe',
    'title': 'Software Engineer',
    'sales_info': {
        'stage': 'Customer',
        'lifetime_value': 24000,
        'account_owner': 'mary@contoso.com'
    },
  }
}

middleware.update_user(user_profile)

Update Users in Batch

Similar to update_user, but used to update a list of users in one batch. Only the user_id field is required. For details, visit the Python API Reference.

from moesiftornado import MoesifMiddleware
middleware = MoesifMiddleware(moesif_config)

userA = {
  'user_id': '12345',
  'company_id': '67890', # If set, associate user with a company object
  'metadata': {
    'email': 'john@acmeinc.com',
    'first_name': 'John',
    'last_name': 'Doe',
    'title': 'Software Engineer',
    'sales_info': {
        'stage': 'Customer',
        'lifetime_value': 24000,
        'account_owner': 'mary@contoso.com'
    },
  }
}

userB = {
  'user_id': '54321',
  'company_id': '67890', # If set, associate user with a company object
  'metadata': {
    'email': 'mary@acmeinc.com',
    'first_name': 'Mary',
    'last_name': 'Jane',
    'title': 'Software Engineer',
    'sales_info': {
        'stage': 'Customer',
        'lifetime_value': 48000,
        'account_owner': 'mary@contoso.com'
    },
  }
}
middleware.update_users_batch([userA, userB])

Update Company

Update A Single Company

Create or update a company profile in Moesif. The metadata field can be any company demographic or other info you want to store. Only the company_id field is required. For details, visit the Python API Reference.

from moesiftornado import MoesifMiddleware
middleware = MoesifMiddleware(moesif_config)

# Only company_id is required.
# Campaign object is optional, but useful if you want to track ROI of acquisition channels
# See https://www.moesif.com/docs/api#update-a-company for campaign schema
# metadata can be any custom object
company_profile = {
  'company_id': '67890',
  'company_domain': 'acmeinc.com', # If domain is set, Moesif will enrich your profiles with publicly available info 
  'campaign': {
    'utm_source': 'google',
    'utm_medium': 'cpc', 
    'utm_campaign': 'adwords',
    'utm_term': 'api+tooling',
    'utm_content': 'landing'
  },
  'metadata': {
    'org_name': 'Acme, Inc',
    'plan_name': 'Free',
    'deal_stage': 'Lead',
    'mrr': 24000,
    'demographics': {
        'alexa_ranking': 500000,
        'employee_count': 47
    },
  }
}

middleware.update_company(company_profile)

Update Companies in Batch

Similar to update_company, but used to update a list of companies in one batch. Only the company_id field is required. For details, visit the Python API Reference.

from moesiftornado import MoesifMiddleware
middleware = MoesifMiddleware(moesif_config)

companyA = {
  'company_id': '67890',
  'company_domain': 'acmeinc.com', # If domain is set, Moesif will enrich your profiles with publicly available info 
  'metadata': {
    'org_name': 'Acme, Inc',
    'plan_name': 'Free',
    'deal_stage': 'Lead',
    'mrr': 24000,
    'demographics': {
        'alexa_ranking': 500000,
        'employee_count': 47
    },
  }
}

companyB = {
  'company_id': '09876',
  'company_domain': 'contoso.com', # If domain is set, Moesif will enrich your profiles with publicly available info 
  'metadata': {
    'org_name': 'Contoso, Inc',
    'plan_name': 'Free',
    'deal_stage': 'Lead',
    'mrr': 48000,
    'demographics': {
        'alexa_ranking': 500000,
        'employee_count': 53
    },
  }
}
middleware.update_companies_batch([companyA, companyB])

Tested versions

Moesif has validated moesiftornado against the following combinations.

Python Tornado
Python 2.7 4.4.1

Example

An example Moesif integration based on quick start tutorial of Tornado: Moesif Tornado Example

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

moesiftornado-0.1.4.tar.gz (21.9 kB view details)

Uploaded Source

Built Distribution

moesiftornado-0.1.4-py2.py3-none-any.whl (20.3 kB view details)

Uploaded Python 2 Python 3

File details

Details for the file moesiftornado-0.1.4.tar.gz.

File metadata

  • Download URL: moesiftornado-0.1.4.tar.gz
  • Upload date:
  • Size: 21.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.15.0 pkginfo/1.5.0.1 requests/2.20.0 setuptools/41.4.0 requests-toolbelt/0.9.1 tqdm/4.36.1 CPython/2.7.16

File hashes

Hashes for moesiftornado-0.1.4.tar.gz
Algorithm Hash digest
SHA256 456e5e3c4ec54c2ea6a8e843079c48b8d7143a23c0006755c705680672b3904c
MD5 9b34d4d3aa8fac947039596af56e54b8
BLAKE2b-256 5e5dead1782f70ca916b1db2b5e78a9103731395fb5cc01b99694f4b51ab863e

See more details on using hashes here.

File details

Details for the file moesiftornado-0.1.4-py2.py3-none-any.whl.

File metadata

  • Download URL: moesiftornado-0.1.4-py2.py3-none-any.whl
  • Upload date:
  • Size: 20.3 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.15.0 pkginfo/1.5.0.1 requests/2.20.0 setuptools/41.4.0 requests-toolbelt/0.9.1 tqdm/4.36.1 CPython/2.7.16

File hashes

Hashes for moesiftornado-0.1.4-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 308be9290e549d27c56ab3e03dcf8e5c8be79766d72c39ab1357d75c3d48eec4
MD5 833f7a66a878f9352ab8c5167335e525
BLAKE2b-256 855ca3fdd986861b2b8013c884dd0babb5d877c7c7f5f6df6bcc1ec579d051c2

See more details on using hashes here.

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