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.1.tar.gz (21.8 kB view details)

Uploaded Source

Built Distribution

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

moesiftornado-0.1.1-py2.py3-none-any.whl (19.8 kB view details)

Uploaded Python 2Python 3

File details

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

File metadata

  • Download URL: moesiftornado-0.1.1.tar.gz
  • Upload date:
  • Size: 21.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.6.1 requests/2.20.0 setuptools/50.3.1.post20201107 requests-toolbelt/0.9.1 tqdm/4.50.2 CPython/3.8.5

File hashes

Hashes for moesiftornado-0.1.1.tar.gz
Algorithm Hash digest
SHA256 c531aeeb4aed560989d883abb75d89f4795968c43b4edde7d4912b43236d39df
MD5 52d7e594c717a8feaeb24fe483b56b8f
BLAKE2b-256 c96e2ebd1912465d36040dfc499d299109ea79ad053cf251ddc5a17d7805e521

See more details on using hashes here.

File details

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

File metadata

  • Download URL: moesiftornado-0.1.1-py2.py3-none-any.whl
  • Upload date:
  • Size: 19.8 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.6.1 requests/2.20.0 setuptools/50.3.1.post20201107 requests-toolbelt/0.9.1 tqdm/4.50.2 CPython/3.8.5

File hashes

Hashes for moesiftornado-0.1.1-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 6e44ef58bfa93f58f90163268841a9745a4e40d8b83ac94a759473316f0bc13b
MD5 39015cfc1a17fc297794c086ae45a818
BLAKE2b-256 fe2cf58fd186b862ccee3ad5bc9782b7b2db8f5a9972f07670a044a44779bda6

See more details on using hashes here.

Supported by

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