Wednesday, October 23, 2019

Help with AWS Lambda writing Bitcoin price to DynamoDB

Hi Guys,

I am a couple months into my Python journey, and as my first proper 'project' I'm trying to use AWS Lambda to write the Bitcoin price into DynamoDB. I was then looking to use Cloudwatch to automate this process and trigger the Lambda every 15 minutes or so. I am interested in Bitcoin, and so thought it would be a good start with getting to know AWS and Python.

When running the program from IDLE everything works as it should, and the data is written to DynamoDB multiple times. However, when I zip the file and then upload it to AWS, after I click 'Test' the Lambda only works once, and posts the wrong data, as can be seen here: https://ibb.co/7ygpHqp. The bottom 5 entries are me running the code in Idle and gives the correct data, the top one (with incorrect time) is the Lambda. Clicking 'Test' multiple times results in no new data being written to DynamoDB. If I delete the entry and then run Test again, the same entry gets written to Dynamo.

Here is my code, I would be massively grateful for any advice, either on Python or AWS.

import requests, json, boto3 from datetime import datetime bitstamp = requests.get('https://www.bitstamp.net/api/ticker/') timestamp = int(bitstamp.json()['timestamp']) dateTime = str(datetime.fromtimestamp(timestamp)) d = datetime.strptime(dateTime, "%Y-%m-%d %H:%M:%S") date = str(d.day) + '-' + str(d.month) + '-' + str(d.year) time = str(d.hour) + ':' + str(d.minute) + ':' + str(d.second) bitstampUSD = float(bitstamp.json()['ask']) dataSet = { 'time(unix)' : timestamp, 'date' : date, 'time' : time, 'bitstampUSD' : str(bitstampUSD) } def lambda_handler(event=None, context=None): dynamodb = boto3.resource('dynamodb') dynamoTable = dynamodb.Table('bitcoinData') dynamoTable.put_item( Item = dataSet ) lambda_handler() 

No comments:

Post a Comment