### Install Local Moesif Django Package Source: https://github.com/moesif/moesifdjango/blob/master/BUILDING.md Install the Moesif Django package from a local .tar.gz file after setting up your virtual environment. ```bash pip install --user path/to/moesifdjango.tar.gz ``` -------------------------------- ### Basic Middleware Setup (Django < 1.9) Source: https://github.com/moesif/moesifdjango/blob/master/README.md Activate the Moesif middleware by adding it to your `MIDDLEWARE_CLASSES` and configure essential settings like `APPLICATION_ID` and `LOG_BODY` in your Django settings. ```APIDOC ## Basic Middleware Setup (Django < 1.9) ### Description Activate the middleware by adding it to the `MIDDLEWARE_CLASSES` list in your Django settings file. ### Configuration Add the following to your Django settings file: ```python MIDDLEWARE_CLASSES = [ ..., 'moesifdjango.middleware_pre19.MoesifMiddlewarePre19', # other middlewares ] MOESIF_MIDDLEWARE = { 'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID', 'LOG_BODY': True, } ``` ### Parameters - `APPLICATION_ID` (String, Required): Your Moesif Application ID. - `LOG_BODY` (Boolean, Optional): Set to `True` to log request and response bodies. ``` -------------------------------- ### Install Moesif Django Middleware Source: https://github.com/moesif/moesifdjango/blob/master/README.md Install the Moesif Django middleware using pip. This command should be run in your project's virtual environment. ```shell pip install moesifdjango ``` -------------------------------- ### Run Django Tests Source: https://github.com/moesif/moesifdjango/blob/master/README.md Use this command to run tests for Django 1.10 or newer. Ensure you have installed Django and moesifdjango. ```bash python manage.py test ``` -------------------------------- ### Install and Configure Moesif Middleware (Django 1.10+) Source: https://context7.com/moesif/moesifdjango/llms.txt Add the moesif_middleware to your Django settings and configure your Application ID. Ensure it's placed after session and authentication middleware. ```python # Install # pip install moesifdjango # settings.py (Django 1.10+) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'moesifdjango.middleware.moesif_middleware', # <-- add after session/auth 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] MOESIF_MIDDLEWARE = { 'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID', # required 'LOG_BODY': True, # default: True 'LOCAL_DEBUG': False, # set True for verbose logging } ``` -------------------------------- ### Run Django Tests (Older Versions) Source: https://github.com/moesif/moesifdjango/blob/master/README.md Use this command to run tests for Django 1.9 or older. Ensure you have installed Django and moesifdjango. ```bash python manage.py test middleware_pre19_tests ``` -------------------------------- ### Install tzdata in Dockerfile Source: https://github.com/moesif/moesifdjango/blob/master/README.md Alternatively, install the tzdata package in your Dockerfile to fix timezone issues when using Docker with Ubuntu-based images. ```dockerfile RUN apt-get install tzdata ``` -------------------------------- ### Get Django Version Source: https://github.com/moesif/moesifdjango/blob/master/README.md Check your current Django version using this Python command. This is important for determining the correct middleware import style. ```python python -c "import django; print(django.get_version())" ``` -------------------------------- ### Docker Timezone Configuration for Moesif Django Source: https://context7.com/moesif/moesifdjango/llms.txt Set the `TZ` environment variable to `UTC` or install `tzdata` in your Dockerfile to ensure correct event timing when running in a Ubuntu-based Docker image. This prevents potential issues with missed events due to timezone discrepancies. ```dockerfile FROM python:3.10-slim # Option 1: set timezone env var ENV TZ=UTC # Option 2: install tzdata # RUN apt-get update && apt-get install -y tzdata COPY requirements.txt . RUN pip install -r requirements.txt COPY . /app WORKDIR /app CMD ["gunicorn", "myapp.wsgi:application", "--bind", "0.0.0.0:8000", "--preload"] # Note: --preload is required on macOS with gunicorn to avoid fork/thread issues. ``` -------------------------------- ### Set Up Virtual Environment Source: https://github.com/moesif/moesifdjango/blob/master/BUILDING.md Commands to create and activate a Python virtual environment for isolated package management. ```bash virtualenv ENV ``` ```bash source bin/activate ``` -------------------------------- ### Build Moesif Django Package Source: https://github.com/moesif/moesifdjango/blob/master/BUILDING.md Run this command from the root folder to create a distributable package in the 'dist' directory. ```bash python setup.py sdist ``` -------------------------------- ### Full Moesif Middleware Configuration with Callbacks Source: https://context7.com/moesif/moesifdjango/llms.txt Configure advanced options including user/company identification, session tokens, metadata, event skipping, and data masking using callback functions. ```python # settings.py def identify_user(req, res): """Return a string user ID for the request.""" if req.user and req.user.is_authenticated: return req.user.username return None def identify_company(req, res): """Return a string company ID for the request.""" return req.META.get('HTTP_X_COMPANY_ID', None) def should_skip(req, res): """Return True to skip logging this event entirely.""" return req.path.startswith('/health') or req.path.startswith('/metrics') def get_session_token(req, res): """Return a custom session/API token string.""" return req.META.get('HTTP_X_API_KEY', None) def get_metadata(req, res): """Return a JSON-serializable dict of custom metadata.""" return { 'datacenter': 'us-east-1', 'deployment_version': 'v2.1.0', 'tenant_id': req.META.get('HTTP_X_TENANT_ID'), } def mask_event(event_model): """Mutate and return the EventModel to remove sensitive fields.""" if event_model.response.body and 'password' in event_model.response.body: event_model.response.body['password'] = None if event_model.request.body and 'ssn' in event_model.request.body: event_model.request.body['ssn'] = None return event_model MOESIF_MIDDLEWARE = { 'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID', # Identity 'IDENTIFY_USER': identify_user, 'IDENTIFY_COMPANY': identify_company, # Session & metadata 'GET_SESSION_TOKEN': get_session_token, 'GET_METADATA': get_metadata, # Filtering & masking 'SKIP': should_skip, 'MASK_EVENT_MODEL': mask_event, 'REQUEST_HEADER_MASKS': ['Authorization', 'X-Api-Key'], 'RESPONSE_HEADER_MASKS': ['Set-Cookie'], 'REQUEST_BODY_MASKS': ['password', 'credit_card'], 'RESPONSE_BODY_MASKS': ['ssn', 'token'], # Body logging 'LOG_BODY': True, # Batching 'BATCH_SIZE': 25, # max events per batch, default 25 'EVENT_QUEUE_SIZE': 100000, # max queued events, default 1,000,000 # Authorization header parsing (for automatic user ID extraction) 'AUTHORIZATION_HEADER_NAME': 'Authorization', # or comma-separated: 'X-Api-Key,Authorization' 'AUTHORIZATION_USER_ID_FIELD': 'sub', # JWT payload field # Outgoing request capture 'CAPTURE_OUTGOING_REQUESTS': False, # Proxy (optional) 'BASE_URI': 'https://your-secure-proxy.example.com', # Debug 'LOCAL_DEBUG': False, } ``` -------------------------------- ### Configure Moesif Middleware (Legacy Django 1.9) Source: https://context7.com/moesif/moesifdjango/llms.txt For older Django versions, use MoesifMiddlewarePre19 in MIDDLEWARE_CLASSES and provide your Application ID. ```python # settings.py (Django 1.9 or older) MIDDLEWARE_CLASSES = [ 'moesifdjango.middleware_pre19.MoesifMiddlewarePre19', # other middlewares... ] MOESIF_MIDDLEWARE = { 'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID', 'LOG_BODY': True, } ``` -------------------------------- ### Gunicorn Preload Option Source: https://github.com/moesif/moesifdjango/blob/master/README.md Add the `--preload` option when launching gunicorn to resolve potential "in progress in another thread when fork() was called" errors on MacOS. ```bash gunicorn myapp.wsgi:application --bind 127.0.0.1:8000 --preload ``` -------------------------------- ### SKIP Configuration Option Source: https://github.com/moesif/moesifdjango/blob/master/README.md Configure the `SKIP` option to define a function that determines whether to skip capturing a specific event. ```APIDOC ## SKIP Configuration Option ### Description This option allows you to specify a function that returns `True` if a particular event should be skipped, preventing it from being sent to Moesif. ### Configuration Add the `SKIP` key to your `MOESIF_MIDDLEWARE` dictionary with a function as its value. ```python MOESIF_MIDDLEWARE = { 'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID', 'SKIP': lambda request, response: True, # Example: skip all events } ``` ### Parameters - `SKIP` (Function, Optional): A function that accepts `request` and `response` objects and returns a Boolean. If `True`, the event is skipped. ``` -------------------------------- ### Moesif Django Repository Structure Source: https://github.com/moesif/moesifdjango/blob/master/README.md Overview of the directory and file structure for the Moesif Django project. ```bash . ├── BUILDING.md ├── images/ ├── LICENSE ├── MANIFEST.in ├── moesifdjango/ ├── pull_request_template.md ├── README.md ├── requirements.txt ├── setup.cfg ├── setup.py └── tests/ ``` -------------------------------- ### Update Users in Batch in Moesif Source: https://github.com/moesif/moesifdjango/blob/master/README.md Use the `update_users_batch()` method to update multiple user profiles simultaneously. Similar to `update_user()`, `user_id` is mandatory, and `company_id` and `metadata` are optional for associating users with companies and storing custom information. ```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]) ``` -------------------------------- ### Update Single User Profile in Moesif Source: https://github.com/moesif/moesifdjango/blob/master/README.md Use the `update_user()` method to create or update a user profile. Only `user_id` is required. Optional fields include `company_id`, `campaign` for tracking ROI, and `metadata` for custom demographic information. ```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) ``` -------------------------------- ### Update a Single Subscription with Moesif Source: https://github.com/moesif/moesifdjango/blob/master/README.md Use `update_subscription` to create or update a subscription. Requires `subscription_id`, `company_id`, and `status`. The `metadata` field can store additional subscription details. ```python # 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) ``` -------------------------------- ### Configure Django MIDDLEWARE Source: https://github.com/moesif/moesifdjango/blob/master/README.md Add the Moesif middleware to your Django settings file's MIDDLEWARE array. It's recommended to place it after session and authentication middleware for richer data. ```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', ] ``` -------------------------------- ### Configure Moesif Django Middleware Options Source: https://github.com/moesif/moesifdjango/blob/master/README.md Configure Moesif Django middleware by defining Python functions for user identification, company identification, session token, skipping logic, event masking, and metadata. Ensure 'APPLICATION_ID' is set to your Moesif application ID. ```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, } ``` -------------------------------- ### Map Requests to User IDs with `IDENTIFY_USER` Source: https://context7.com/moesif/moesifdjango/llms.txt Implement `IDENTIFY_USER` to override automatic user detection and assign a custom user ID. It should return a string user ID or `None`. ```python def identify_user(req, res): # Prefer a custom header, fall back to authenticated user custom_id = req.META.get('HTTP_X_USER_ID') if custom_id: return custom_id if hasattr(req, 'user') and req.user.is_authenticated: return str(req.user.id) return None MOESIF_MIDDLEWARE = { 'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID', 'IDENTIFY_USER': identify_user, } ``` -------------------------------- ### Update Subscriptions in Batch with Moesif Source: https://github.com/moesif/moesifdjango/blob/master/README.md Use `update_subscriptions_batch` to update multiple subscriptions in a single call. Each subscription object must include `subscription_id`, `company_id`, and `status`. ```python 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]) ``` -------------------------------- ### Update Companies in Batch with Moesif Source: https://github.com/moesif/moesifdjango/blob/master/README.md Use `update_companies_batch` to update multiple companies simultaneously. Provide a list of company objects, each with at least a `company_id`. ```python 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]) ``` -------------------------------- ### Django 1.10+ MIDDLEWARE Configuration Source: https://github.com/moesif/moesifdjango/blob/master/README.md For Django 1.10 and newer, add the Moesif middleware to the MIDDLEWARE list in your settings. Ensure it's placed appropriately relative to other middleware. ```python MIDDLEWARE = [ ..., 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'moesifdjango.middleware.moesif_middleware' ... ``` -------------------------------- ### Map Requests to Company IDs with `IDENTIFY_COMPANY` Source: https://context7.com/moesif/moesifdjango/llms.txt Use `IDENTIFY_COMPANY` to associate events with a specific company or tenant by returning a string company ID. It can read IDs from request headers or other sources. ```python def identify_company(req, res): # Read tenant from a request header return req.META.get('HTTP_X_TENANT_ID', None) MOESIF_MIDDLEWARE = { 'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID', 'IDENTIFY_COMPANY': identify_company, } ``` -------------------------------- ### Configure Moesif Middleware Settings Source: https://github.com/moesif/moesifdjango/blob/master/README.md Define the MOESIF_MIDDLEWARE dictionary in your Django settings file to provide your Moesif Application ID and enable request/response body logging. ```python MOESIF_MIDDLEWARE = { 'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID', 'LOG_BODY': True, } ``` -------------------------------- ### Update Users in Batch Source: https://github.com/moesif/moesifdjango/blob/master/README.md Updates a list of user profiles in Moesif in a single batch operation using the `update_users_batch()` method. Each user object requires a `user_id` and can optionally include `company_id` and custom `metadata`. ```APIDOC ## Update Users in Batch ### Description To update a list of [users](https://www.moesif.com/docs/getting-started/users/) in one batch, use the `update_users_batch()` method. ### Method ```python middleware.update_users_batch(users_list) ``` ### Parameters #### Request Body - **users_list** (array) - Required - A list of user objects to update. - Each user object in the list should contain: - **user_id** (string) - Required - The unique identifier for the user. - **company_id** (string) - Optional - The identifier for the company the user belongs to. - **metadata** (object) - Optional - Any custom object with demographic or other information. ### Request Example ```python userA = { 'user_id': '12345', 'company_id': '67890', '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', '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]) ``` ### Response 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). ``` -------------------------------- ### Attach Custom Metadata with `GET_METADATA` Source: https://context7.com/moesif/moesifdjango/llms.txt Use `GET_METADATA` to return a JSON-serializable dictionary of custom data to be stored with each event. This is useful for custom filtering and analysis in Moesif. ```python import socket def get_metadata(req, res): return { 'host': socket.gethostname(), 'region': 'us-west-2', 'route_name': req.resolver_match.url_name if req.resolver_match else None, 'response_time_ms': getattr(req, '_moesif_duration_ms', None), 'feature_flags': getattr(req, 'active_flags', []), } MOESIF_MIDDLEWARE = { 'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID', 'GET_METADATA': get_metadata, } ``` -------------------------------- ### update_users_batch Source: https://context7.com/moesif/moesifdjango/llms.txt Sends a list of user profiles in a single API call for bulk updates. ```APIDOC ## update_users_batch — Bulk Update User Profiles ### Description Sends a list of user profiles in a single API call. ### Method ```python middleware.update_users_batch(user_profiles) ``` ### Parameters #### Request Body - **user_profiles** (list) - Required - A list of user profile dictionaries. ### Request Example ```json [ { "user_id": "usr_001", "company_id": "cmp_abc", "metadata": {"email": "bob@example.com", "plan": "pro"} }, { "user_id": "usr_002", "company_id": "cmp_abc", "metadata": {"email": "carol@example.com", "plan": "starter"} }, { "user_id": "usr_003", "metadata": {"email": "dave@example.com", "plan": "free"} } ] ``` ### Response All specified users upserted in a single request to Moesif. ``` -------------------------------- ### Update A Single User Source: https://github.com/moesif/moesifdjango/blob/master/README.md Creates or updates a user profile in Moesif using the `update_user()` method. Requires at least a `user_id` and can optionally include `company_id`, `campaign` details, and custom `metadata`. ```APIDOC ## Update A Single User ### Description To create or update a [user](https://www.moesif.com/docs/getting-started/users/) profile in Moesif, use the `update_user()` method. ### Method ```python middleware.update_user(user) ``` ### Parameters #### Request Body - **user** (object) - Required - An object containing user details. - **user_id** (string) - Required - The unique identifier for the user. - **company_id** (string) - Optional - The identifier for the company the user belongs to. - **campaign** (object) - Optional - Campaign details for tracking acquisition channels. - **metadata** (object) - Optional - Any custom object with demographic or other information. ### Request Example ```python user = { 'user_id': '12345', 'company_id': '67890', '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) ``` ### Response 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). ``` -------------------------------- ### Capture Outgoing Requests with Moesif Source: https://context7.com/moesif/moesifdjango/llms.txt Enable `CAPTURE_OUTGOING_REQUESTS` to automatically log HTTP calls made via the `requests` library. Specific callbacks like `IDENTIFY_USER_OUTGOING` and `SKIP_OUTGOING` can customize this logging. ```python def identify_user_outgoing(req, res): return 'service-account-stripe' def skip_outgoing(req, res): # Do not log internal health-check calls return 'internal-health' in req.url MOESIF_MIDDLEWARE = { 'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID', 'CAPTURE_OUTGOING_REQUESTS': True, # Outgoing-specific callbacks 'IDENTIFY_USER_OUTGOING': identify_user_outgoing, 'IDENTIFY_COMPANY_OUTGOING': lambda req, res: 'acme-corp', 'SKIP_OUTGOING': skip_outgoing, 'GET_METADATA_OUTGOING': lambda req, res: {'target_service': req.url.split('/')[2]}, 'GET_SESSION_TOKEN_OUTGOING': lambda req, res: req.headers.get('Authorization'), 'LOG_BODY_OUTGOING': True, } ``` -------------------------------- ### Uninstall Moesif Django Package Source: https://github.com/moesif/moesifdjango/blob/master/BUILDING.md Command to remove the Moesif Django package from your environment. ```bash pip uninstall moesifdjango ``` -------------------------------- ### Conditionally Skip Event Logging with `SKIP` Source: https://context7.com/moesif/moesifdjango/llms.txt Use the `SKIP` callback to prevent specific requests from being logged. It receives request and response objects and should return `True` to skip logging. ```python def should_skip(req, res): # Skip health-check and static asset requests skip_paths = ['/health/', '/readyz', '/static/'] if any(req.path.startswith(p) for p in skip_paths): return True # Skip successful OPTIONS preflight requests if req.method == 'OPTIONS' and res.status_code == 200: return True return False MOESIF_MIDDLEWARE = { 'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID', 'SKIP': should_skip, } ``` -------------------------------- ### IDENTIFY_COMPANY Configuration Option Source: https://github.com/moesif/moesifdjango/blob/master/README.md Configure the `IDENTIFY_COMPANY` option to specify a function that returns the company ID associated with an event. ```APIDOC ## IDENTIFY_COMPANY Configuration Option ### Description This option allows you to associate events with specific companies by providing a function that returns a unique company identifier string. ### Configuration Add the `IDENTIFY_COMPANY` key to your `MOESIF_MIDDLEWARE` dictionary with a function as its value. ```python MOESIF_MIDDLEWARE = { 'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID', 'IDENTIFY_COMPANY': lambda request, response: get_company_id_for_user(request.user), # Example: custom company ID logic } ``` ### Parameters - `IDENTIFY_COMPANY` (Function, Optional): A function that accepts `request` and `response` objects and returns a String representing the company ID. ``` -------------------------------- ### update_companies_batch Source: https://context7.com/moesif/moesifdjango/llms.txt Sends multiple company profiles in a single API call for bulk updates. ```APIDOC ## update_companies_batch — Bulk Update Company Profiles ### Description Sends multiple company profiles in a single API call. ### Method ```python middleware.update_companies_batch(company_profiles) ``` ### Parameters #### Request Body - **company_profiles** (list) - Required - A list of company profile dictionaries. ### Request Example ```json [ { "company_id": "cmp_001", "company_domain": "startup.io", "metadata": {"plan_name": "Growth", "mrr": 5000} }, { "company_id": "cmp_002", "company_domain": "bigcorp.com", "metadata": {"plan_name": "Enterprise", "mrr": 50000} } ] ``` ### Response Both specified company records upserted in a single Moesif API call. ``` -------------------------------- ### update_subscription Source: https://context7.com/moesif/moesifdjango/llms.txt Creates or updates a subscription record in Moesif. 'subscription_id', 'company_id', and 'status' are all required. ```APIDOC ## update_subscription — Create or Update a Subscription ### Description Creates or updates a subscription record. `subscription_id`, `company_id`, and `status` are all required. ### Method ```python middleware.update_subscription(subscription) ``` ### Parameters #### Request Body - **subscription** (dict) - Required - A dictionary representing the subscription. Must contain `subscription_id`, `company_id`, and `status`. ### Request Example ```json { "subscription_id": "sub_pro_99", "company_id": "cmp_67890", "status": "active", "metadata": { "plan_name": "Pro", "billing_cycle": "monthly", "mrr": 299, "currency": "USD", "trial_end": "2024-03-01" } } ``` ### Response Subscription record upserted in Moesif, linked to the specified company. ``` -------------------------------- ### Bulk Update User Profiles with Moesif Django Source: https://context7.com/moesif/moesifdjango/llms.txt Use `update_users_batch` to send a list of user profiles in a single API call to Moesif. This is efficient for updating multiple users at once. ```python from moesifdjango.middleware import moesif_middleware middleware = moesif_middleware(None) users = [ { 'user_id': 'usr_001', 'company_id': 'cmp_abc', 'metadata': {'email': 'bob@example.com', 'plan': 'pro'}, }, { 'user_id': 'usr_002', 'company_id': 'cmp_abc', 'metadata': {'email': 'carol@example.com', 'plan': 'starter'}, }, { 'user_id': 'usr_003', 'metadata': {'email': 'dave@example.com', 'plan': 'free'}, }, ] middleware.update_users_batch(users) # Result: All three users upserted in a single request to Moesif. ``` -------------------------------- ### Update Subscription Source: https://github.com/moesif/moesifdjango/blob/master/README.md Creates or updates a single subscription in Moesif. Requires `subscription_id`, `company_id`, and `status`. The `metadata` field can store additional subscription details. ```APIDOC ## Update Subscription ### Description Creates or updates a single subscription in Moesif. Requires `subscription_id`, `company_id`, and `status`. The `metadata` field can store additional subscription details. ### Method ```python middleware.update_subscription(subscription) ``` ### Parameters #### Request Body - **subscription** (object) - Required - A dictionary representing the subscription. - **subscription_id** (string) - Required - The unique identifier for the subscription. - **company_id** (string) - Required - The ID of the company this subscription belongs to. - **status** (string) - Required - The current status of the subscription (e.g., 'active'). - **metadata** (object) - Optional - Custom data about the subscription. ### Request Example ```python 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) ``` ### Response This method is a helper that calls the Moesif API library. Refer to the Moesif Python API reference for detailed response information. ``` -------------------------------- ### Bulk Update Company Profiles with Moesif Django Source: https://context7.com/moesif/moesifdjango/llms.txt Use `update_companies_batch` to send multiple company profiles in a single API call to Moesif. This is useful for updating several companies efficiently. ```python from moesifdjango.middleware import moesif_middleware middleware = moesif_middleware(None) companies = [ { 'company_id': 'cmp_001', 'company_domain': 'startup.io', 'metadata': {'plan_name': 'Growth', 'mrr': 5000}, }, { 'company_id': 'cmp_002', 'company_domain': 'bigcorp.com', 'metadata': {'plan_name': 'Enterprise', 'mrr': 50000}, }, ] middleware.update_companies_batch(companies) # Result: Both companies upserted in a single Moesif API call. ``` -------------------------------- ### Update Subscriptions in Batch Source: https://github.com/moesif/moesifdjango/blob/master/README.md Updates multiple subscriptions in a single batch request. Requires `subscription_id`, `company_id`, and `status` for each subscription. `metadata` can be used for custom data. ```APIDOC ## Update Subscriptions in Batch ### Description Updates multiple subscriptions in a single batch request. Requires `subscription_id`, `company_id`, and `status` for each subscription. `metadata` can be used for custom data. ### Method ```python middleware.update_subscriptions_batch(subscriptions) ``` ### Parameters #### Request Body - **subscriptions** (array) - Required - A list of subscription objects to update. - Each subscription object should have `subscription_id`, `company_id`, and `status`. - **subscription_id** (string) - Required - The unique identifier for the subscription. - **company_id** (string) - Required - The ID of the company this subscription belongs to. - **status** (string) - Required - The current status of the subscription (e.g., 'active'). - **metadata** (object) - Optional - Custom data about the subscription. ### Request Example ```python 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]) ``` ### Response This method is a helper that calls the Moesif API library. Refer to the Moesif Python API reference for detailed response information. ``` -------------------------------- ### Update Single Company Profile in Moesif Source: https://github.com/moesif/moesifdjango/blob/master/README.md Use the `update_company()` method to update a single company profile. The `company_id` is required. Optional fields include `campaign` for tracking ROI and `metadata` for custom company information. ```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 ``` -------------------------------- ### IDENTIFY_USER Configuration Option Source: https://github.com/moesif/moesifdjango/blob/master/README.md Use the `IDENTIFY_USER` option to provide a custom function for identifying users associated with an event. ```APIDOC ## IDENTIFY_USER Configuration Option ### Description This option is highly recommended for accurately identifying users. It allows you to define a function that returns a unique string identifier for the user making the request. ### Configuration Add the `IDENTIFY_USER` key to your `MOESIF_MIDDLEWARE` dictionary with a function as its value. ```python MOESIF_MIDDLEWARE = { 'APPLICATION_ID': 'YOUR_MOESIF_APPLICATION_ID', 'IDENTIFY_USER': lambda request, response: request.user.username, # Example: use Django's user username } ``` ### Parameters - `IDENTIFY_USER` (Function, Optional but Recommended): A function that accepts `request` and `response` objects and returns a String representing the user ID. ``` -------------------------------- ### Bulk Update Subscriptions with Moesif Django Source: https://context7.com/moesif/moesifdjango/llms.txt Use `update_subscriptions_batch` to send multiple subscription records in a single API call to Moesif. This is useful for updating several subscriptions efficiently. ```python from moesifdjango.middleware import moesif_middleware middleware = moesif_middleware(None) subscriptions = [ { 'subscription_id': 'sub_001', 'company_id': 'cmp_001', 'status': 'active', 'metadata': {'plan_name': 'Starter', 'mrr': 49}, }, { 'subscription_id': 'sub_002', 'company_id': 'cmp_002', 'status': 'canceled', 'metadata': {'plan_name': 'Pro', 'mrr': 0, 'canceled_at': '2024-02-15'}, }, ] middleware.update_subscriptions_batch(subscriptions) # Result: Both subscription records upserted in a single Moesif API call. ``` -------------------------------- ### Update Subscription with Moesif Django Source: https://context7.com/moesif/moesifdjango/llms.txt Use `update_subscription` to create or update a single subscription record in Moesif. `subscription_id`, `company_id`, and `status` are all required. ```python from moesifdjango.middleware import moesif_middleware middleware = moesif_middleware(None) subscription = { 'subscription_id': 'sub_pro_99', 'company_id': 'cmp_67890', 'status': 'active', # required: 'active', 'canceled', 'trialing', etc. 'metadata': { 'plan_name': 'Pro', 'billing_cycle': 'monthly', 'mrr': 299, 'currency': 'USD', 'trial_end': '2024-03-01', }, } middleware.update_subscription(subscription) # Result: Subscription record upserted in Moesif, linked to company cmp_67890. ``` -------------------------------- ### Update Companies in Batch Source: https://github.com/moesif/moesifdjango/blob/master/README.md Updates multiple companies in a single batch request. Similar to single company updates, `company_id` is required, and `metadata` can hold custom information. ```APIDOC ## Update Companies in Batch ### Description Updates multiple companies in a single batch request. Similar to single company updates, `company_id` is required, and `metadata` can hold custom information. ### Method ```python middleware.update_companies_batch(companies) ``` ### Parameters #### Request Body - **companies** (array) - Required - A list of company objects to update. - Each company object should have at least a `company_id`. - **company_id** (string) - Required - The unique identifier for the company. - **company_domain** (string) - Optional - The company's domain, used for enrichment. - **metadata** (object) - Optional - Custom data about the company. ### Request Example ```python companyA = { 'company_id': '67890', 'company_domain': 'acmeinc.com', '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', '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([companyA, companyB]) ``` ### Response This method is a helper that calls the Moesif API library. Refer to the Moesif Python API reference for detailed response information. ``` -------------------------------- ### update_user Source: https://context7.com/moesif/moesifdjango/llms.txt Creates or updates a user record in Moesif. Accepts a dict, a UserModel instance, or a JSON string. 'user_id' is required. ```APIDOC ## update_user — Create or Update a User Profile ### Description Creates or updates a user record in Moesif. Accepts a `dict`, a `UserModel` instance, or a JSON string. `user_id` is required. ### Method ```python middleware.update_user(user_profile) ``` ### Parameters #### Request Body - **user_profile** (dict | UserModel | str) - Required - A dictionary, UserModel instance, or JSON string representing the user profile. Must contain a `user_id`. ### Request Example ```json { "user_id": "usr_12345", "company_id": "cmp_67890", "campaign": { "utm_source": "google", "utm_medium": "cpc", "utm_campaign": "spring_launch" }, "metadata": { "email": "alice@example.com", "first_name": "Alice", "last_name": "Smith", "plan": "enterprise", "mrr": 4800 } } ``` ### Response User profile upserted in Moesif; future events with user_id='usr_12345' are linked to this record. ``` -------------------------------- ### Update a Single Company with Moesif Source: https://github.com/moesif/moesifdjango/blob/master/README.md Use `update_company` to add or update a single company's information in Moesif. The `company_id` is required, and the `metadata` field can store any custom company data. ```python 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) ``` -------------------------------- ### update_subscriptions_batch Source: https://context7.com/moesif/moesifdjango/llms.txt Sends multiple subscription records in a single API call for bulk updates. ```APIDOC ## update_subscriptions_batch — Bulk Update Subscriptions ### Description Sends multiple subscription records in a single API call. ### Method ```python middleware.update_subscriptions_batch(subscriptions) ``` ### Parameters #### Request Body - **subscriptions** (list) - Required - A list of subscription dictionaries. ### Request Example ```json [ { "subscription_id": "sub_001", "company_id": "cmp_001", "status": "active", "metadata": {"plan_name": "Starter", "mrr": 49} }, { "subscription_id": "sub_002", "company_id": "cmp_002", "status": "canceled", "metadata": {"plan_name": "Pro", "mrr": 0, "canceled_at": "2024-02-15"} } ] ``` ### Response Both specified subscription records upserted in a single Moesif API call. ``` -------------------------------- ### Capturing Outgoing API Calls Source: https://github.com/moesif/moesifdjango/blob/master/README.md Enable the capture of outgoing API calls to third-party services by setting the `CAPTURE_OUTGOING_REQUESTS` option. ```APIDOC ## Capturing Outgoing API Calls ### Description Capture calls made to third-party services by setting the `CAPTURE_OUTGOING_REQUESTS` option. ### Configuration Set the `CAPTURE_OUTGOING_REQUESTS` option in your `MOESIF_MIDDLEWARE` dictionary. For specific configuration options related to outgoing API calls, refer to the [Options For Outgoing API Calls](#options-for-outgoing-api-calls) section. ### Parameters - `CAPTURE_OUTGOING_REQUESTS` (Boolean, Optional): Set to `True` to enable capturing outgoing requests. ``` -------------------------------- ### Set Timezone in Dockerfile Source: https://github.com/moesif/moesifdjango/blob/master/README.md Set the TZ environment variable to UTC in your Dockerfile to resolve potential timezone issues when using Docker with Ubuntu-based images for event capturing. ```dockerfile ENV TZ=UTC ```