Skip to content

Instantly share code, notes, and snippets.

@Yloganathan
Last active May 20, 2019 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yloganathan/d5418bf7f8b80fedf619a4952906f868 to your computer and use it in GitHub Desktop.
Save Yloganathan/d5418bf7f8b80fedf619a4952906f868 to your computer and use it in GitHub Desktop.
Example backend for AWS Lambda
import boto3
import time
import json
import random
import string
import decimal
print('Loading function')
dynamo = boto3.resource('dynamodb').Table('Ideas')
def handler(event, context):
operation = event['httpMethod']
operations = {
'POST': lambda x: create(x),
'GET': lambda x: get(x),
'PATCH': lambda x: update(x),
'DELETE': lambda x: delete(x)
}
if operation in operations:
return operations[operation](event)
else:
raise ValueError('Unrecognized operation "{}"'.format(operation))
def create(event):
data = json.loads(event['body'])
print('Executing create event' + json.dumps(data))
if 'title' not in data:
raise Exception("Couldn't create item.")
timestamp = int(time.time() * 1000)
item = {
'id': ''.join([random.choice(string.ascii_letters + string.digits) for n in range(6)]),
'title': data['title'],
'body': data['body'],
'upvotes': data['upvotes'],
'comments': data['comments'],
'createdAt': timestamp,
'updatedAt': timestamp,
}
# write the todo to the database
dynamo.put_item(Item=item)
return send_200_response(item)
def send_200_response(data):
response = {
"statusCode": 200,
"headers": {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': True,
},
"body": json.dumps(data, cls=DecimalEncoder)
}
return response
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
if o % 1 > 0:
return float(o)
else:
return int(o)
return super(DecimalEncoder, self).default(o)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment