Last active
December 18, 2019 22:23
-
-
Save cooperreid-optimizely/bad41f7a28e6c5a45c914404a5836a2c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
import json | |
from botocore.vendored import requests | |
def resp(err = None, res = {}): | |
resp_body = {'message': str(err)} if err else res | |
return { | |
'statusCode': '400' if err else '200', | |
'body': json.dumps(resp_body), | |
'headers': { | |
'Content-Type': 'application/json', | |
}, | |
} | |
def lambda_handler(event, context): | |
err = None | |
res = {} | |
print('Received webhook: {}'.format(event['headers']['Host'])) | |
if event['httpMethod'] != 'POST': | |
return resp(ValueError('Must be a post request')) | |
# fetch snippet from Optimizely CDN | |
try: | |
snippet_metadata = json.loads(event['body']) | |
snippet_origin = snippet_metadata.get('data', {}).get('origin_url') | |
project_id = snippet_metadata.get('project_id') | |
snippet_updated = snippet_metadata.get('timestamp') | |
snippet_contents = requests.get(snippet_origin).text | |
except Exception as e: | |
err = e | |
# write snippet content to s3 | |
try: | |
s3 = boto3.resource('s3') | |
s3object = s3.Object('YOUR-AWS-S3-BUCKET-NAME', 'snippet/{}.js'.format(project_id)) | |
s3object.put(Body=snippet_contents, ACL='public-read', ContentType='application/javascript') | |
except Exception as e: | |
err = e | |
return resp(err, {'message': 'success'}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment