Beispiel #1
0
def deactivate_sensors():
    """
    This API is used to deactivate sensor with VTA and invoke lambda to stop publishing sensor data
    ---
    tags:
    - Sensor
    """
    try:
        sensorid = request.args.get('sensorid')
        table = dynamodb.Table('sensor')
        try:
            response = table.update_item(
                Key={'sensorid': sensorid},
                UpdateExpression="set sensorstatus = :status",
                ConditionExpression="sensorid = :id",
                ExpressionAttributeValues={
                    ':id': sensorid,
                    ':status': 'Inactive'
                },
                ReturnValues="UPDATED_NEW")
            url = 'https://cs5ti98u99.execute-api.us-west-2.amazonaws.com/prod/sensors'
            payload = {'sensorId': int(sensorid), 'op': 'stop'}
            headers = {'content-type': 'application/json'}
            r = requests.post(url, data=json.dumps(payload), headers=headers)
            return r.text
            return jsonify({
                'Success': True,
                'Message': 'Sensor deactivated successfully'
            })
        except Exception as e:
            return jsonify({'Success': False, 'Message': e.message})
    except Exception as e:
        return jsonify({'Success': False, 'Message': e.message})
Beispiel #2
0
def create():
    data_file = request.files.get('resume')
    data_values = request.form
    file_name = data_file.filename
    conn = S3Connection(
        (os.environ["AWS_ACCESS_KEY_ID"], os.environ["AWS_SECRET_ACCESS_KEY"]))
    bucket = conn.get_bucket("whackfall2017")
    k = Key(bucket)
    key = random.getrandbits(64)
    k.key = key
    k.set_contents_from_string(data_file.read())
    table = dynamodb.Table('WHACK_registered_userss')
    optional = [
        "first_hackathon", "links", "special_accomodations", "other_notes"
    ]
    new_items = {
        'name': data_values["first_name"] + " " + data_values["last_name"],
        'email': data_values["email"],
        'school': data_values["school"],
        'major': data_values["major"],
        'graduation_year': data_values["graduation_year"],
        'ethnicity': data_values["ethnicity"],
        'gender_identity': data_values["gender_identity"],
        'sexual_orientation': data_values["sexual_orientation"],
        'resume': data_values["file_name"],
        'resume_id': str(key),
    }
    for i in optional:
        if len(data_values[i]) > 0:
            new_items[i] = data_values[i]

    response = table.put_item(Item=new_items)
    return jsonify(name=file_name, response=response)
Beispiel #3
0
def register_sensors():
    """
    This API is used to register the sensors to sensorpool by the Sensor provider
    ---
    tags:
    - Sensorpool
    """
    try:
        request_item = {
            'sensorid': request.args.get('sensorid'),
            'sensorname': request.args.get('sensorname'),
            'manufacturer': request.args.get('manufactuter'),
            'sensortype': request.args.get('sensortype'),
            'provisionedto': request.args.get('proviionedto'),
            'sensorstatus': request.args.get('sensorstatus'),
        }
        print request_item['sensorid']
        table = dynamodb.Table('sensorpool')
        if not (check_user('sensorpool', 'sensorid',
                           request_item['sensorid'])):
            table.put_item(Item=request_item)
            return jsonify({
                'Success': True,
                'Message': 'Sensor created successfully'
            })
        else:
            return jsonify({
                'Success': False,
                'Message': 'Sensor already exists'
            })
    except Exception as e:
        return jsonify({'Success': False, 'Message': e.message})
Beispiel #4
0
def check_user(tablename, primarykey, value):
    try:
        table = dynamodb.Table(tablename)
        items = table.scan(FilterExpression=Attr(primarykey).eq(value))
        print items['Count']
        if items['Count'] == 1:
            return True
        else:
            return False
    except Exception as e:
        return False
Beispiel #5
0
def create_sensors():
    """
    This API is used to create/register new sensor with VTA
    ---
    tags:
    - Sensor
    """
    try:
        request_item = {
            'sensorid': request.args.get('sensorid'),
            'sensorname': request.args.get('sensorname'),
            'sensorgroup': request.args.get('sensorgroup'),
            'sensorhub': request.args.get('sensorhub'),
            'sensorstatus': request.args.get('sensorstatus'),
        }
        print request_item['sensorid']
        table = dynamodb.Table('sensor')
        if not (check_user('sensor', 'sensorid', request_item['sensorid'])):
            table.put_item(Item=request_item)
            pool_table = dynamodb.Table('sensorpool')
            response = pool_table.update_item(
                Key={'sensorid': request_item['sensorid']},
                UpdateExpression="set sensorstatus = :status",
                ConditionExpression="sensorid = :id",
                ExpressionAttributeValues={
                    ':id': request_item['sensorid'],
                    ':status': 'Provisioned'
                },
                ReturnValues="UPDATED_NEW")
            return jsonify({
                'Success': True,
                'Message': 'Sensor created successfully'
            })
        else:
            return jsonify({
                'Success': False,
                'Message': 'Sensor already procured by you'
            })
    except Exception as e:
        return jsonify({'Success': False, 'Message': e.message})
Beispiel #6
0
def delete_sensors():
    """
    This API is used to suspend sensor with VTA
    ---
    tags:
    - Sensor
    """
    try:
        sensorid = request.args.get('sensorid')
        print sensorid
        table = dynamodb.Table('sensor')
        if (check_user('sensor', 'sensorid', sensorid)):
            table.delete_item(Key={'sensorid': sensorid},
                              ConditionExpression="sensorid = :id",
                              ExpressionAttributeValues={
                                  ':id': sensorid,
                              })
            pool_table = dynamodb.Table('sensorpool')
            response = pool_table.update_item(
                Key={'sensorid': sensorid},
                UpdateExpression="set sensorstatus = :status",
                ConditionExpression="sensorid = :id",
                ExpressionAttributeValues={
                    ':id': sensorid,
                    ':status': 'Available'
                },
                ReturnValues="UPDATED_NEW")
            return response
            return jsonify({
                'Success': True,
                'Message': 'Sensor suspended successfully'
            })
        else:
            return jsonify({
                'Success': False,
                'Message': 'Sensor not suspended'
            })
    except Exception as e:
        return jsonify({'Success': False, 'Message': e.message})
def handler(event, context):
    g = event.get("menu_id")
    o = event.get("selection")
    selection = json.dumps(o)[1:-1:1]
    print selection
    print o
    dynamodb = boto3.resource('dynamodb', region_name='us-west-2')
    table = dynamodb.Table('PizzaShopMenu')
    test = json.dumps(o)
    print test
    response = table.update_item(Key={'menu_id': g},
                                 UpdateExpression="set selection= :r",
                                 ExpressionAttributeValues={':r': o},
                                 ReturnValues="UPDATED_NEW")
Beispiel #8
0
def verify_login():
    """
    This API is to authenticate users registered with Smart Sensor App
    ---
    tags:
        - User
    """
    user_table = dynamodb.Table('users')
    print request.authorization.username
    items = user_table.scan(
        FilterExpression=Attr('email').eq(request.authorization.username)
        and Attr('password').eq(request.authorization.password))
    if items['Count'] == 1:
        return jsonify(data={'Success': True, 'Message': 'Authenticated user'})
    else:
        return jsonify({'Success': False, 'Message': 'Invalid user'})
Beispiel #9
0
def create():
    start = time.time()
    data_file = request.files.get('resume')
    data_values = request.form
    file_name = data_file.filename
    conn = S3Connection(os.environ["AWS_ACCESS_KEY_ID"],
                        os.environ["AWS_SECRET_ACCESS_KEY"])
    bucket = conn.get_bucket("whackfall2017")
    k = Key(bucket)
    new_hash = random.getrandbits(64)
    key = data_values["file_name"][:-4]
    key += str(new_hash) + ".pdf"
    k.key = key
    k.set_contents_from_string(data_file.read())
    end_1 = time.time()
    table = dynamodb.Table('WHACK_registered_userss')
    optional = [
        "first_hackathon", "links", "special_accomodations", "other_notes",
        "goals", "teammates"
    ]
    new_items = {
        'name': data_values["first_name"] + " " + data_values["last_name"],
        'email': data_values["email"],
        'school': data_values["school"],
        'major': data_values["major"],
        'graduation_year': data_values["graduation_year"],
        'ethnicity': data_values["ethnicity"],
        'gender_identity': data_values["gender_identity"],
        'sexual_orientation': data_values["sexual_orientation"],
        'resume_id': key,
    }
    for i in optional:
        if len(data_values[i]) > 0:
            new_items[i] = data_values[i]

    response = table.put_item(Item=new_items)
    end_2 = time.time()
    send_email(data_values["first_name"], data_values["email"])
    end_3 = time.time()
    print("sending email took ")
    print(end_3 - end_2)
    print("putitng into AWS S3")
    print(end_2 - end_1)
    print("putting into DynamoDB")
    print(start - end_1)
    return jsonify(name=file_name, response=response)
Beispiel #10
0
def get_sensorpool():
    """
    This API is used to get all the availabe sensors from sensorpool
    ---
    tags:
    - Sensorpool
    """
    try:
        table = dynamodb.Table('sensorpool')
        items = table.scan()
        return jsonify({
            'Success': True,
            'Message': 'Request is successful',
            'Response': items,
            'Count': items['Count']
        })
    except Exception as e:
        return jsonify({'Success': False, 'Message': e.message})
Beispiel #11
0
def get_sensorgroups():
    """
    This API is used to get list of all sensor groups with VTA
    ---
    tags:
    - Sensor
    """
    try:
        table = dynamodb.Table('sensorGroups')
        items = table.scan()
        return jsonify({
            'Success': True,
            'Message': 'Request is successful',
            'Response': items['Items'],
            'Count': items['Count']
        })
    except Exception as e:
        return jsonify({'Success': False, 'Message': e.message})
Beispiel #12
0
def main(args):
    # Connect to the table.
    dynamodb = boto3.resource('dynamodb')
    my_table = dynamodb.Table(args.table)

    if not args.force:
        # Print a warning
        print 'About to delete all rows from table {}!!!'.format(args.table)
        print 'Are you sure? (type "YES" to continue)'
        response = raw_input().upper()
        if response != 'YES':
            print 'OK, not deleting anything!'
            quit()

    batch = my_table.batch_writer()
    response = my_table.scan()
    while 'LastEvaluatedKey' in response:
        for item in response['Items']:
            if args.range is None:
                batch.delete_item(
                    Key={args.key_attribute: item[args.key_attribute]})
            else:
                batch.delete_item(
                    Key={
                        args.key_attribute: item[args.key_attribute],
                        args.range: item[args.range]
                    })
        response = my_table.scan(
            ExclusiveStartKey=response['LastEvaluatedKey'])
    for item in response['Items']:
        if args.range is None:
            batch.delete_item(
                Key={args.key_attribute: item[args.key_attribute]})
        else:
            batch.delete_item(
                Key={
                    args.key_attribute: item[args.key_attribute],
                    args.range: item[args.range]
                })

    batch.__exit__(None, None, None)
Beispiel #13
0
def update_sensor_status(sensorid, status):
    """
    This API is used to Update the sensor status using sensor id in Sensorpool
    ---
    tags:
    - Sensorpool
    """
    table = dynamodb.Table('sensorpool')
    try:
        table.update_item(Key={'sensorid': sensorid},
                          UpdateExpression="set sensorstatus = :status",
                          ConditionExpression="sensorid = :id",
                          ExpressionAttributeValues={
                              ':id': sensorid,
                              ':status': status
                          },
                          ReturnValues="UPDATED_NEW")
        return jsonify({
            'Success': True,
            'Message': 'Record updated successfully'
        })
    except Exception as e:
        return jsonify({'Success': False, 'Message': e.message})
def handler(event, context):
    print "Hello World12"
    dynamodb0 = boto3.resource('dynamodb', region_name='us-west-2')
    table0 = dynamodb0.Table('Orders')
    # Your code goes here!
    e = event.get("menu_id")
    f = event.get("order_id")
    g = event.get("customer_name")
    h = event.get("customer_email")
    response = table0.put_item(
        Item={
            'menu_id': e,
            'order_id': f,
            'customer_name': g,
            'customer_email': h,
            'orders': {
                'selection': "NULL",
                'size': "NULL",
                'cost': "NULL",
                'order_time': "NULL"
            }
        })
    #print(json.dumps(response, indent=4, cls=DecimalEncoder))
    dynamodb = boto3.resource('dynamodb', region_name='us-west-2')
    table = dynamodb.Table('PizzaShopMenu')
    response = table.get_item(ProjectionExpression="selection",
                              Key={'menu_id': e})
    item = response['Item']
    t = json.dumps(item['selection'])
    choice_list = t[1:-1:1].split(",")
    string = " "
    for i, choice in enumerate(choice_list, start=1):
        string = string + str(i) + ". " + choice.split('"')[1] + "    "
    return "Message: Hi " + event.get(
        "customer_name"
    ) + ", please choose one of these selection:" + string[:-4:]
Beispiel #15
0
def register_users():
    """
    This API is to register new users with Smart Sensor App
    ---
    tags:
        - User
    """
    try:
        request_item = json.loads(request.data)
        print request_item['email']
        table = dynamodb.Table('users')
        if not (check_user('users', 'email', request_item['email'])):
            table.put_item(Item=request_item)
            return jsonify({
                'Success': True,
                'Message': 'User created successfully'
            })
        else:
            return jsonify({
                'Success': False,
                'Message': 'User already exists'
            })
    except Exception as e:
        return jsonify({'Success': False, 'Message': e.message})
                                  'WriteCapacityUnits': 10
                              })

# wait for table to create
table.meta.client.get_waiter('table_exists').wait(
    TableName='aws_pythonic_dynamodb')

# Print
print(table.item_count)

# Using the Created table
import boto3

dynamodb = boto3.resource('dynamodb')

table = dynamodb.Table('aws_pythonic_dynamodb')

print(table.creation_date_time)

# Creating Item to the Table
table.put_item(Item={
    'Name': 'YOUR_NNAME',
    'Entry_ID': 1,
    'ID': 101,
    'Place': 'USA'
})

# Get the Item
response = table.get_item(Key={'Entry_ID': 1, 'ID': 101})
item = response['Item']
print(item)
Beispiel #17
0
def handler(event,context):
    print "Hello World"
    
    dynamodb0 = boto3.resource('dynamodb', region_name='us-west-2')
    table0 = dynamodb0.Table('Orders')
                # Your code goes here!
    g = event.get("input")
    o = event.get("order_id")
    selection_number = int(json.dumps(g)[1:-1:1])-1

    response = table0.get_item(ProjectionExpression="menu_id, orders.selection",
                          Key={
                          'order_id': o
                          }
                          )
    item1 = response['Item']
    t = item1['menu_id']
    t2 = item1['orders']['selection']

    if(t2 == "NULL"):
        print "True"
        dynamodb = boto3.resource('dynamodb', region_name='us-west-2')
        table = dynamodb.Table('PizzaShopMenu')
        response1 = table.get_item(ProjectionExpression="selection",
                            Key={
                            'menu_id': t
                            }
                            )
        item = response1['Item']
        test = json.dumps(item['selection'])
        choice_list = test[1:-1:1].split(",")
        choice =  (choice_list[selection_number])[1:-1:1]
        if (choice[0].isalpha()==False) :
            choice = choice[1:]

        dynamodb0 = boto3.resource('dynamodb', region_name='us-west-2')
        table0 = dynamodb0.Table('Orders')
        response = table0.update_item(
                                    Key={
                                        'order_id': o
                                },
        UpdateExpression="set orders.selection = :r, order_status  = :a",
        ExpressionAttributeValues={
            ':r': choice,
            ':a': "processing"
        },
        ReturnValues="UPDATED_NEW"
        )

        dynamodb1 = boto3.resource('dynamodb', region_name='us-west-2')
        table = dynamodb1.Table('PizzaShopMenu')
        response = table.get_item(ProjectionExpression="size",
                            Key={
                            'menu_id': t
                            }
                            )
        item = response['Item']
        t = json.dumps(item['size'])
        size_list = t[1:-1:1].split(",")
        string = " "
        for i,size in enumerate(size_list,start=1):
            string = string + str(i)+". "+size.split('"')[1]+"    "
        return "Message : Which size do you want?"+ string[:-4:]

    else:
        dynamodb = boto3.resource('dynamodb', region_name='us-west-2')
        table = dynamodb.Table('PizzaShopMenu')
        response1 = table.get_item(ProjectionExpression="size,price",
                            Key={
                            'menu_id': t
                            }
                            )
        item = response1['Item']
        test = json.dumps(item['size'])
        choice_list = test[1:-1:1].split(",")
        choice =  (choice_list[selection_number])[1:-1:1]
        if (choice[0].isalpha()==False) :
            choice = choice[1:]
        
        test3 = item['price']
        costs =  test3[selection_number]
        print costs
        localtime   = time.localtime()
        timeString  = time.strftime("%m-%d-%Y@%H:%M:%S", localtime)

        dynamodb0 = boto3.resource('dynamodb', region_name='us-west-2')
        table0 = dynamodb0.Table('Orders')
        response = table0.update_item(
                                    Key={
                                        'order_id': o
                                },
        UpdateExpression="set orders.size = :r, orders.cost = :p, orders.order_time = :q",
        ExpressionAttributeValues={
            ':r': choice,
            ':p': costs,
            ':q': timeString
        },
        ReturnValues="UPDATED_NEW"
        )

        #todays =  str(datetime.date.today())
        #date_time = datetime.datetime.strptime(todays, '%m-%d-%Y')
        #print date_time

        return "Message : Your order costs $"+str(costs)+". We will email you when the order is ready. Thank you!"
Beispiel #18
0
def handler(event, context):
    g = event.get("menu_id")
    dynamodb = boto3.resource('dynamodb', region_name='us-west-2')
    table = dynamodb.Table('PizzaShopMenu')
    response = table.delete_item(Key={'menu_id': event['menu_id']})
    return {}
Beispiel #19
0
# from django.shortcuts import render, redirect
# from django.contrib.auth.forms import UserCreationForm
# from django.contrib.auth.decorators import login_required
from django import forms
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from boto3.dynamodb.conditions import Key, Attr
import boto3
import botocore
import boto.dynamodb

dynamodb = boto3.resource('dynamodb',
                          aws_access_key_id='YOUR_KEY',
                          aws_secret_access_key='YOUR_KEY',
                          region_name='us-east-2')
table = dynamodb.Table('users')


def exists(self, attri):
    val = self.cleaned_data.get(attri)
    response = table.scan(FilterExpression=Attr(attri).eq(val))
    if len(response['Items']) == 0:  # cannot find in db
        return False
    else:  # if already in db
        return True


class RegisterForm(forms.Form):
    username = forms.CharField(label='Username', min_length=4, max_length=150)
    email = forms.EmailField(label='Email')
    phone = forms.CharField(label='Phone')