moesifasgi


Namemoesifasgi JSON
Version 1.0.10 PyPI version JSON
download
home_pagehttps://www.moesif.com/docs/server-integration/python-asgi/
SummaryMoesif Middleware for Python ASGI based platforms (FastAPI & Others)
upload_time2024-11-01 20:28:22
maintainerNone
docs_urlNone
authorMoesif, Inc
requires_pythonNone
licenseApache Software License
keywords log analysis restful api development debug asgi fastapi http middleware
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Moesif Middleware for Python ASGI-based Frameworks

[![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]

With Moesif middleware for Python ASGI-based frameworks, you can automatically log API calls 
and send them to [Moesif](https://www.moesif.com) for API analytics and monitoring.

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

## Overview

This middleware allows you to integrate Moesif's API analytics and 
API monetization features with minimal configuration into APIs that are built on Python ASGI-based (Asynchronous Server Gateway Interface) frameworks.

[ASGI](https://asgi.readthedocs.io/en/latest/)
is a spiritual successor to WSGI (Web Server Gateway Interface). ASGI provides a standard interface between async-capable Python web servers, frameworks, and applications. Many Python Frameworks
are built on top of ASGI, such as [FastAPI](https://fastapi.tiangolo.com/).

## 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` using the following command:

```shell
pip install moesifasgi
```

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

## How to Use

### FastAPI

Simply add `MoesifMiddleware` to a FastAPI application using the `add_middleware` method:

```python
from moesifasgi import MoesifMiddleware

moesif_settings = {
    'APPLICATION_ID': 'YOUR_APPLICATION_ID',
    'LOG_BODY': True,
    # ... For other options see below.
}

app = FastAPI()

app.add_middleware(MoesifMiddleware, settings=moesif_settings)
```

Replace *`YOUR_MOESIF_APPLICATION_ID`* with your [Moesif Application ID](#get-your-moesif-application-id).

### Other ASGI Frameworks

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

### 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:

```python
from moesifasgi import MoesifMiddleware

moesif_settings = {
    'APPLICATION_ID': 'YOUR_APPLICATION_ID',
    'LOG_BODY': True,
    'CAPTURE_OUTGOING_REQUESTS': False,
}

app = FastAPI()

app.add_middleware(MoesifMiddleware, settings=moesif_settings)
```

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)

## Repository Structure

```
.
├── BUILDING.md
├── examples/
├── images/
├── LICENSE
├── MANIFEST.in
├── moesifasgi/
├── README.md
├── requirements.txt
├── setup.cfg
└── setup.py
```

## Configuration Options
The following sections describe the available configuration options for this middleware. You can set these options in a Python dictionary and then pass that as a parameter to `add_middleware` when you add this middleware. See [the sample FastAPI code](https://github.com/Moesif/moesifasgi/blob/1c43c02d2e90b392980371bd4382a609fbdd7f06/examples/fastapi/main.py#L218-L233) for an example.

Some configuration options use request and response as input arguments. These correspond to the [`Requests`](https://www.starlette.io/requests/) and [`Responses`](https://www.starlette.io/responses/) objects respectively.

#### `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).

#### `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.

A function that takes a request and a response,
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>
    <code>String</code>
   </td>
  </tr>
</table>

Optional, but highly recommended.

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

Moesif identifies users automatically. However, due to the differences arising from different frameworks and implementations, provide this function to ensure user identification properly.

#### `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 response, and returns a string that represents the company ID for this event.

#### `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.

This function allows you
to add custom metadata that Moesif can associate with the event. The metadata must be a simple Python dictionary that can be converted to JSON. 

For example, you may want to save a virtual machine instance ID, a trace ID, or a resource ID with the request.

#### `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 response, and returns a string that represents the session token for this event. 

Similar to users and companies, Moesif tries to retrieve session tokens automatically. But if it doesn't work for your service, provide this function to help identify sessions.

#### `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 event model with desired data removed. 

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

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

Optional.

Set to `True` to print debug logs if you're having integration issues.

#### `LOG_BODY`
<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.

Whether to log request and response body to Moesif.

#### `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>

An optional field name that specifies the maximum batch size when sending to Moesif.

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

Optional.

Maximum time in seconds to wait before sending a batch of events to Moesif when reading from the queue.

#### `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 event objects queued in memory pending upload to Moesif. For a full queue, additional calls to `MoesifMiddleware` returns immediately without logging the event. Therefore, set this option based on the event size and memory capacity you expect.

#### `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 ASGI, you can import [`moesifpythonrequest`](https://github.com/Moesif/moesifpythonrequest) directly.

#### `CAPTURE_OUTGOING_REQUESTS` (Required)
<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.

##### `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.

## Examples
See the example FastAPI app in the `examples/` folder of this repository that uses this middleware.

Here's another sample FastAPI app:

```python
# Your custom code that returns a user id string
custom_user = "12345"

async def custom_identify_user():
    return custom_user

# identify user using async mode
async def identify_user(request, response):
    user = await custom_identify_user()
    return user

# identify user not using async mode
def identify_user(request, response):
    return custom_user

# Your custom code that returns a company id string
custom_company = "67890"

async def custom_identify_company():
    return custom_company

# identify company using async mode
async def identify_company(request, response):
    company = await custom_identify_company()
    return company

# identify company not using async mode
def identify_company(request, response):
    return custom_company

custom_session_token = "XXXXXXXXXXXXXX"

async def custom_get_token():
    # If you don't want to use the standard ASGI session token,
    # add your custom code that returns a string for session/API token
    return custom_session_token

# get session token using async mode
async def get_token(request, response):
    result = await custom_get_token()
    return result

# get session token not using async mode
def get_token(request, response):
    return custom_session_token

custom_metadata = {
    'datacenter': 'westus',
    'deployment_version': 'v1.2.3',
}

async def custom_get_metadata():
    return custom_metadata

# get metadata using async mode
async def get_metadata(request, response):
    result = await custom_get_metadata()
    return result

# get metadata not using async mode
def get_metadata(request, response):
    return custom_metadata

skip_route = "health/probe"

async def custom_should_skip(request):
    # Your custom code that returns `True` to skip logging
    return skip_route in request.url._url

# should skip check using async mode
async def should_skip(request, response):
    result = await custom_should_skip(request)
    return result

# should skip check not using async mode
def should_skip(request, response):
    return skip_route in request.url._url

def custom_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

# mask event using async mode
async def mask_event(eventmodel):
    return custom_mask_event(eventmodel)

# mask event not using async mode
def mask_event(eventmodel):
    return custom_mask_event(eventmodel)


moesif_settings = {
    'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID',
    '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,
    'CAPTURE_OUTGOING_REQUESTS': False
}

app = FastAPI()

app.add_middleware(MoesifMiddleware, settings=moesif_settings)
```

You can use OAuth2 in your FastAPI app with this middleware. For more information, see [OAuth2 with Password (and hashing), Bearer with JWT tokens](https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/).

## Tested versions

Moesif has validated this middleware against the following frameworks and framework versions:

|         | Framework Version |
|---------|-------------------|
| fastapi | > 0.51.0 - 0.78.0 |
| fastapi |  0.108.0          |

## 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-python%20asgi-blue.svg
[ico-version]: https://img.shields.io/pypi/v/moesifasgi.svg
[ico-language]: https://img.shields.io/pypi/pyversions/moesifasgi.svg
[ico-license]: https://img.shields.io/badge/License-Apache%202.0-green.svg
[ico-source]: https://img.shields.io/github/last-commit/moesif/moesifasgi.svg?style=social

[link-built-for]: https://en.wikipedia.org/wiki/Web_Server_Gateway_Interface
[link-package]: https://pypi.python.org/pypi/moesifasgi
[link-language]: https://pypi.python.org/pypi/moesifasgi
[link-license]: https://raw.githubusercontent.com/Moesif/moesifasgi/master/LICENSE
[link-source]: https://github.com/Moesif/moesifasgi

            

Raw data

            {
    "_id": null,
    "home_page": "https://www.moesif.com/docs/server-integration/python-asgi/",
    "name": "moesifasgi",
    "maintainer": null,
    "docs_url": null,
    "requires_python": null,
    "maintainer_email": null,
    "keywords": "log analysis restful api development debug asgi fastapi http middleware",
    "author": "Moesif, Inc",
    "author_email": "keyur@moesif.com",
    "download_url": "https://files.pythonhosted.org/packages/f9/14/45b7ab20fe3f18c115596ef73b177a0b01d678ea19d9f3b08ff2dbfeba0a/moesifasgi-1.0.10.tar.gz",
    "platform": null,
    "description": "# Moesif Middleware for Python ASGI-based Frameworks\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\nWith Moesif middleware for Python ASGI-based frameworks, you can automatically log API calls \nand send them to [Moesif](https://www.moesif.com) for API analytics and monitoring.\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## Overview\n\nThis middleware allows you to integrate Moesif's API analytics and \nAPI monetization features with minimal configuration into APIs that are built on Python ASGI-based (Asynchronous Server Gateway Interface) frameworks.\n\n[ASGI](https://asgi.readthedocs.io/en/latest/)\nis a spiritual successor to WSGI (Web Server Gateway Interface). ASGI provides a standard interface between async-capable Python web servers, frameworks, and applications. Many Python Frameworks\nare built on top of ASGI, such as [FastAPI](https://fastapi.tiangolo.com/).\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\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\nInstall with `pip` using the following command:\n\n```shell\npip install moesifasgi\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\n### FastAPI\n\nSimply add `MoesifMiddleware` to a FastAPI application using the `add_middleware` method:\n\n```python\nfrom moesifasgi import MoesifMiddleware\n\nmoesif_settings = {\n    'APPLICATION_ID': 'YOUR_APPLICATION_ID',\n    'LOG_BODY': True,\n    # ... For other options see below.\n}\n\napp = FastAPI()\n\napp.add_middleware(MoesifMiddleware, settings=moesif_settings)\n```\n\nReplace *`YOUR_MOESIF_APPLICATION_ID`* with your [Moesif Application ID](#get-your-moesif-application-id).\n\n### Other ASGI Frameworks\n\nIf you are using a framework that is built on top of ASGI, it should work just by adding the Moesif middleware.\nPlease read the documentation for your specific framework on how to add middlewares.\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:\n\n```python\nfrom moesifasgi import MoesifMiddleware\n\nmoesif_settings = {\n    'APPLICATION_ID': 'YOUR_APPLICATION_ID',\n    'LOG_BODY': True,\n    'CAPTURE_OUTGOING_REQUESTS': False,\n}\n\napp = FastAPI()\n\napp.add_middleware(MoesifMiddleware, settings=moesif_settings)\n```\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## Repository Structure\n\n```\n.\n\u251c\u2500\u2500 BUILDING.md\n\u251c\u2500\u2500 examples/\n\u251c\u2500\u2500 images/\n\u251c\u2500\u2500 LICENSE\n\u251c\u2500\u2500 MANIFEST.in\n\u251c\u2500\u2500 moesifasgi/\n\u251c\u2500\u2500 README.md\n\u251c\u2500\u2500 requirements.txt\n\u251c\u2500\u2500 setup.cfg\n\u2514\u2500\u2500 setup.py\n```\n\n## Configuration Options\nThe following sections describe the available configuration options for this middleware. You can set these options in a Python dictionary and then pass that as a parameter to `add_middleware` when you add this middleware. See [the sample FastAPI code](https://github.com/Moesif/moesifasgi/blob/1c43c02d2e90b392980371bd4382a609fbdd7f06/examples/fastapi/main.py#L218-L233) for an example.\n\nSome configuration options use request and response as input arguments. These correspond to the [`Requests`](https://www.starlette.io/requests/) and [`Responses`](https://www.starlette.io/responses/) objects respectively.\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#### `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\nA function that takes a request and a response,\nand 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    <code>String</code>\n   </td>\n  </tr>\n</table>\n\nOptional, but highly recommended.\n\nA function that takes a request and a response, and returns a string that represents the user ID used by your system. \n\nMoesif identifies users automatically. However, due to the differences arising from different frameworks and implementations, provide this function to ensure user identification properly.\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 response, and returns a string that represents the company ID for this event.\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\nThis function allows you\nto add custom metadata that Moesif can associate with the event. The metadata must be a simple Python dictionary that can be converted to JSON. \n\nFor example, you may want to save a virtual machine instance ID, a trace ID, or a resource ID with the request.\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 response, and returns a string that represents the session token for this event. \n\nSimilar to users and companies, Moesif tries to retrieve session tokens automatically. But if it doesn't work for your service, provide this function to help identify sessions.\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 event model with desired data removed. \n\nThe return value must be a valid eventt model required by Moesif data ingestion API. For more information about the `EventModel` object, see the [Moesif Python API documentation](https://www.moesif.com/docs/api?python).\n\n#### `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 debug logs if you're having integration issues.\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    Boolean\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\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\nAn optional field name that specifies the maximum batch size when sending to Moesif.\n\n#### `EVENT_BATCH_TIMEOUT`\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>1</code>\n   </td>\n  </tr>\n</table>\n\nOptional.\n\nMaximum time in seconds to wait before sending a batch of events to Moesif when reading from the queue.\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 event objects queued in memory pending upload to Moesif. For a full queue, additional calls to `MoesifMiddleware` returns immediately without logging the event. Therefore, set this option based on the event size and memory capacity you expect.\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 ASGI, you can import [`moesifpythonrequest`](https://github.com/Moesif/moesifpythonrequest) directly.\n\n#### `CAPTURE_OUTGOING_REQUESTS` (Required)\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##### `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## Examples\nSee the example FastAPI app in the `examples/` folder of this repository that uses this middleware.\n\nHere's another sample FastAPI app:\n\n```python\n# Your custom code that returns a user id string\ncustom_user = \"12345\"\n\nasync def custom_identify_user():\n    return custom_user\n\n# identify user using async mode\nasync def identify_user(request, response):\n    user = await custom_identify_user()\n    return user\n\n# identify user not using async mode\ndef identify_user(request, response):\n    return custom_user\n\n# Your custom code that returns a company id string\ncustom_company = \"67890\"\n\nasync def custom_identify_company():\n    return custom_company\n\n# identify company using async mode\nasync def identify_company(request, response):\n    company = await custom_identify_company()\n    return company\n\n# identify company not using async mode\ndef identify_company(request, response):\n    return custom_company\n\ncustom_session_token = \"XXXXXXXXXXXXXX\"\n\nasync def custom_get_token():\n    # If you don't want to use the standard ASGI session token,\n    # add your custom code that returns a string for session/API token\n    return custom_session_token\n\n# get session token using async mode\nasync def get_token(request, response):\n    result = await custom_get_token()\n    return result\n\n# get session token not using async mode\ndef get_token(request, response):\n    return custom_session_token\n\ncustom_metadata = {\n    'datacenter': 'westus',\n    'deployment_version': 'v1.2.3',\n}\n\nasync def custom_get_metadata():\n    return custom_metadata\n\n# get metadata using async mode\nasync def get_metadata(request, response):\n    result = await custom_get_metadata()\n    return result\n\n# get metadata not using async mode\ndef get_metadata(request, response):\n    return custom_metadata\n\nskip_route = \"health/probe\"\n\nasync def custom_should_skip(request):\n    # Your custom code that returns `True` to skip logging\n    return skip_route in request.url._url\n\n# should skip check using async mode\nasync def should_skip(request, response):\n    result = await custom_should_skip(request)\n    return result\n\n# should skip check not using async mode\ndef should_skip(request, response):\n    return skip_route in request.url._url\n\ndef custom_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\n# mask event using async mode\nasync def mask_event(eventmodel):\n    return custom_mask_event(eventmodel)\n\n# mask event not using async mode\ndef mask_event(eventmodel):\n    return custom_mask_event(eventmodel)\n\n\nmoesif_settings = {\n    'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID',\n    '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    'CAPTURE_OUTGOING_REQUESTS': False\n}\n\napp = FastAPI()\n\napp.add_middleware(MoesifMiddleware, settings=moesif_settings)\n```\n\nYou can use OAuth2 in your FastAPI app with this middleware. For more information, see [OAuth2 with Password (and hashing), Bearer with JWT tokens](https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/).\n\n## Tested versions\n\nMoesif has validated this middleware against the following frameworks and framework versions:\n\n|         | Framework Version |\n|---------|-------------------|\n| fastapi | > 0.51.0 - 0.78.0 |\n| fastapi |  0.108.0          |\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-python%20asgi-blue.svg\n[ico-version]: https://img.shields.io/pypi/v/moesifasgi.svg\n[ico-language]: https://img.shields.io/pypi/pyversions/moesifasgi.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/moesifasgi.svg?style=social\n\n[link-built-for]: https://en.wikipedia.org/wiki/Web_Server_Gateway_Interface\n[link-package]: https://pypi.python.org/pypi/moesifasgi\n[link-language]: https://pypi.python.org/pypi/moesifasgi\n[link-license]: https://raw.githubusercontent.com/Moesif/moesifasgi/master/LICENSE\n[link-source]: https://github.com/Moesif/moesifasgi\n",
    "bugtrack_url": null,
    "license": "Apache Software License",
    "summary": "Moesif Middleware for Python ASGI based platforms (FastAPI & Others)",
    "version": "1.0.10",
    "project_urls": {
        "Homepage": "https://www.moesif.com/docs/server-integration/python-asgi/"
    },
    "split_keywords": [
        "log",
        "analysis",
        "restful",
        "api",
        "development",
        "debug",
        "asgi",
        "fastapi",
        "http",
        "middleware"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "77a6526557eff7d13282d0e51cbfd84ce76264dbbfee248a2f0462dad3569dbf",
                "md5": "f1cf3a9f76985f3d1aa49bf5c398a7e0",
                "sha256": "f8bb7806f0278d7ba323c4131d3e25008d3335a9f19e7624f7ae2410ba0fcd98"
            },
            "downloads": -1,
            "filename": "moesifasgi-1.0.10-py2.py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "f1cf3a9f76985f3d1aa49bf5c398a7e0",
            "packagetype": "bdist_wheel",
            "python_version": "py2.py3",
            "requires_python": null,
            "size": 20908,
            "upload_time": "2024-11-01T20:28:20",
            "upload_time_iso_8601": "2024-11-01T20:28:20.834442Z",
            "url": "https://files.pythonhosted.org/packages/77/a6/526557eff7d13282d0e51cbfd84ce76264dbbfee248a2f0462dad3569dbf/moesifasgi-1.0.10-py2.py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "f91445b7ab20fe3f18c115596ef73b177a0b01d678ea19d9f3b08ff2dbfeba0a",
                "md5": "33ddf8d06f59927f0096f2537ac08099",
                "sha256": "948407233ed3ae2de23c4f55aa50c49dc32f369a453b34f2fbc7954b144e16e3"
            },
            "downloads": -1,
            "filename": "moesifasgi-1.0.10.tar.gz",
            "has_sig": false,
            "md5_digest": "33ddf8d06f59927f0096f2537ac08099",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 25062,
            "upload_time": "2024-11-01T20:28:22",
            "upload_time_iso_8601": "2024-11-01T20:28:22.467572Z",
            "url": "https://files.pythonhosted.org/packages/f9/14/45b7ab20fe3f18c115596ef73b177a0b01d678ea19d9f3b08ff2dbfeba0a/moesifasgi-1.0.10.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-11-01 20:28:22",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "moesifasgi"
}
        
Elapsed time: 0.43292s