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.

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.0.tar.gz (20.1 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.0-py2.py3-none-any.whl (18.6 kB view details)

Uploaded Python 2Python 3

File details

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

File metadata

  • Download URL: moesiftornado-0.1.0.tar.gz
  • Upload date:
  • Size: 20.1 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.0.tar.gz
Algorithm Hash digest
SHA256 d059a2a4430381739e3012f84d99e74ec485e10cc1748855c7df982260aef0f5
MD5 123fdac192c5a9cbba1423c1c0ab8c6f
BLAKE2b-256 3d883eae80006e14450d0f14c7ab5b0fae8864fb56a5e7b6b29d2c942159b4e1

See more details on using hashes here.

File details

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

File metadata

  • Download URL: moesiftornado-0.1.0-py2.py3-none-any.whl
  • Upload date:
  • Size: 18.6 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.0-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 d439205b67eb786769216e68ad67d980ad86664e177d9ff6376d8abcf8ed851d
MD5 fe551192616f7385d0f5ae8f63651033
BLAKE2b-256 957980c6243872951089829c66426be5edf4744ea45d6d8b00c7ba48184f9a17

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