Skip to content

Commit

Permalink
Add: Functions to update User and Company profiles
Browse files Browse the repository at this point in the history
Add: Functions to update User and Company profiles
Refactor: Update README.md
Bump version to 1.0.5
  • Loading branch information
Keyur committed Feb 11, 2020
1 parent 284875c commit 5302e1f
Show file tree
Hide file tree
Showing 5 changed files with 441 additions and 2 deletions.
184 changes: 184 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,190 @@ Type: `Boolean`

`LOG_BODY` is default to true, set to false to remove logging request and response body to Moesif.

## Update User

### Update A Single User
Create or update a user profile in Moesif.
The metadata field can be any customer demographic or other info you want to store.
Only the `user_id` field is required.
For details, visit the [Python API Reference](https://www.moesif.com/docs/api?python#update-a-user).

```python
from moesif_aws_lambda.middleware import *

moesif_options = {
'LOG_BODY': True,
'DEBUG': True,
}

# 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(user, moesif_options)
```

### Update Users in Batch
Similar to update_user, but used to update a list of users in one batch.
Only the `user_id` field is required.
For details, visit the [Python API Reference](https://www.moesif.com/docs/api?python#update-users-in-batch).

```python
from moesif_aws_lambda.middleware import *

moesif_options = {
'LOG_BODY': True,
'DEBUG': True,
}

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_batch([userA, userB], moesif_options)
```

## Update Company

### Update A Single Company
Create or update a company profile in Moesif.
The metadata field can be any company demographic or other info you want to store.
Only the `company_id` field is required.
For details, visit the [Python API Reference](https://www.moesif.com/docs/api?python#update-a-company).

```python
from moesif_aws_lambda.middleware import *

moesif_options = {
'LOG_BODY': True,
'DEBUG': True,
}

# 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(company, moesif_options)
```

### Update Companies in Batch
Similar to update_company, but used to update a list of companies in one batch.
Only the `company_id` field is required.
For details, visit the [Python API Reference](https://www.moesif.com/docs/api?python#update-companies-in-batch).

```python
from moesif_aws_lambda.middleware import *

moesif_options = {
'LOG_BODY': True,
'DEBUG': True,
}

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_batch([companyA, companyB], moesif_options)
```

## Examples

- [A complete example is available on GitHub](https://github.com/Moesif/moesif-aws-lambda-python-example).
Expand Down
23 changes: 22 additions & 1 deletion moesif_aws_lambda/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
from moesifapi.exceptions.api_exception import *
from moesifapi.models import *
from .client_ip import ClientIp
from .update_companies import Company
from .update_users import User
from datetime import *
import base64
import json
Expand All @@ -16,6 +18,25 @@
except ImportError:
from urllib.parse import urlencode

# Initialized the client
if os.environ["MOESIF_APPLICATION_ID"]:
api_client = MoesifAPIClient(os.environ["MOESIF_APPLICATION_ID"]).api
else:
raise Exception('Moesif Application ID is required in settings')

def update_user(user_profile, moesif_options):
User().update_user(user_profile, api_client, moesif_options)

def update_users_batch(user_profiles, moesif_options):
User().update_users_batch(user_profiles, api_client, moesif_options)

def update_company(company_profile, moesif_options):
Company().update_company(company_profile, api_client, moesif_options)

def update_companies_batch(companies_profiles, moesif_options):
Company().update_companies_batch(companies_profiles, api_client, moesif_options)


def MoesifLogger(moesif_options):
class log_data(LambdaDecorator):
def __init__(self, handler):
Expand Down Expand Up @@ -267,7 +288,7 @@ def after(self, retval):
# Send event to Moesif
if self.DEBUG:
print('Moesif Event Model:')
pprint(self.event)
print(json.dumps(self.event))

event_send = self.api_client.create_event(event_model)
if self.DEBUG:
Expand Down
117 changes: 117 additions & 0 deletions moesif_aws_lambda/update_companies.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
from moesifapi.moesif_api_client import *
from moesifapi.api_helper import *
from moesifapi.exceptions.api_exception import *
from moesifapi.models import *


class Company:


def update_company(self, company_profile, api_client, moesif_options):
DEBUG = moesif_options.get('DEBUG', False)
if not company_profile:
print('Expecting the input to be either of the type - CompanyModel, dict or json while updating company')
else:
if isinstance(company_profile, dict):
if 'company_id' in company_profile:
try:
api_client.update_company(CompanyModel.from_dictionary(company_profile))
if DEBUG:
print('Company Profile updated successfully')
except APIException as inst:
if 401 <= inst.response_code <= 403:
print("Unauthorized access sending event to Moesif. Please check your Appplication Id.")
if DEBUG:
print("Error while updating company, with status code:")
print(inst.response_code)
else:
print('To update an company, an company_id field is required')

elif isinstance(company_profile, CompanyModel):
if company_profile.company_id is not None:
try:
api_client.update_company(company_profile)
if DEBUG:
print('Company Profile updated successfully')
except APIException as inst:
if 401 <= inst.response_code <= 403:
print("Unauthorized access sending event to Moesif. Please check your Appplication Id.")
if DEBUG:
print("Error while updating company, with status code:")
print(inst.response_code)
else:
print('To update a company, a company_id field is required')
else:
try:
company_profile_json = APIHelper.json_deserialize(company_profile)
if 'company_id' in company_profile_json:
try:
api_client.update_company(CompanyModel.from_dictionary(company_profile_json))
if DEBUG:
print('Company Profile updated successfully')
except APIException as inst:
if 401 <= inst.response_code <= 403:
print("Unauthorized access sending event to Moesif. Please check your Appplication Id.")
if DEBUG:
print("Error while updating company, with status code:")
print(inst.response_code)
else:
print('To update a company, an company_id field is required')
except:
print('Error while deserializing the json, please make sure the json is valid')

def update_companies_batch(self, company_profiles, api_client, moesif_options):
DEBUG = moesif_options.get('DEBUG', False)
if not company_profiles:
print('Expecting the input to be either of the type - List of CompanyModel, dict or json while updating companies')
else:
if all(isinstance(company, dict) for company in company_profiles):
if all('company_id' in company for company in company_profiles):
try:
batch_profiles = [CompanyModel.from_dictionary(d) for d in company_profiles]
api_client.update_companies_batch(batch_profiles)
if DEBUG:
print('Company Profile updated successfully')
except APIException as inst:
if 401 <= inst.response_code <= 403:
print("Unauthorized access sending event to Moesif. Please check your Appplication Id.")
if DEBUG:
print("Error while updating companies, with status code:")
print(inst.response_code)
else:
print('To update companies, an company_id field is required')

elif all(isinstance(company, CompanyModel) for company in company_profiles):
if all(company.company_id is not None for company in company_profiles):
try:
api_client.update_companies_batch(company_profiles)
if DEBUG:
print('Company Profile updated successfully')
except APIException as inst:
if 401 <= inst.response_code <= 403:
print("Unauthorized access sending event to Moesif. Please check your Appplication Id.")
if DEBUG:
print("Error while updating companies, with status code:")
print(inst.response_code)
else:
print('To update companies, an company_id field is required')
else:
try:
company_profiles_json = [APIHelper.json_deserialize(d) for d in company_profiles]
if all(isinstance(company, dict) for company in company_profiles_json) and all(
'company_id' in user for user in company_profiles_json):
try:
batch_profiles = [CompanyModel.from_dictionary(d) for d in company_profiles_json]
api_client.update_companies_batch(batch_profiles)
if DEBUG:
print('Company Profile updated successfully')
except APIException as inst:
if 401 <= inst.response_code <= 403:
print("Unauthorized access sending event to Moesif. Please check your Appplication Id.")
if DEBUG:
print("Error while updating companies, with status code:")
print(inst.response_code)
else:
print('To update companies, an company_id field is required')
except:
print('Error while deserializing the json, please make sure the json is valid')
Loading

0 comments on commit 5302e1f

Please sign in to comment.