moesifdjango


Namemoesifdjango JSON
Version 2.3.11 PyPI version JSON
download
home_pagehttps://www.moesif.com/docs/server-integration/django/
SummaryMoesif Middleware for Python Django
upload_time2024-10-31 21:00:24
maintainerNone
docs_urlhttps://pythonhosted.org/moesifdjango/
authorMoesif, Inc
requires_pythonNone
licenseApache Software License
keywords log analysis restful api development debug
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Moesif Middleware for Python Django
by [Moesif](https://moesif.com), the [API analytics](https://www.moesif.com/features/api-analytics) and [API monetization](https://www.moesif.com/solutions/metered-api-billing) platform.

[![Built For][ico-built-for]][link-built-for]
[![Latest Version][ico-version]][link-package]
[![Language Versions][ico-language]][link-language]
[![Software License][ico-license]][link-license]
[![Source Code][ico-source]][link-source]

Moesif middleware for Django automatically logs incoming and outgoing API calls 
and sends them to [Moesif](https://www.moesif.com) for API analytics and monitoring.

This SDK uses the Requests library and works for Python versions 2.7 up to 3.10.4.

> If you're new to Moesif, see [our Getting Started](https://www.moesif.com/docs/) resources to quickly get up and running.

## Prerequisites
Before using this middleware, make sure you have the following:

- [An active Moesif account](https://moesif.com/wrap)
- [A Moesif Application ID](#get-your-moesif-application-id)

### Get Your Moesif Application ID
After you log into [Moesif Portal](https://www.moesif.com/wrap), you can get your Moesif Application ID during the onboarding steps. You can always access the Application ID any time by following these steps from Moesif Portal after logging in:

1. Select the account icon to bring up the settings menu.
2. Select **Installation** or **API Keys**.
3. Copy your Moesif Application ID from the **Collector Application ID** field.
<img class="lazyload blur-up" src="images/app_id.png" width="700" alt="Accessing the settings menu in Moesif Portal">

## Install the Middleware

Install with pip:

```shell
pip install moesifdjango
```

## Configure the Middleware
See the available [configuration options](#configuration-options) to learn how to configure the middleware for your use case.

## How to Use

In your [Django settings file](https://docs.djangoproject.com/en/4.0/topics/settings/#default-settings), add `moesifdjango.middleware.moesif_middleware`
to the [`MIDDLEWARE` array](https://docs.djangoproject.com/en/4.0/topics/http/middleware/#activating-middleware):

```python
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'moesifdjango.middleware.moesif_middleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
```

Because of [middleware execution order](https://docs.djangoproject.com/en/4.0/ref/middleware/#middleware-ordering), we highly recommend that you add `moesif_middleweare` _after_ `SessionMiddleware` and `AuthenticationMiddleware`. These Django middleware add useful session data that enables deeper error analysis. On the other hand, if you have other middleware that modifies responses before going out, you may choose to place Moesif middleware before the middleware that modifies responses. This allows Moesif to see the modifications to the response data and see closer to what goes over the wire.

### Changes in Django 1.10

Django middleware style and setup was refactored in version 1.10. You need need to import the correct version of Moesif middleware depending on your Django version:

- For Django 1.10 or greater, use `moesifdjango.middleware.moesif_middleware`.
- For Django 1.9 or older, you need to follow the legacy style for importing middleware and use `moesifdjango.middleware_pre19.MoesifMiddlewarePre19` instead.

To find your current Django version, you can execute the following command in your terminal:

```sh
python -c "import django; print(django.get_version())"
```

### Django 1.10 or Newer

Django 1.10 renamed `MIDDLEWARE_CLASSES` to `MIDDLEWARE.` Therefore, for Django 1.10 or newer, you must [activate your middleware](https://docs.djangoproject.com/en/4.0/topics/http/middleware/#activating-middleware) by adding it to the `MIDDLEWARE` list:

```python
MIDDLEWARE = [
    ...,
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'moesifdjango.middleware.moesif_middleware'
    ...
]
```

Then add a dictionary `MOESIF_MIDDLEWARE` to your Django settings file: 

```
MOESIF_MIDDLEWARE = {
    'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID',
    'LOG_BODY': True,
}
```

### Django 1.9 or Older

[Activate the middleware](https://docs.djangoproject.com/en/1.8/topics/http/middleware/#activating-middleware) by adding it to the `MIDDLEWARE_CLASSES` list in your Django settings file:

```
MIDDLEWARE_CLASSES = [
    ...,
    'moesifdjango.middleware_pre19.MoesifMiddlewarePre19',
    # other middlewares
]
```

Then add a dictionary `MOESIF_MIDDLEWARE` to your Django settings file: 
```

MOESIF_MIDDLEWARE = {
    'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID',
    'LOG_BODY': True,
}
```

The dictionary contains the [configuration options](#configuration-options) for 
the middleware, including your [Moesif Application ID](#get-your-moesif-application-id) that you must specify.

### Optional: Capturing Outgoing API Calls
In addition to your own APIs, you can also start capturing calls out to third party services through by setting the [`CAPTURE_OUTGOING_REQUESTS` option](#capture_outgoing_requests).

For configuration options specific to capturing outgoing API calls, see [Options For Outgoing API Calls](#options-for-outgoing-api-calls).

## Troubleshoot
For a general troubleshooting guide that can help you solve common problems, see [Server Troubleshooting Guide](https://www.moesif.com/docs/troubleshooting/server-troubleshooting-guide/).

Other troubleshooting supports:

- [FAQ](https://www.moesif.com/docs/faq/)
- [Moesif support email](mailto:support@moesif.com)

### Solve Timezone Issue with Docker
When using Docker with Ubuntu-based image, events may not be captured if the image fails to find any timezone configuration. To solve this issue, add the following line to your Dockerfile:

```
ENV TZ=UTC
```

Otherwise, you can add `RUN apt-get install tzdata` in the Dockerfile.

## Repository Structure

```
.
├── BUILDING.md
├── images/
├── LICENSE
├── MANIFEST.in
├── moesifdjango/
├── pull_request_template.md
├── README.md
├── requirements.txt
├── setup.cfg
├── setup.py
└── tests/
```

## Configuration options
The following sections describe the available configuration options for this middleware. You have to set these options in a Python dictionary `MOESIF_MIDDLEWARE`. See the [examples](#examples) for better understanding.

#### `APPLICATION_ID` (Required)
<table>
  <tr>
   <th scope="col">
    Data type
   </th>
  </tr>
  <tr>
   <td>
    String
   </td>
  </tr>
</table>

A string that [identifies your application in Moesif](#get-your-moesif-application-id).

### Options specific to Incoming API Calls
The following options document the configuration options to use for incoming API calls.

Several options use request and response as input arguments. These correspond to [Django's request and response objects](https://docs.djangoproject.com/en/1.10/ref/request-response/).

#### `SKIP`
<table>
  <tr>
   <th scope="col">
    Data type
   </th>
   <th scope="col">
    Parameters
   </th>
   <th scope="col">
    Return type
   </th>
  </tr>
  <tr>
   <td>
    Function
   </td>
   <td>
    <code>(request, response)</code>
   </td>
   <td>
    Boolean
   </td>
  </tr>
</table>

Optional.

This function takes Requests [`Request` and `Response` objects](https://requests.readthedocs.io/en/latest/user/advanced/#request-and-response-objects) and returns `True` if you want to skip this particular event.

#### `IDENTIFY_USER`
<table>
  <tr>
   <th scope="col">
    Data type
   </th>
   <th scope="col">
    Parameters
   </th>
   <th scope="col">
    Return type
   </th>
  </tr>
  <tr>
   <td>
    Function
   </td>
   <td>
    <code>(request, response)</code>
   </td>
   <td>
    String
   </td>
  </tr>
</table>

Optional, but highly recommended.

This function takes a request and a response and returns a string that represents 
the user ID used by your system.

Moesif tries to identify users automatically and fetch the username from [`django.http.HttpRequest.user`](https://docs.djangoproject.com/en/1.8/ref/request-response/#django.http.HttpRequest.user). However, if implementation differs, we highly recommend that you accurately provide a 
user ID using this function.

#### `IDENTIFY_COMPANY`
<table>
  <tr>
   <th scope="col">
    Data type
   </th>
   <th scope="col">
    Parameters
   </th>
   <th scope="col">
    Return type
   </th>
  </tr>
  <tr>
   <td>
    Function
   </td>
   <td>
    <code>(request, response)</code>
   </td>
   <td>
    String
   </td>
  </tr>
</table>

Optional.

A function that takes a request and a response and returns a string that represents the company ID for this event.

#### `GET_SESSION_TOKEN`
<table>
  <tr>
   <th scope="col">
    Data type
   </th>
   <th scope="col">
    Parameters
   </th>
   <th scope="col">
    Return type
   </th>
  </tr>
  <tr>
   <td>
    Function
   </td>
   <td>
    <code>(request, response)</code>
   </td>
   <td>
    String
   </td>
  </tr>
</table>

Optional. 

A function that takes a request and a response, and returns a string that represents the session token for this event. 

Similar to [user IDs](#identify_user), Moesif tries to get the session token automatically. However, if you setup differs from the standard, this function can help tying up events together and help you replay the events.

#### `GET_METADATA`
<table>
  <tr>
   <th scope="col">
    Data type
   </th>
   <th scope="col">
    Parameters
   </th>
   <th scope="col">
    Return type
   </th>
  </tr>
  <tr>
   <td>
    Function
   </td>
   <td>
    <code>(request, response)</code>
   </td>
   <td>
    Dictionary
   </td>
  </tr>
</table>

Optional.

A function that takes a request and a response and returns a Python dictionary.

The dictionary must be such that it can be converted into valid JSON. This allows you to associate this event with custom metadata. For example, you may want to save a virtual machine instance ID, a trace ID, or a tenant ID with the request.

#### `LOG_BODY`
<table>
  <tr>
   <th scope="col">
    Data type
   </th>
   <th scope="col">
    Default
   </th>
  </tr>
  <tr>
   <td>
    <code>Boolean</code>
   </td>
   <td>
    <code>True</code>
   </td>
  </tr>
</table>

Optional.

Whether to log request and response body to Moesif.

Set to `False` to remove the HTTP body before sending to Moesif. 

If you want more control over which fields the middleware includes or not, see the next option `MASK_EVENT_MODEL`.

#### `MASK_EVENT_MODEL`
<table>
  <tr>
   <th scope="col">
    Data type
   </th>
   <th scope="col">
    Parameters
   </th>
   <th scope="col">
    Return type
   </th>
  </tr>
  <tr>
   <td>
    Function
   </td>
   <td>
    <code>(EventModel)</code>
   </td>
   <td>
    <code>EventModel</code>
   </td>
  </tr>
</table>

Optional.

A function that takes the final Moesif event model and returns an `EventModel` object with desired data removed. 

Use this if you prefer to write your own mask function than uses the string based filter options: 

- `REQUEST_BODY_MASKS`
- `REQUEST_HEADER_MASKS`
- `RESPONSE_BODY_MASKS`
- `RESPONSE_HEADER_MASKS`

The return value must be a valid `EventModel` required by Moesif data ingestion API. For more information about Moesif event model, see [Moesif Python API documentation](https://www.moesif.com/docs/api?python).

#### `BATCH_SIZE`
<table>
  <tr>
   <th scope="col">
    Data type
   </th>
   <th scope="col">
    Default
   </th>
  </tr>
  <tr>
   <td>
    <code>int</code>
   </td>
   <td>
    <code>25</code>
   </td>
  </tr>
</table>

Optional.

Specifies the maximum batch size when sending to Moesif.

#### `EVENT_QUEUE_SIZE`
<table>
  <tr>
   <th scope="col">
    Data type
   </th>
   <th scope="col">
    Default
   </th>
  </tr>
  <tr>
   <td>
    <code>int</code>
   </td>
   <td>
    <code>1000_000</code>
   </td>
  </tr>
</table>

Optional.

The maximum number of events to hold in queue before sending to Moesif. 

In case of network issues, the middleware may fail to connect or send event to Moesif. In those cases, the middleware skips adding new to event to queue to prevent memory overflow.

#### `AUTHORIZATION_HEADER_NAME`
<table>
  <tr>
   <th scope="col">
    Data type
   </th>
   <th scope="col">
    Default 
   </th>
  </tr>
  <tr>
   <td>
    String
   </td>
   <td>
    <code>authorization</code>
   </td>
  </tr>
</table>

Optional.

A request header field name used to identify the User in Moesif. It also supports a comma separated string. Moesif checks headers in order like `"X-Api-Key,Authorization"`.

#### `AUTHORIZATION_USER_ID_FIELD`
<table>
  <tr>
   <th scope="col">
    Data type
   </th>
   <th scope="col">
    Default 
   </th>
  </tr>
  <tr>
   <td>
    String
   </td>
   <td>
    <code>sub</code>
   </td>
  </tr>
</table>

Optional.

A field name used to parse the user from authorization header in Moesif.

#### `BASE_URI`
<table>
  <tr>
   <th scope="col">
    Data type
   </th>
  </tr>
  <tr>
   <td>
    String
   </td>
  </tr>
</table>

Optional.

A local proxy hostname when sending traffic through secure proxy. Remember to set this field when using secure proxy. For more information, see [Secure Proxy documentation.](https://www.moesif.com/docs/platform/secure-proxy/#2-configure-moesif-sdk).

### Options For Outgoing API Calls 

The following options apply to outgoing API calls. These are calls you initiate using the Python [Requests](http://docs.python-requests.org/en/master/) library to third parties like Stripe or to your own services.

Several options use request and response as input arguments. These correspond to the [Requests](http://docs.python-requests.org/en/master/api/) library's request or response objects.

If you are not using Django, you can import [`moesifpythonrequest`](https://github.com/Moesif/moesifpythonrequest) directly.

#### `CAPTURE_OUTGOING_REQUESTS`
<table>
  <tr>
   <th scope="col">
    Data type
   </th>
   <th scope="col">
    Default 
   </th>
  </tr>
  <tr>
   <td>
    Boolean
   </td>
   <td>
    <code>False</code>
   </td>
  </tr>
</table>

Set to `True` to capture all outgoing API calls.

##### `GET_METADATA_OUTGOING`
<table>
  <tr>
   <th scope="col">
    Data type
   </th>
   <th scope="col">
    Parameters
   </th>
   <th scope="col">
    Return type
   </th>
  </tr>
  <tr>
   <td>
    Function
   </td>
   <td>
    <code>(req, res)</code>
   </td>
   <td>
    Dictionary
   </td>
  </tr>
</table>

Optional.

A function that enables you to return custom metadata associated with the logged API calls.

Takes in the [Requests](http://docs.python-requests.org/en/master/api/) request and response objects as arguments. 

We recommend that you implement a function that
returns a dictionary containing your custom metadata. The dictionary must be a valid one that can be encoded into JSON. For example, you may want to save a virtual machine instance ID, a trace ID, or a resource ID with the request.

##### `SKIP_OUTGOING`
<table>
  <tr>
   <th scope="col">
    Data type
   </th>
   <th scope="col">
    Parameters
   </th>
   <th scope="col">
    Return type
   </th>
  </tr>
  <tr>
   <td>
    Function
   </td>
   <td>
    <code>(req, res)</code>
   </td>
   <td>
    Boolean
   </td>
  </tr>
</table>

Optional.

A function that takes a [Requests](http://docs.python-requests.org/en/master/api/) request and response objects,
and returns `True` if you want to skip this particular event.

##### `IDENTIFY_USER_OUTGOING`
<table>
  <tr>
   <th scope="col">
    Data type
   </th>
   <th scope="col">
    Parameters
   </th>
   <th scope="col">
    Return type
   </th>
  </tr>
  <tr>
   <td>
    Function
   </td>
   <td>
    <code>(req, res)</code>
   </td>
   <td>
    String
   </td>
  </tr>
</table>

Optional, but highly recommended.

A function that takes [Requests](http://docs.python-requests.org/en/master/api/) request and response objects, and returns a string that represents the user ID used by your system. 

While Moesif tries to identify users automatically, different frameworks and your implementation might vary. So we highly recommend that you accurately provide a 
user ID using this function.

##### `IDENTIFY_COMPANY_OUTGOING`
<table>
  <tr>
   <th scope="col">
    Data type
   </th>
   <th scope="col">
    Parameters
   </th>
   <th scope="col">
    Return type
   </th>
  </tr>
  <tr>
   <td>
    Function
   </td>
   <td>
    <code>(req, res)</code>
   </td>
   <td>
    String
   </td>
  </tr>
</table>

Optional.

A function that takes [Requests](http://docs.python-requests.org/en/master/api/) request and response objects and returns a string that represents the company ID for this event.

##### `GET_SESSION_TOKEN_OUTGOING`
<table>
  <tr>
   <th scope="col">
    Data type
   </th>
   <th scope="col">
    Parameters
   </th>
   <th scope="col">
    Return type
   </th>
  </tr>
  <tr>
   <td>
    Function
   </td>
   <td>
    <code>(req, res)</code>
   </td>
   <td>
    String
   </td>
  </tr>
</table>

Optional.

A function that takes [Requests](http://docs.python-requests.org/en/master/api/) request and response objects, and returns a string that corresponds to the session token for this event. 

Similar to [user IDs](#identify_user_outgoing), Moesif tries to get the session token automatically. However, if you setup differs from the standard, this function can help tying up events together and help you replay the events.

### General options
#### `LOG_BODY_OUTGOING`
<table>
  <tr>
   <th scope="col">
    Data type
   </th>
   <th scope="col">
    Default
   </th>
  </tr>
  <tr>
   <td>
    Boolean
   </td>
   <td>
    <code>True</code>
   </td>
  </tr>
</table>

Optional.

Set to `False` to remove logging request and response body.

#### `LOCAL_DEBUG`
<table>
  <tr>
   <th scope="col">
    Data type
   </th>
  </tr>
  <tr>
   <td>
    Boolean
   </td>
  </tr>
</table>

Optional.

Set to `True` to print internal log messages for debugging SDK integration issues.

## Examples
See the [Moesif Django Example](https://github.com/Moesif/moesifdjangoexample) for a complete Django application that uses this middleware.

The following shows a sample Django settings file with different configuration options.

```python
def identify_user(req, res):
    # Your custom code that returns a user id string
    if req.user and req.user.is_authenticated:
        return req.user.username
    else:
        return None

def identify_company(req, res):
    # Your custom code that returns a company id string
    return "67890"

def should_skip(req, res):
    # Your custom code that returns true to skip logging
    return "health/probe" in req.path

def get_token(req, res):
    # If you don't want to use the standard Django session token,
    # add your custom code that returns a string for session/API token
    return "XXXXXXXXXXXXXX"

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

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


MOESIF_MIDDLEWARE = {
    'APPLICATION_ID': 'Your application id',
    'LOCAL_DEBUG': False,
    'LOG_BODY': True,
    '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,
}
```

The following examples demonstrate how to add and update customer information using the middleware.

### Update A Single User
To create or update a [user](https://www.moesif.com/docs/getting-started/users/) profile in Moesif, use the `update_user()` method.

```python
middleware = MoesifMiddleware(None)

# 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 = {
  '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'
    },
  }
}

update_user = middleware.update_user(user)
```

The `metadata` field can contain any customer demographic or other info you want to store. Moesif only requires the `user_id` field. This method is a convenient helper that calls the Moesif API library.

For more information, see [Moesif Python API reference](https://www.moesif.com/docs/api?python#update-a-user).

### Update Users in Batch
To update a list of [users](https://www.moesif.com/docs/getting-started/users/) in one batch, use the `update_users_batch()` method.

```python
middleware = MoesifMiddleware(None)

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'
    },
  }
}
update_users = middleware.update_users_batch([userA, userB])
```

The `metadata` field can contain any customer demographic or other info you want to store. Moesif only requires the `user_id` field. This method is a convenient helper that calls the Moesif API library.

For more information, see [Moesif Python API reference](https://www.moesif.com/docs/api?python#update-users-in-batch).

### Update A Single Company
To update a single [company](https://www.moesif.com/docs/getting-started/companies/), use the `update_company()` method.

```python
middleware = MoesifMiddleware(None)

# 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 = {
  '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
    },
  }
}

update_company = middleware.update_company(company)
```

The `metadata` field can contain any company demographic or other info you want to store. Moesif only requires the `company_id` field. This method is a convenient helper that calls the Moesif API library.

For more information, see [Moesif Python API reference](https://www.moesif.com/docs/api?python#update-a-company).

### Update Companies in Batch
To update a list of [companies](https://www.moesif.com/docs/getting-started/companies/) in one batch, use the `update_companies_batch()` method.

```python
middleware = MoesifMiddleware(None)

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
    },
  }
}

update_companies = middleware.update_companies_batch([userA, userB])
```

The `metadata` field can contain any company demographic or other info you want to store. Moesif only requires the `company_id` field. This method is a convenient helper that calls the Moesif API library.

For more information, see [Moesif Python API reference](https://www.moesif.com/docs/api?python#update-companies-in-batch).

### Update Subscription

#### Update A Single Subscription
To create or update a subscription in Moesif, use the `update_subscription` method.

```python
middleware = MoesifMiddleware(None)

# Only subscription_id is required.
# metadata can be any custom object
subscription = {
  'subscription_id': 'sub_67890',
  'company_id': '3456',
  'status': 'active'
  'metadata': {
    'plan_name': 'Pro',
    'signup_date': '2020-09-09',
    'expiration_date': '2021-09-09',
    'payment_method': 'credit_card',
    'mrr': 12000,
    'currency': 'USD'
  }
}

update_subscription = middleware.update_subscription(subscription)
```

The `metadata` field can store any subscription-related information. Moesif only requires the the following fields: 

- `subscription_id`
- `company_id`
- `status` 

This method is a convenient helper that calls the Moesif API library. 

For more information, see [Moesif Python API reference](https://www.moesif.com/docs/api?python#update-a-subscription).

### Update Subscriptions in Batch
To update a list of subscriptions in one batch, use the `update_subscriptions_batch` method.

```python
middleware = MoesifMiddleware(None)

subscriptionA = {
  'subscription_id': 'sub_67890',
  'company_id': '3456',
  'status': 'active'
  'metadata': {
    'plan_name': 'Pro',
    'signup_date': '2020-09-09',
    'expiration_date': '2021-09-09',
    'payment_method': 'credit_card',
    'mrr': 12000,
    'currency': 'USD'
  }
}

subscriptionB = {
  'subscription_id': 'sub_54321',
  'company_id': '6789',
  'status': 'active'
  'metadata': {
    'plan_name': 'Enterprise',
    'signup_date': '2020-10-01',
    'expiration_date': '2021-10-01',
    'payment_method': 'paypal',
    'mrr': 24000,
    'currency': 'USD'
  }
}

update_subscriptions = middleware.update_subscriptions_batch([subscriptionA, subscriptionB])
```

The `metadata` field can store any subscription-related information. Moesif only requires the the following fields: 

- `subscription_id`
- `company_id`
- `status` 

This method is a convenient helper that calls the Moesif API library.  

For more information, see [Moesif Python API reference](https://www.moesif.com/docs/api?python#update-subscriptions-in-batch).

## Tested Python and Django Versions

Moesif has validated this middleware against the following combinations of Python and Django versions:

| Python        | Django     | 
| ------------  | -------    | 
| Python 2.7    | 1.11.22    | 
| Python 2.7    | 1.11.22    | 
| Python 2.7    | 1.9        | 
| Python 3.4.5  | 1.11.22    | 
| Python 3.4.5  | 1.11.22    | 
| Python 3.4.5  | 1.9        | 
| Python 3.6.4  | 1.11.22    | 
| Python 3.6.4  | 1.11.22    | 
| Python 3.6.4  | 1.9        | 
| Python 3.10.4 | 3.2.13 LTS | 
| Python 3.10.4 | 4.0.5      |

## How to Test
1. Manually clone this repository.
2. From your terminal, navigate to the root directory of the middleware.
3. Run `pip install Django` and then run `pip install moesifdjango`.
4. Add your [Moesif Application ID](#get-your-moesif-application-id) to `tests/settings.py`.
5. From terminal, navigate to the root directory of the middleware tests `tests/`.
   
   a. Run `python manage.py test` if you are using Django 1.10 or newer.
   
   b. Run `python manage.py test middleware_pre19_tests` if you are using Django 1.9 or older.

## Explore Other Integrations

Explore other integration options from Moesif:

- [Server integration options documentation](https://www.moesif.com/docs/server-integration//)
- [Client integration options documentation](https://www.moesif.com/docs/client-integration/)

[ico-built-for]: https://img.shields.io/badge/built%20for-django-blue.svg
[ico-version]: https://img.shields.io/pypi/v/moesifdjango.svg
[ico-language]: https://img.shields.io/pypi/pyversions/moesifdjango.svg
[ico-license]: https://img.shields.io/badge/License-Apache%202.0-green.svg
[ico-source]: https://img.shields.io/github/last-commit/moesif/moesifdjango.svg?style=social

[link-built-for]: https://www.djangoproject.com/
[link-package]: https://pypi.python.org/pypi/moesifdjango
[link-language]: https://pypi.python.org/pypi/moesifdjango
[link-license]: https://raw.githubusercontent.com/Moesif/moesifdjango/master/LICENSE
[link-source]: https://github.com/Moesif/moesifdjango

            

Raw data

            {
    "_id": null,
    "home_page": "https://www.moesif.com/docs/server-integration/django/",
    "name": "moesifdjango",
    "maintainer": null,
    "docs_url": "https://pythonhosted.org/moesifdjango/",
    "requires_python": null,
    "maintainer_email": null,
    "keywords": "log analysis restful api development debug",
    "author": "Moesif, Inc",
    "author_email": "derric@moesif.com",
    "download_url": "https://files.pythonhosted.org/packages/cd/f1/fa77e60eca0ac12a4a3f234defe29418ae6992e26738e5a1b76a72397643/moesifdjango-2.3.11.tar.gz",
    "platform": null,
    "description": "# Moesif Middleware for Python Django\nby [Moesif](https://moesif.com), the [API analytics](https://www.moesif.com/features/api-analytics) and [API monetization](https://www.moesif.com/solutions/metered-api-billing) platform.\n\n[![Built For][ico-built-for]][link-built-for]\n[![Latest Version][ico-version]][link-package]\n[![Language Versions][ico-language]][link-language]\n[![Software License][ico-license]][link-license]\n[![Source Code][ico-source]][link-source]\n\nMoesif middleware for Django automatically logs incoming and outgoing API calls \nand sends them to [Moesif](https://www.moesif.com) for API analytics and monitoring.\n\nThis SDK uses the Requests library and works for Python versions 2.7 up to 3.10.4.\n\n> If you're new to Moesif, see [our Getting Started](https://www.moesif.com/docs/) resources to quickly get up and running.\n\n## Prerequisites\nBefore using this middleware, make sure you have the following:\n\n- [An active Moesif account](https://moesif.com/wrap)\n- [A Moesif Application ID](#get-your-moesif-application-id)\n\n### Get Your Moesif Application ID\nAfter you log into [Moesif Portal](https://www.moesif.com/wrap), you can get your Moesif Application ID during the onboarding steps. You can always access the Application ID any time by following these steps from Moesif Portal after logging in:\n\n1. Select the account icon to bring up the settings menu.\n2. Select **Installation** or **API Keys**.\n3. Copy your Moesif Application ID from the **Collector Application ID** field.\n<img class=\"lazyload blur-up\" src=\"images/app_id.png\" width=\"700\" alt=\"Accessing the settings menu in Moesif Portal\">\n\n## Install the Middleware\n\nInstall with pip:\n\n```shell\npip install moesifdjango\n```\n\n## Configure the Middleware\nSee the available [configuration options](#configuration-options) to learn how to configure the middleware for your use case.\n\n## How to Use\n\nIn your [Django settings file](https://docs.djangoproject.com/en/4.0/topics/settings/#default-settings), add `moesifdjango.middleware.moesif_middleware`\nto the [`MIDDLEWARE` array](https://docs.djangoproject.com/en/4.0/topics/http/middleware/#activating-middleware):\n\n```python\nMIDDLEWARE = [\n    'django.middleware.security.SecurityMiddleware',\n    'django.contrib.sessions.middleware.SessionMiddleware',\n    'django.middleware.common.CommonMiddleware',\n    'django.middleware.csrf.CsrfViewMiddleware',\n    'django.contrib.auth.middleware.AuthenticationMiddleware',\n    'moesifdjango.middleware.moesif_middleware',\n    'django.contrib.messages.middleware.MessageMiddleware',\n    'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n```\n\nBecause of [middleware execution order](https://docs.djangoproject.com/en/4.0/ref/middleware/#middleware-ordering), we highly recommend that you add `moesif_middleweare` _after_ `SessionMiddleware` and `AuthenticationMiddleware`. These Django middleware add useful session data that enables deeper error analysis. On the other hand, if you have other middleware that modifies responses before going out, you may choose to place Moesif middleware before the middleware that modifies responses. This allows Moesif to see the modifications to the response data and see closer to what goes over the wire.\n\n### Changes in Django 1.10\n\nDjango middleware style and setup was refactored in version 1.10. You need need to import the correct version of Moesif middleware depending on your Django version:\n\n- For Django 1.10 or greater, use `moesifdjango.middleware.moesif_middleware`.\n- For Django 1.9 or older, you need to follow the legacy style for importing middleware and use `moesifdjango.middleware_pre19.MoesifMiddlewarePre19` instead.\n\nTo find your current Django version, you can execute the following command in your terminal:\n\n```sh\npython -c \"import django; print(django.get_version())\"\n```\n\n### Django 1.10 or Newer\n\nDjango 1.10 renamed `MIDDLEWARE_CLASSES` to `MIDDLEWARE.` Therefore, for Django 1.10 or newer, you must [activate your middleware](https://docs.djangoproject.com/en/4.0/topics/http/middleware/#activating-middleware) by adding it to the `MIDDLEWARE` list:\n\n```python\nMIDDLEWARE = [\n    ...,\n    'django.contrib.sessions.middleware.SessionMiddleware',\n    'django.middleware.common.CommonMiddleware',\n    'django.contrib.auth.middleware.AuthenticationMiddleware',\n    'moesifdjango.middleware.moesif_middleware'\n    ...\n]\n```\n\nThen add a dictionary `MOESIF_MIDDLEWARE` to your Django settings file: \n\n```\nMOESIF_MIDDLEWARE = {\n    'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID',\n    'LOG_BODY': True,\n}\n```\n\n### Django 1.9 or Older\n\n[Activate the middleware](https://docs.djangoproject.com/en/1.8/topics/http/middleware/#activating-middleware) by adding it to the `MIDDLEWARE_CLASSES` list in your Django settings file:\n\n```\nMIDDLEWARE_CLASSES = [\n    ...,\n    'moesifdjango.middleware_pre19.MoesifMiddlewarePre19',\n    # other middlewares\n]\n```\n\nThen add a dictionary `MOESIF_MIDDLEWARE` to your Django settings file: \n```\n\nMOESIF_MIDDLEWARE = {\n    'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID',\n    'LOG_BODY': True,\n}\n```\n\nThe dictionary contains the [configuration options](#configuration-options) for \nthe middleware, including your [Moesif Application ID](#get-your-moesif-application-id) that you must specify.\n\n### Optional: Capturing Outgoing API Calls\nIn addition to your own APIs, you can also start capturing calls out to third party services through by setting the [`CAPTURE_OUTGOING_REQUESTS` option](#capture_outgoing_requests).\n\nFor configuration options specific to capturing outgoing API calls, see [Options For Outgoing API Calls](#options-for-outgoing-api-calls).\n\n## Troubleshoot\nFor a general troubleshooting guide that can help you solve common problems, see [Server Troubleshooting Guide](https://www.moesif.com/docs/troubleshooting/server-troubleshooting-guide/).\n\nOther troubleshooting supports:\n\n- [FAQ](https://www.moesif.com/docs/faq/)\n- [Moesif support email](mailto:support@moesif.com)\n\n### Solve Timezone Issue with Docker\nWhen using Docker with Ubuntu-based image, events may not be captured if the image fails to find any timezone configuration. To solve this issue, add the following line to your Dockerfile:\n\n```\nENV TZ=UTC\n```\n\nOtherwise, you can add `RUN apt-get install tzdata` in the Dockerfile.\n\n## Repository Structure\n\n```\n.\n\u251c\u2500\u2500 BUILDING.md\n\u251c\u2500\u2500 images/\n\u251c\u2500\u2500 LICENSE\n\u251c\u2500\u2500 MANIFEST.in\n\u251c\u2500\u2500 moesifdjango/\n\u251c\u2500\u2500 pull_request_template.md\n\u251c\u2500\u2500 README.md\n\u251c\u2500\u2500 requirements.txt\n\u251c\u2500\u2500 setup.cfg\n\u251c\u2500\u2500 setup.py\n\u2514\u2500\u2500 tests/\n```\n\n## Configuration options\nThe following sections describe the available configuration options for this middleware. You have to set these options in a Python dictionary `MOESIF_MIDDLEWARE`. See the [examples](#examples) for better understanding.\n\n#### `APPLICATION_ID` (Required)\n<table>\n  <tr>\n   <th scope=\"col\">\n    Data type\n   </th>\n  </tr>\n  <tr>\n   <td>\n    String\n   </td>\n  </tr>\n</table>\n\nA string that [identifies your application in Moesif](#get-your-moesif-application-id).\n\n### Options specific to Incoming API Calls\nThe following options document the configuration options to use for incoming API calls.\n\nSeveral options use request and response as input arguments. These correspond to [Django's request and response objects](https://docs.djangoproject.com/en/1.10/ref/request-response/).\n\n#### `SKIP`\n<table>\n  <tr>\n   <th scope=\"col\">\n    Data type\n   </th>\n   <th scope=\"col\">\n    Parameters\n   </th>\n   <th scope=\"col\">\n    Return type\n   </th>\n  </tr>\n  <tr>\n   <td>\n    Function\n   </td>\n   <td>\n    <code>(request, response)</code>\n   </td>\n   <td>\n    Boolean\n   </td>\n  </tr>\n</table>\n\nOptional.\n\nThis function takes Requests [`Request` and `Response` objects](https://requests.readthedocs.io/en/latest/user/advanced/#request-and-response-objects) and returns `True` if you want to skip this particular event.\n\n#### `IDENTIFY_USER`\n<table>\n  <tr>\n   <th scope=\"col\">\n    Data type\n   </th>\n   <th scope=\"col\">\n    Parameters\n   </th>\n   <th scope=\"col\">\n    Return type\n   </th>\n  </tr>\n  <tr>\n   <td>\n    Function\n   </td>\n   <td>\n    <code>(request, response)</code>\n   </td>\n   <td>\n    String\n   </td>\n  </tr>\n</table>\n\nOptional, but highly recommended.\n\nThis function takes a request and a response and returns a string that represents \nthe user ID used by your system.\n\nMoesif tries to identify users automatically and fetch the username from [`django.http.HttpRequest.user`](https://docs.djangoproject.com/en/1.8/ref/request-response/#django.http.HttpRequest.user). However, if implementation differs, we highly recommend that you accurately provide a \nuser ID using this function.\n\n#### `IDENTIFY_COMPANY`\n<table>\n  <tr>\n   <th scope=\"col\">\n    Data type\n   </th>\n   <th scope=\"col\">\n    Parameters\n   </th>\n   <th scope=\"col\">\n    Return type\n   </th>\n  </tr>\n  <tr>\n   <td>\n    Function\n   </td>\n   <td>\n    <code>(request, response)</code>\n   </td>\n   <td>\n    String\n   </td>\n  </tr>\n</table>\n\nOptional.\n\nA function that takes a request and a response and returns a string that represents the company ID for this event.\n\n#### `GET_SESSION_TOKEN`\n<table>\n  <tr>\n   <th scope=\"col\">\n    Data type\n   </th>\n   <th scope=\"col\">\n    Parameters\n   </th>\n   <th scope=\"col\">\n    Return type\n   </th>\n  </tr>\n  <tr>\n   <td>\n    Function\n   </td>\n   <td>\n    <code>(request, response)</code>\n   </td>\n   <td>\n    String\n   </td>\n  </tr>\n</table>\n\nOptional. \n\nA function that takes a request and a response, and returns a string that represents the session token for this event. \n\nSimilar to [user IDs](#identify_user), Moesif tries to get the session token automatically. However, if you setup differs from the standard, this function can help tying up events together and help you replay the events.\n\n#### `GET_METADATA`\n<table>\n  <tr>\n   <th scope=\"col\">\n    Data type\n   </th>\n   <th scope=\"col\">\n    Parameters\n   </th>\n   <th scope=\"col\">\n    Return type\n   </th>\n  </tr>\n  <tr>\n   <td>\n    Function\n   </td>\n   <td>\n    <code>(request, response)</code>\n   </td>\n   <td>\n    Dictionary\n   </td>\n  </tr>\n</table>\n\nOptional.\n\nA function that takes a request and a response and returns a Python dictionary.\n\nThe dictionary must be such that it can be converted into valid JSON. This allows you to associate this event with custom metadata. For example, you may want to save a virtual machine instance ID, a trace ID, or a tenant ID with the request.\n\n#### `LOG_BODY`\n<table>\n  <tr>\n   <th scope=\"col\">\n    Data type\n   </th>\n   <th scope=\"col\">\n    Default\n   </th>\n  </tr>\n  <tr>\n   <td>\n    <code>Boolean</code>\n   </td>\n   <td>\n    <code>True</code>\n   </td>\n  </tr>\n</table>\n\nOptional.\n\nWhether to log request and response body to Moesif.\n\nSet to `False` to remove the HTTP body before sending to Moesif. \n\nIf you want more control over which fields the middleware includes or not, see the next option `MASK_EVENT_MODEL`.\n\n#### `MASK_EVENT_MODEL`\n<table>\n  <tr>\n   <th scope=\"col\">\n    Data type\n   </th>\n   <th scope=\"col\">\n    Parameters\n   </th>\n   <th scope=\"col\">\n    Return type\n   </th>\n  </tr>\n  <tr>\n   <td>\n    Function\n   </td>\n   <td>\n    <code>(EventModel)</code>\n   </td>\n   <td>\n    <code>EventModel</code>\n   </td>\n  </tr>\n</table>\n\nOptional.\n\nA function that takes the final Moesif event model and returns an `EventModel` object with desired data removed. \n\nUse this if you prefer to write your own mask function than uses the string based filter options: \n\n- `REQUEST_BODY_MASKS`\n- `REQUEST_HEADER_MASKS`\n- `RESPONSE_BODY_MASKS`\n- `RESPONSE_HEADER_MASKS`\n\nThe return value must be a valid `EventModel` required by Moesif data ingestion API. For more information about Moesif event model, see [Moesif Python API documentation](https://www.moesif.com/docs/api?python).\n\n#### `BATCH_SIZE`\n<table>\n  <tr>\n   <th scope=\"col\">\n    Data type\n   </th>\n   <th scope=\"col\">\n    Default\n   </th>\n  </tr>\n  <tr>\n   <td>\n    <code>int</code>\n   </td>\n   <td>\n    <code>25</code>\n   </td>\n  </tr>\n</table>\n\nOptional.\n\nSpecifies the maximum batch size when sending to Moesif.\n\n#### `EVENT_QUEUE_SIZE`\n<table>\n  <tr>\n   <th scope=\"col\">\n    Data type\n   </th>\n   <th scope=\"col\">\n    Default\n   </th>\n  </tr>\n  <tr>\n   <td>\n    <code>int</code>\n   </td>\n   <td>\n    <code>1000_000</code>\n   </td>\n  </tr>\n</table>\n\nOptional.\n\nThe maximum number of events to hold in queue before sending to Moesif. \n\nIn case of network issues, the middleware may fail to connect or send event to Moesif. In those cases, the middleware skips adding new to event to queue to prevent memory overflow.\n\n#### `AUTHORIZATION_HEADER_NAME`\n<table>\n  <tr>\n   <th scope=\"col\">\n    Data type\n   </th>\n   <th scope=\"col\">\n    Default \n   </th>\n  </tr>\n  <tr>\n   <td>\n    String\n   </td>\n   <td>\n    <code>authorization</code>\n   </td>\n  </tr>\n</table>\n\nOptional.\n\nA request header field name used to identify the User in Moesif. It also supports a comma separated string. Moesif checks headers in order like `\"X-Api-Key,Authorization\"`.\n\n#### `AUTHORIZATION_USER_ID_FIELD`\n<table>\n  <tr>\n   <th scope=\"col\">\n    Data type\n   </th>\n   <th scope=\"col\">\n    Default \n   </th>\n  </tr>\n  <tr>\n   <td>\n    String\n   </td>\n   <td>\n    <code>sub</code>\n   </td>\n  </tr>\n</table>\n\nOptional.\n\nA field name used to parse the user from authorization header in Moesif.\n\n#### `BASE_URI`\n<table>\n  <tr>\n   <th scope=\"col\">\n    Data type\n   </th>\n  </tr>\n  <tr>\n   <td>\n    String\n   </td>\n  </tr>\n</table>\n\nOptional.\n\nA local proxy hostname when sending traffic through secure proxy. Remember to set this field when using secure proxy. For more information, see [Secure Proxy documentation.](https://www.moesif.com/docs/platform/secure-proxy/#2-configure-moesif-sdk).\n\n### Options For Outgoing API Calls \n\nThe following options apply to outgoing API calls. These are calls you initiate using the Python [Requests](http://docs.python-requests.org/en/master/) library to third parties like Stripe or to your own services.\n\nSeveral options use request and response as input arguments. These correspond to the [Requests](http://docs.python-requests.org/en/master/api/) library's request or response objects.\n\nIf you are not using Django, you can import [`moesifpythonrequest`](https://github.com/Moesif/moesifpythonrequest) directly.\n\n#### `CAPTURE_OUTGOING_REQUESTS`\n<table>\n  <tr>\n   <th scope=\"col\">\n    Data type\n   </th>\n   <th scope=\"col\">\n    Default \n   </th>\n  </tr>\n  <tr>\n   <td>\n    Boolean\n   </td>\n   <td>\n    <code>False</code>\n   </td>\n  </tr>\n</table>\n\nSet to `True` to capture all outgoing API calls.\n\n##### `GET_METADATA_OUTGOING`\n<table>\n  <tr>\n   <th scope=\"col\">\n    Data type\n   </th>\n   <th scope=\"col\">\n    Parameters\n   </th>\n   <th scope=\"col\">\n    Return type\n   </th>\n  </tr>\n  <tr>\n   <td>\n    Function\n   </td>\n   <td>\n    <code>(req, res)</code>\n   </td>\n   <td>\n    Dictionary\n   </td>\n  </tr>\n</table>\n\nOptional.\n\nA function that enables you to return custom metadata associated with the logged API calls.\n\nTakes in the [Requests](http://docs.python-requests.org/en/master/api/) request and response objects as arguments. \n\nWe recommend that you implement a function that\nreturns a dictionary containing your custom metadata. The dictionary must be a valid one that can be encoded into JSON. For example, you may want to save a virtual machine instance ID, a trace ID, or a resource ID with the request.\n\n##### `SKIP_OUTGOING`\n<table>\n  <tr>\n   <th scope=\"col\">\n    Data type\n   </th>\n   <th scope=\"col\">\n    Parameters\n   </th>\n   <th scope=\"col\">\n    Return type\n   </th>\n  </tr>\n  <tr>\n   <td>\n    Function\n   </td>\n   <td>\n    <code>(req, res)</code>\n   </td>\n   <td>\n    Boolean\n   </td>\n  </tr>\n</table>\n\nOptional.\n\nA function that takes a [Requests](http://docs.python-requests.org/en/master/api/) request and response objects,\nand returns `True` if you want to skip this particular event.\n\n##### `IDENTIFY_USER_OUTGOING`\n<table>\n  <tr>\n   <th scope=\"col\">\n    Data type\n   </th>\n   <th scope=\"col\">\n    Parameters\n   </th>\n   <th scope=\"col\">\n    Return type\n   </th>\n  </tr>\n  <tr>\n   <td>\n    Function\n   </td>\n   <td>\n    <code>(req, res)</code>\n   </td>\n   <td>\n    String\n   </td>\n  </tr>\n</table>\n\nOptional, but highly recommended.\n\nA function that takes [Requests](http://docs.python-requests.org/en/master/api/) request and response objects, and returns a string that represents the user ID used by your system. \n\nWhile Moesif tries to identify users automatically, different frameworks and your implementation might vary. So we highly recommend that you accurately provide a \nuser ID using this function.\n\n##### `IDENTIFY_COMPANY_OUTGOING`\n<table>\n  <tr>\n   <th scope=\"col\">\n    Data type\n   </th>\n   <th scope=\"col\">\n    Parameters\n   </th>\n   <th scope=\"col\">\n    Return type\n   </th>\n  </tr>\n  <tr>\n   <td>\n    Function\n   </td>\n   <td>\n    <code>(req, res)</code>\n   </td>\n   <td>\n    String\n   </td>\n  </tr>\n</table>\n\nOptional.\n\nA function that takes [Requests](http://docs.python-requests.org/en/master/api/) request and response objects and returns a string that represents the company ID for this event.\n\n##### `GET_SESSION_TOKEN_OUTGOING`\n<table>\n  <tr>\n   <th scope=\"col\">\n    Data type\n   </th>\n   <th scope=\"col\">\n    Parameters\n   </th>\n   <th scope=\"col\">\n    Return type\n   </th>\n  </tr>\n  <tr>\n   <td>\n    Function\n   </td>\n   <td>\n    <code>(req, res)</code>\n   </td>\n   <td>\n    String\n   </td>\n  </tr>\n</table>\n\nOptional.\n\nA function that takes [Requests](http://docs.python-requests.org/en/master/api/) request and response objects, and returns a string that corresponds to the session token for this event. \n\nSimilar to [user IDs](#identify_user_outgoing), Moesif tries to get the session token automatically. However, if you setup differs from the standard, this function can help tying up events together and help you replay the events.\n\n### General options\n#### `LOG_BODY_OUTGOING`\n<table>\n  <tr>\n   <th scope=\"col\">\n    Data type\n   </th>\n   <th scope=\"col\">\n    Default\n   </th>\n  </tr>\n  <tr>\n   <td>\n    Boolean\n   </td>\n   <td>\n    <code>True</code>\n   </td>\n  </tr>\n</table>\n\nOptional.\n\nSet to `False` to remove logging request and response body.\n\n#### `LOCAL_DEBUG`\n<table>\n  <tr>\n   <th scope=\"col\">\n    Data type\n   </th>\n  </tr>\n  <tr>\n   <td>\n    Boolean\n   </td>\n  </tr>\n</table>\n\nOptional.\n\nSet to `True` to print internal log messages for debugging SDK integration issues.\n\n## Examples\nSee the [Moesif Django Example](https://github.com/Moesif/moesifdjangoexample) for a complete Django application that uses this middleware.\n\nThe following shows a sample Django settings file with different configuration options.\n\n```python\ndef identify_user(req, res):\n    # Your custom code that returns a user id string\n    if req.user and req.user.is_authenticated:\n        return req.user.username\n    else:\n        return None\n\ndef identify_company(req, res):\n    # Your custom code that returns a company id string\n    return \"67890\"\n\ndef should_skip(req, res):\n    # Your custom code that returns true to skip logging\n    return \"health/probe\" in req.path\n\ndef get_token(req, res):\n    # If you don't want to use the standard Django session token,\n    # add your custom code that returns a string for session/API token\n    return \"XXXXXXXXXXXXXX\"\n\ndef mask_event(eventmodel):\n    # Your custom code to change or remove any sensitive fields\n    if 'password' in eventmodel.response.body:\n        eventmodel.response.body['password'] = None\n    return eventmodel\n\ndef get_metadata(req, res):\n    return {\n        'datacenter': 'westus',\n        'deployment_version': 'v1.2.3',\n    }\n\n\nMOESIF_MIDDLEWARE = {\n    'APPLICATION_ID': 'Your application id',\n    'LOCAL_DEBUG': False,\n    'LOG_BODY': True,\n    'IDENTIFY_USER': identify_user,\n    'IDENTIFY_COMPANY': identify_company,\n    'GET_SESSION_TOKEN': get_token,\n    'SKIP': should_skip,\n    'MASK_EVENT_MODEL': mask_event,\n    'GET_METADATA': get_metadata,\n}\n```\n\nThe following examples demonstrate how to add and update customer information using the middleware.\n\n### Update A Single User\nTo create or update a [user](https://www.moesif.com/docs/getting-started/users/) profile in Moesif, use the `update_user()` method.\n\n```python\nmiddleware = MoesifMiddleware(None)\n\n# Only user_id is required.\n# Campaign object is optional, but useful if you want to track ROI of acquisition channels\n# See https://www.moesif.com/docs/api#users for campaign schema\n# metadata can be any custom object\nuser = {\n  'user_id': '12345',\n  'company_id': '67890', # If set, associate user with a company object\n  'campaign': {\n    'utm_source': 'google',\n    'utm_medium': 'cpc', \n    'utm_campaign': 'adwords',\n    'utm_term': 'api+tooling',\n    'utm_content': 'landing'\n  },\n  'metadata': {\n    'email': 'john@acmeinc.com',\n    'first_name': 'John',\n    'last_name': 'Doe',\n    'title': 'Software Engineer',\n    'sales_info': {\n        'stage': 'Customer',\n        'lifetime_value': 24000,\n        'account_owner': 'mary@contoso.com'\n    },\n  }\n}\n\nupdate_user = middleware.update_user(user)\n```\n\nThe `metadata` field can contain any customer demographic or other info you want to store. Moesif only requires the `user_id` field. This method is a convenient helper that calls the Moesif API library.\n\nFor more information, see [Moesif Python API reference](https://www.moesif.com/docs/api?python#update-a-user).\n\n### Update Users in Batch\nTo update a list of [users](https://www.moesif.com/docs/getting-started/users/) in one batch, use the `update_users_batch()` method.\n\n```python\nmiddleware = MoesifMiddleware(None)\n\nuserA = {\n  'user_id': '12345',\n  'company_id': '67890', # If set, associate user with a company object\n  'metadata': {\n    'email': 'john@acmeinc.com',\n    'first_name': 'John',\n    'last_name': 'Doe',\n    'title': 'Software Engineer',\n    'sales_info': {\n        'stage': 'Customer',\n        'lifetime_value': 24000,\n        'account_owner': 'mary@contoso.com'\n    },\n  }\n}\n\nuserB = {\n  'user_id': '54321',\n  'company_id': '67890', # If set, associate user with a company object\n  'metadata': {\n    'email': 'mary@acmeinc.com',\n    'first_name': 'Mary',\n    'last_name': 'Jane',\n    'title': 'Software Engineer',\n    'sales_info': {\n        'stage': 'Customer',\n        'lifetime_value': 48000,\n        'account_owner': 'mary@contoso.com'\n    },\n  }\n}\nupdate_users = middleware.update_users_batch([userA, userB])\n```\n\nThe `metadata` field can contain any customer demographic or other info you want to store. Moesif only requires the `user_id` field. This method is a convenient helper that calls the Moesif API library.\n\nFor more information, see [Moesif Python API reference](https://www.moesif.com/docs/api?python#update-users-in-batch).\n\n### Update A Single Company\nTo update a single [company](https://www.moesif.com/docs/getting-started/companies/), use the `update_company()` method.\n\n```python\nmiddleware = MoesifMiddleware(None)\n\n# Only company_id is required.\n# Campaign object is optional, but useful if you want to track ROI of acquisition channels\n# See https://www.moesif.com/docs/api#update-a-company for campaign schema\n# metadata can be any custom object\ncompany = {\n  'company_id': '67890',\n  'company_domain': 'acmeinc.com', # If domain is set, Moesif will enrich your profiles with publicly available info \n  'campaign': {\n    'utm_source': 'google',\n    'utm_medium': 'cpc', \n    'utm_campaign': 'adwords',\n    'utm_term': 'api+tooling',\n    'utm_content': 'landing'\n  },\n  'metadata': {\n    'org_name': 'Acme, Inc',\n    'plan_name': 'Free',\n    'deal_stage': 'Lead',\n    'mrr': 24000,\n    'demographics': {\n        'alexa_ranking': 500000,\n        'employee_count': 47\n    },\n  }\n}\n\nupdate_company = middleware.update_company(company)\n```\n\nThe `metadata` field can contain any company demographic or other info you want to store. Moesif only requires the `company_id` field. This method is a convenient helper that calls the Moesif API library.\n\nFor more information, see [Moesif Python API reference](https://www.moesif.com/docs/api?python#update-a-company).\n\n### Update Companies in Batch\nTo update a list of [companies](https://www.moesif.com/docs/getting-started/companies/) in one batch, use the `update_companies_batch()` method.\n\n```python\nmiddleware = MoesifMiddleware(None)\n\ncompanyA = {\n  'company_id': '67890',\n  'company_domain': 'acmeinc.com', # If domain is set, Moesif will enrich your profiles with publicly available info \n  'metadata': {\n    'org_name': 'Acme, Inc',\n    'plan_name': 'Free',\n    'deal_stage': 'Lead',\n    'mrr': 24000,\n    'demographics': {\n        'alexa_ranking': 500000,\n        'employee_count': 47\n    },\n  }\n}\n\ncompanyB = {\n  'company_id': '09876',\n  'company_domain': 'contoso.com', # If domain is set, Moesif will enrich your profiles with publicly available info \n  'metadata': {\n    'org_name': 'Contoso, Inc',\n    'plan_name': 'Free',\n    'deal_stage': 'Lead',\n    'mrr': 48000,\n    'demographics': {\n        'alexa_ranking': 500000,\n        'employee_count': 53\n    },\n  }\n}\n\nupdate_companies = middleware.update_companies_batch([userA, userB])\n```\n\nThe `metadata` field can contain any company demographic or other info you want to store. Moesif only requires the `company_id` field. This method is a convenient helper that calls the Moesif API library.\n\nFor more information, see [Moesif Python API reference](https://www.moesif.com/docs/api?python#update-companies-in-batch).\n\n### Update Subscription\n\n#### Update A Single Subscription\nTo create or update a subscription in Moesif, use the `update_subscription` method.\n\n```python\nmiddleware = MoesifMiddleware(None)\n\n# Only subscription_id is required.\n# metadata can be any custom object\nsubscription = {\n  'subscription_id': 'sub_67890',\n  'company_id': '3456',\n  'status': 'active'\n  'metadata': {\n    'plan_name': 'Pro',\n    'signup_date': '2020-09-09',\n    'expiration_date': '2021-09-09',\n    'payment_method': 'credit_card',\n    'mrr': 12000,\n    'currency': 'USD'\n  }\n}\n\nupdate_subscription = middleware.update_subscription(subscription)\n```\n\nThe `metadata` field can store any subscription-related information. Moesif only requires the the following fields: \n\n- `subscription_id`\n- `company_id`\n- `status` \n\nThis method is a convenient helper that calls the Moesif API library. \n\nFor more information, see [Moesif Python API reference](https://www.moesif.com/docs/api?python#update-a-subscription).\n\n### Update Subscriptions in Batch\nTo update a list of subscriptions in one batch, use the `update_subscriptions_batch` method.\n\n```python\nmiddleware = MoesifMiddleware(None)\n\nsubscriptionA = {\n  'subscription_id': 'sub_67890',\n  'company_id': '3456',\n  'status': 'active'\n  'metadata': {\n    'plan_name': 'Pro',\n    'signup_date': '2020-09-09',\n    'expiration_date': '2021-09-09',\n    'payment_method': 'credit_card',\n    'mrr': 12000,\n    'currency': 'USD'\n  }\n}\n\nsubscriptionB = {\n  'subscription_id': 'sub_54321',\n  'company_id': '6789',\n  'status': 'active'\n  'metadata': {\n    'plan_name': 'Enterprise',\n    'signup_date': '2020-10-01',\n    'expiration_date': '2021-10-01',\n    'payment_method': 'paypal',\n    'mrr': 24000,\n    'currency': 'USD'\n  }\n}\n\nupdate_subscriptions = middleware.update_subscriptions_batch([subscriptionA, subscriptionB])\n```\n\nThe `metadata` field can store any subscription-related information. Moesif only requires the the following fields: \n\n- `subscription_id`\n- `company_id`\n- `status` \n\nThis method is a convenient helper that calls the Moesif API library.  \n\nFor more information, see [Moesif Python API reference](https://www.moesif.com/docs/api?python#update-subscriptions-in-batch).\n\n## Tested Python and Django Versions\n\nMoesif has validated this middleware against the following combinations of Python and Django versions:\n\n| Python        | Django     | \n| ------------  | -------    | \n| Python 2.7    | 1.11.22    | \n| Python 2.7    | 1.11.22    | \n| Python 2.7    | 1.9        | \n| Python 3.4.5  | 1.11.22    | \n| Python 3.4.5  | 1.11.22    | \n| Python 3.4.5  | 1.9        | \n| Python 3.6.4  | 1.11.22    | \n| Python 3.6.4  | 1.11.22    | \n| Python 3.6.4  | 1.9        | \n| Python 3.10.4 | 3.2.13 LTS | \n| Python 3.10.4 | 4.0.5      |\n\n## How to Test\n1. Manually clone this repository.\n2. From your terminal, navigate to the root directory of the middleware.\n3. Run `pip install Django` and then run `pip install moesifdjango`.\n4. Add your [Moesif Application ID](#get-your-moesif-application-id) to `tests/settings.py`.\n5. From terminal, navigate to the root directory of the middleware tests `tests/`.\n   \n   a. Run `python manage.py test` if you are using Django 1.10 or newer.\n   \n   b. Run `python manage.py test middleware_pre19_tests` if you are using Django 1.9 or older.\n\n## Explore Other Integrations\n\nExplore other integration options from Moesif:\n\n- [Server integration options documentation](https://www.moesif.com/docs/server-integration//)\n- [Client integration options documentation](https://www.moesif.com/docs/client-integration/)\n\n[ico-built-for]: https://img.shields.io/badge/built%20for-django-blue.svg\n[ico-version]: https://img.shields.io/pypi/v/moesifdjango.svg\n[ico-language]: https://img.shields.io/pypi/pyversions/moesifdjango.svg\n[ico-license]: https://img.shields.io/badge/License-Apache%202.0-green.svg\n[ico-source]: https://img.shields.io/github/last-commit/moesif/moesifdjango.svg?style=social\n\n[link-built-for]: https://www.djangoproject.com/\n[link-package]: https://pypi.python.org/pypi/moesifdjango\n[link-language]: https://pypi.python.org/pypi/moesifdjango\n[link-license]: https://raw.githubusercontent.com/Moesif/moesifdjango/master/LICENSE\n[link-source]: https://github.com/Moesif/moesifdjango\n",
    "bugtrack_url": null,
    "license": "Apache Software License",
    "summary": "Moesif Middleware for Python Django",
    "version": "2.3.11",
    "project_urls": {
        "Homepage": "https://www.moesif.com/docs/server-integration/django/"
    },
    "split_keywords": [
        "log",
        "analysis",
        "restful",
        "api",
        "development",
        "debug"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "cd6a36e015de7bc383be412ae319117cb0234abaad4a37faeb6407d3b8f9b2b8",
                "md5": "844c41fbd37c50dc60ba7ad8322657b5",
                "sha256": "df45daad656cb9d854ff05dfa2886e30e16178c112197ecdefef403f7658f3e4"
            },
            "downloads": -1,
            "filename": "moesifdjango-2.3.11-py2.py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "844c41fbd37c50dc60ba7ad8322657b5",
            "packagetype": "bdist_wheel",
            "python_version": "py2.py3",
            "requires_python": null,
            "size": 39200,
            "upload_time": "2024-10-31T21:00:22",
            "upload_time_iso_8601": "2024-10-31T21:00:22.663785Z",
            "url": "https://files.pythonhosted.org/packages/cd/6a/36e015de7bc383be412ae319117cb0234abaad4a37faeb6407d3b8f9b2b8/moesifdjango-2.3.11-py2.py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "cdf1fa77e60eca0ac12a4a3f234defe29418ae6992e26738e5a1b76a72397643",
                "md5": "3ea970e44a8feb25a0649f44155f0d92",
                "sha256": "583810e6e5f27fab8e50fd3261c6dcd54a1d3bdfbb06fb2294b835d28882a1a4"
            },
            "downloads": -1,
            "filename": "moesifdjango-2.3.11.tar.gz",
            "has_sig": false,
            "md5_digest": "3ea970e44a8feb25a0649f44155f0d92",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 40638,
            "upload_time": "2024-10-31T21:00:24",
            "upload_time_iso_8601": "2024-10-31T21:00:24.735881Z",
            "url": "https://files.pythonhosted.org/packages/cd/f1/fa77e60eca0ac12a4a3f234defe29418ae6992e26738e5a1b76a72397643/moesifdjango-2.3.11.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-10-31 21:00:24",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "moesifdjango"
}
        
Elapsed time: 0.55405s