Esempio n. 1
0
def lambda_handler(event, context):
    logger.info('got event{}'.format(event))

    site = deserialize_site(event)
    if site is None:
        return respond(
            '400',
            '{ "errorCode": "400", "errorMessage":"Bad Request: No valid Site data sent in the body."}'
        )

    # Check to see if there are any items already existing with that slug
    existing_site_check = Site.find(site.slug)
    if existing_site_check is not None:
        return respond(
            '400',
            '{ "errorCode": "400", "errorMessage":"Bad Request: Duplicate slug value specified. This must be a unique value for each site."}'
        )

    # Actually create the record now
    if not site.save():
        return respond(
            '400',
            '{ "errorCode": "400", "errorMessage":"Bad Request: Unable to create record due to failed validation checks."}'
        )
    else:
        response_body = Site.find(site.slug).to_json(
        )  # Reload the object from the database to ensure that any on-save hooks are accounted for
        return respond('200', response_body)
Esempio n. 2
0
 def test_get_one(self):
     site = Site.find('test_site_1')
     self.assertEqual("123 Fake Street", site.address)
     self.assertEqual('test_site_1', site.name)
     self.assertEqual('Yellow', site.availability_status)
     self.assertEqual(False, site.is_open)
     self.assertEqual('8-4', site.hours)
Esempio n. 3
0
def lambda_handler(event, context):
    #get the site name from the url
    if 'pathParameters' not in event:
        return respond(
            '400',
            '{ "errorCode": "400", "errorMessage":"Bad Request: No Site Slug specified in the path"}'
        )
    if 'sitename' not in event['pathParameters']:
        return respond(
            '400',
            '{ "errorCode": "400", "errorMessage":"Bad Request: No Site Slug found in the path parameters"}'
        )
    site_name = urllib.parse.unquote(event['pathParameters']['sitename'])

    if len(site_name) == 0:
        return respond(
            '400',
            '{ "errorCode": "400", "errorMessage":"Bad Request: Empty sitename"}'
        )

    site = Site.find(site_name)

    if site is None:
        return respond(
            '404', '{ "errorCode": "404", "errorMessage":"Invalid site name"}')

    return respond('200', site.to_json())
Esempio n. 4
0
def lambda_handler(event, context):
    logger.info('got event{}'.format(event))
    #get the site name from the url
    if 'pathParameters' not in event:
        return respond(
            '400',
            '{ "errorCode": "400", "errorMessage":"Bad Request: No Site Slug specified in the path"}'
        )
    if 'sitename' not in event['pathParameters']:
        return respond(
            '400',
            '{ "errorCode": "400", "errorMessage":"Bad Request: No Site Slug found in the path parameters"}'
        )
#    site_name = urllib.parse.unquote(event['pathParameters']['sitename'])
# TODO: implement url decoding, or do pattern validation on the sitename
    site_name = event['pathParameters']['sitename']

    if len(site_name) == 0:
        return respond(
            '400',
            '{ "errorCode": "400", "errorMessage":"Bad Request: Empty sitename"}'
        )

    site = Site.find(site_name)
    if site is None:
        return respond(
            '404',
            '{ "errorCode": "404", "errorMessage":"Not Found: no Site found with that slug"}'
        )

    #actually delete the site
    site.delete()
    return respond('200', '')
Esempio n. 5
0
def lambda_handler(event, context):
    logger.info('got event{}'.format(event))

    site = deserialize_site(event)
    if site is None:
        return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: No valid Site data sent in the body."}')

    # Check to see if there are any items already existing with that slug
    existing_site_check = Site.find(site.slug)
    if existing_site_check is not None:
        return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: Duplicate slug value specified. This must be a unique value for each site."}')

    # Actually create the record now
    if not site.save():
        return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: Unable to create record due to failed validation checks."}')
    else:
        response_body = Site.find(site.slug).to_json() # Reload the object from the database to ensure that any on-save hooks are accounted for
        return respond('200', response_body)
Esempio n. 6
0
    def test_create_new(self):
        # Keep track of the initial set, so that we can discern which changes were caused by this test
        starting_sites = Site.all()

        site = Site()
        site.name = 'Chris\' Awesome Test Site #1'
        site.slug = 'chris-awesome-test-site-1'
        site.xstreet = '1234 Fake Street'
        site.xcity = 'Universal City'
        site.xzip = '78005'
        # site.latitude = Decimal('175.1')
        # site.longitude = Decimal('176.0')
        site.latitude = '175.1'
        site.longitude = '176.0'
        site.opentime = '10am'
        site.closetime = '6pm'
        site.days = 'M-T'
        site.sitecoordinator = None  # TODO: test variations of this too
        site.sitetype = 'Tax Preparation'

        site.is_open = True

        result = site.save()
        self.assertEqual(200, result, 'Failed to save the new site')
        # Validate that the record was indeed written out to the DB
        self.assertEqual(
            len(starting_sites) + 1, len(Site.all()),
            'No Site record was actually written')

        # # Now fetch the site data back out
        site2 = Site.find('chris-awesome-test-site-1')
        self.assertEqual('Chris\' Awesome Test Site #1', site2.name)
        self.assertEqual('chris-awesome-test-site-1', site2.slug)
        self.assertEqual("1234 Fake Street", site2.xstreet)
        self.assertEqual('Universal City', site2.xcity)
        self.assertEqual('78005', site2.xzip)
        # self.assertEqual(Decimal('175.1'), site2.latitude)
        # self.assertEqual(Decimal('176.0'), site2.longitude)
        self.assertEqual('175.1', site2.latitude)
        self.assertEqual('176.0', site2.longitude)
        self.assertEqual('10am', site2.opentime)
        self.assertEqual('6pm', site2.closetime)
        self.assertEqual('M-T', site2.days)
        self.assertEqual(None, site2.sitecoordinator)
        self.assertEqual(True, site2.is_open)

        # Delete the newly created site
        self.assertEqual(200, site2.delete())
        self.assertEqual(
            len(starting_sites), len(Site.all()),
            'The site creation test failed to clean up after itself')
Esempio n. 7
0
    def test_create_new(self):
        # Keep track of the initial set, so that we can discern which changes were caused by this test
        starting_sites = Site.all()

        site = Site()
        site.name = 'Chris\' Awesome Test Site #1'
        site.slug = 'chris-awesome-test-site-1'
        site.xstreet = '1234 Fake Street'
        site.xcity = 'Universal City'
        site.xzip = '78005'
        # site.latitude = Decimal('175.1')
        # site.longitude = Decimal('176.0')
        site.latitude = '175.1'
        site.longitude = '176.0'
        site.opentime = '10am'
        site.closetime = '6pm'
        site.days = 'M-T'
        site.sitecoordinator = None # TODO: test variations of this too
        site.sitetype = 'Tax Preparation'

        site.is_open = True

        result = site.save()
        self.assertEqual(200, result, 'Failed to save the new site')
        # Validate that the record was indeed written out to the DB
        self.assertEqual(len(starting_sites)+1, len(Site.all()), 'No Site record was actually written')

        # # Now fetch the site data back out
        site2 = Site.find('chris-awesome-test-site-1')
        self.assertEqual('Chris\' Awesome Test Site #1', site2.name)
        self.assertEqual('chris-awesome-test-site-1', site2.slug)
        self.assertEqual("1234 Fake Street", site2.xstreet)
        self.assertEqual('Universal City', site2.xcity)
        self.assertEqual('78005', site2.xzip)
        # self.assertEqual(Decimal('175.1'), site2.latitude)
        # self.assertEqual(Decimal('176.0'), site2.longitude)
        self.assertEqual('175.1', site2.latitude)
        self.assertEqual('176.0', site2.longitude)
        self.assertEqual('10am', site2.opentime)
        self.assertEqual('6pm', site2.closetime)
        self.assertEqual('M-T', site2.days)
        self.assertEqual(None, site2.sitecoordinator)
        self.assertEqual(True, site2.is_open)
        
        # Delete the newly created site
        self.assertEqual(200, site2.delete())
        self.assertEqual(len(starting_sites), len(Site.all()), 'The site creation test failed to clean up after itself')
Esempio n. 8
0
    def test_delete_site(self):
        # Make note of the starting site count
        starting_sites = Site.all()

        # Create a Site manually first so that we isolate this test to only the Update API
        raw_site = Site()
        raw_site.name = 'tc_lambda_sites_test_delete_site'
        raw_site.address = '123 tc_lambda_sites_test_delete_site street'
        raw_site.availability_status = 'Green'
        raw_site.hours = '12-12'
        raw_site.is_open = True
        raw_site.save()
        self.assertEqual("123 tc_lambda_sites_test_delete_site street",
                         raw_site.address)
        self.assertEqual('tc_lambda_sites_test_delete_site', raw_site.name)
        self.assertEqual('Green', raw_site.availability_status)
        self.assertEqual(True, raw_site.is_open)
        self.assertEqual('12-12', raw_site.hours)

        event = {
            'httpMethod': 'DELETE',
            'path': '/site/tc_lambda_sites_test_delete_site',
            'resource': '/site/{sitename}',
            'pathParameters': {
                'sitename': 'tc_lambda_sites_test_delete_site'
            },
            'body': None,
        }

        response = LambdaApiHandler.site_apis(event)
        self.assertEqual('', response['body'])
        self.assertEqual('200', response['statusCode'])
        self.assertEqual(
            len(starting_sites), len(Site.all()),
            'The Delete Site API failed to destroy the record it created.')

        # Fetch the site separately and validate the content
        site = Site.find('tc_lambda_sites_test_delete_site')
        self.assertIsNone(site)

        # Cleanup.
        if raw_site != None:
            raw_site.delete()
        # Cleanup validation
        self.assertEqual(len(starting_sites), len(Site.all()),
                         "Failed to clean up the site we created!")
Esempio n. 9
0
def lambda_handler(event, context):
    #get the site name from the url
    if 'pathParameters' not in event:
        return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: No Site Slug specified in the path"}')
    if 'sitename' not in event['pathParameters']:
        return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: No Site Slug found in the path parameters"}')
    site_name = urllib.parse.unquote(event['pathParameters']['sitename'])

    if len(site_name) == 0: 
        return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: Empty sitename"}')
        
    site = Site.find(site_name)

    if site is None:
        return respond('404', '{ "errorCode": "404", "errorMessage":"Invalid site name"}')

    return respond('200', site.to_json())
Esempio n. 10
0
 def test_get_one(self):
     site = Site.find('chris-awesome-test-site-2')
     self.assertIsNotNone(site, 'Default site not found. This probably needs to be created manually')
     self.assertEqual('Chris\' Awesome Test Site #2', site.name)
     self.assertEqual('chris-awesome-test-site-2', site.slug)
     self.assertEqual("1234 Fake Street", site.xstreet)
     self.assertEqual('Universal City', site.xcity)
     self.assertEqual('78005', site.xzip)
     # self.assertEqual(Decimal('175.1'), site.latitude)
     # self.assertEqual(Decimal('176.0'), site.longitude)
     self.assertEqual('175.1', site.latitude)
     self.assertEqual('176.0', site.longitude)
     self.assertEqual('10am', site.opentime)
     self.assertEqual('6pm', site.closetime)
     self.assertEqual('M-T', site.days)
     self.assertEqual(None, site.sitecoordinator)
     self.assertEqual(True, site.is_open)
Esempio n. 11
0
    def test_create_site(self):
        event = {
            'httpMethod':
            'PUT',
            'path':
            '/site',
            'resource':
            '/site',
            'pathParameters':
            None,
            'body':
            json.dumps({
                "Site": {
                    "name": "tc_lambda_sites_test_create_site",
                    "address": "1234 Fake Street",
                    "hours": "8-3",
                    "is_open": False,
                    "availability_status": "Red"
                }
            }),
        }
        # Make note of the starting site count
        starting_sites = Site.all()

        response = LambdaApiHandler.site_apis(event)
        self.assertEqual('200', response['statusCode'])
        self.assertEqual(len(starting_sites) + 1, len(Site.all()))

        # Fetch the site separately and validate the content
        site = Site.find('tc_lambda_sites_test_create_site')
        self.assertIsNotNone(site)
        self.assertEqual('tc_lambda_sites_test_create_site', site.name)
        self.assertEqual("1234 Fake Street", site.address)
        self.assertEqual('Red', site.availability_status)
        self.assertEqual(False, site.is_open)
        self.assertEqual('8-3', site.hours)

        # Cleanup.
        if site != None:
            site.delete()
        # Cleanup validation
        self.assertEqual(len(starting_sites), len(Site.all()),
                         "Failed to clean up the site we created!")
Esempio n. 12
0
 def test_get_one(self):
     site = Site.find('chris-awesome-test-site-2')
     self.assertIsNotNone(
         site,
         'Default site not found. This probably needs to be created manually'
     )
     self.assertEqual('Chris\' Awesome Test Site #2', site.name)
     self.assertEqual('chris-awesome-test-site-2', site.slug)
     self.assertEqual("1234 Fake Street", site.xstreet)
     self.assertEqual('Universal City', site.xcity)
     self.assertEqual('78005', site.xzip)
     # self.assertEqual(Decimal('175.1'), site.latitude)
     # self.assertEqual(Decimal('176.0'), site.longitude)
     self.assertEqual('175.1', site.latitude)
     self.assertEqual('176.0', site.longitude)
     self.assertEqual('10am', site.opentime)
     self.assertEqual('6pm', site.closetime)
     self.assertEqual('M-T', site.days)
     self.assertEqual(None, site.sitecoordinator)
     self.assertEqual(True, site.is_open)
Esempio n. 13
0
def lambda_handler(event, context):
    logger.info('got event{}'.format(event))
#get the site name from the url
    if 'pathParameters' not in event:
        return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: No Site Slug specified in the path"}')
    if 'sitename' not in event['pathParameters']:
        return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: No Site Slug found in the path parameters"}')
#    site_name = urllib.parse.unquote(event['pathParameters']['sitename'])
    # TODO: implement url decoding, or do pattern validation on the sitename
    site_name = event['pathParameters']['sitename']

    if len(site_name) == 0: 
        return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: Empty sitename"}')
        
    site = Site.find(site_name)
    if site is None: 
        return respond('404', '{ "errorCode": "404", "errorMessage":"Not Found: no Site found with that slug"}')
    
    #actually delete the site
    site.delete()
    return respond('200', '')
Esempio n. 14
0
    def test_create_new(self):
        site = Site()
        site.name = 'test_site_2'
        site.address = '234 Fake Street'
        site.availability_status = 'Green'
        site.hours = '1-2'
        site.is_open = True

        result = site.save()
        self.assertTrue(result, 'Failed to save the new site')
        # Validate that the record was indeed written out to the DB
        self.assertEqual(2, len(Site.all()))

        # Now fetch the site data back out
        site2 = Site.find('test_site_2')
        self.assertEqual("234 Fake Street", site.address)
        self.assertEqual('test_site_2', site.name)
        self.assertEqual('Green', site.availability_status)
        self.assertEqual(True, site.is_open)
        self.assertEqual('1-2', site.hours)

        # Delete the newly created site
        site2.delete()
        self.assertEqual(1, len(Site.all()))
Esempio n. 15
0
    def test_update_site(self):
        # Make note of the starting site count
        starting_sites = Site.all()

        # Create a Site manually first so that we isolate this test to only the Update API
        raw_site = Site()
        raw_site.name = 'tc_lambda_sites_test_update_site'
        raw_site.address = '123 tc_lambda_sites_test_update_site street'
        raw_site.availability_status = 'Green'
        raw_site.hours = '12-12'
        raw_site.is_open = True

        raw_site.save()
        self.assertEqual("123 tc_lambda_sites_test_update_site street",
                         raw_site.address)
        self.assertEqual('tc_lambda_sites_test_update_site', raw_site.name)
        self.assertEqual('Green', raw_site.availability_status)
        self.assertEqual(True, raw_site.is_open)
        self.assertEqual('12-12', raw_site.hours)

        event = {
            'httpMethod':
            'POST',
            'path':
            '/site/tc_lambda_sites_test_update_site',
            'resource':
            '/site/{sitename}',
            'pathParameters': {
                'sitename': 'tc_lambda_sites_test_update_site'
            },
            'body':
            json.dumps({
                "Site": {
                    "name": raw_site.name,
                    "address": "123 tc_lambda_sites_test_update_site parkway",
                    "hours": raw_site.hours,
                    "is_open": raw_site.is_open,
                    "availability_status": raw_site.availability_status
                }
            }),
        }

        response = LambdaApiHandler.site_apis(event)
        self.assertEqual('', response['body'])
        self.assertEqual('200', response['statusCode'])
        self.assertEqual(
            len(starting_sites) + 1, len(Site.all()),
            'Somehow the Update Site API created a new entry')

        # Fetch the site separately and validate the content
        site = Site.find('tc_lambda_sites_test_update_site')
        self.assertIsNotNone(site)
        self.assertEqual('tc_lambda_sites_test_update_site', site.name)
        self.assertEqual("123 tc_lambda_sites_test_update_site parkway",
                         site.address)
        self.assertEqual('Green', site.availability_status)
        self.assertEqual(True, site.is_open)
        self.assertEqual('12-12', site.hours)

        # Cleanup.
        if raw_site != None:
            raw_site.delete()
        # Cleanup validation
        self.assertEqual(len(starting_sites), len(Site.all()),
                         "Failed to clean up the site we created!")
Esempio n. 16
0
    def site_apis(event):
        """ Handle all of the Site Management API endpoints """
        response_body = ''
        response_code = '200'

        site_name = None if event['pathParameters'] == None else event[
            'pathParameters']['sitename']
        site_data = LambdaApiHandler.deserialize_site(
            event
        )  # This will simply return None if there is no (correctly formatted) data in the request body

        if event['httpMethod'] == 'GET':
            if site_name == None:
                # Fetch all sites
                print("Fetching all sites")
                sites = Site.all()
                sites_json = []
                for site in sites:
                    sites_json.append(site.to_json())
                j = ','.join(sites_json)
                response_body = "[ " + j + " ]"
                response_code = '200'
                print("Compiled response: " + response_code + " : " +
                      response_body)
            else:
                # Fetch single site
                print("Querying a single site: " + site_name)
                site = Site.find(site_name)
                response_body = site.to_json()
                response_code = '200'

        elif event['httpMethod'] == 'PUT':
            # Create a new site
            if site_data == None:
                response_body = '{"error":"Invalid Site data in request body"}'
                response_code = '400'
            else:
                if site_data.save():
                    response_body = Site.find(site_data.name).to_json(
                    )  # Reload the object from the database to ensure that any on-save hooks are accounted for
                    response_code = '200'
                else:
                    response_body = '{"error":"failed to create site"}'
                    response_code = '500'

        elif event['httpMethod'] == 'POST':
            # Update an existing site status
            if site_name == None:
                response_body = '{"error":"bad request. Please specify the sitename path parameter"}'
                response_code = '400'
            elif site_data == None:
                response_body = '{"error":"Invalid Site data in request body"}'
                response_code = '400'
            else:
                if site_data.save():
                    response_body = ''
                    response_code = '200'
                else:
                    response_body = '{"error":"failed to update site"}'
                    response_code = '500'

        elif event['httpMethod'] == 'DELETE':
            # Destroy an existing Site
            if site_name == None:
                response_body = '{"error":"bad request. Please specify the sitename path parameter"}'
                response_code = '400'
            else:
                site = Site.find(site_name)
                if site == None:
                    response_body = '{"error":"Invalid site_name"}'
                    response_code = '400'
                elif site.delete():
                    response_body = ''
                    response_code = '200'
                else:
                    response_body = '{"error":"failed to delete site"}'
                    response_code = '400'
        else:
            response_body = '{"error":"bad request"}'
            response_code = '400'

        #utilities.respond(response_code, response_body) # TODO: test this method before implementing
        return {
            'statusCode': response_code,
            'body': response_body,
            'headers': {
                'Content-Type': 'application/json'
            },
        }
Esempio n. 17
0
def lambda_handler(event, context):
    logger.info('got event{}'.format(event))
    # Extract the ID from the path parameters
    if 'pathParameters' not in event:
        return respond(
            '400',
            '{ "errorCode": "400", "errorMessage":"Bad Request: No Site Slug specified in the path"}'
        )
    if 'sitename' not in event['pathParameters']:
        return respond(
            '400',
            '{ "errorCode": "400", "errorMessage":"Bad Request: No Site Slug found in the path parameters"}'
        )
    if 'body' not in event:
        return respond(
            '400',
            '{ "errorCode": "400", "errorMessage":"Bad Request: No Site data attached in the request body."}'
        )
    if event['body'] is None:
        return respond(
            '400',
            '{ "errorCode": "400", "errorMessage":"Bad Request: No valid Site data attached in the request body."}'
        )

    #site_name = urllib.parse.unquote(event['pathParameters']['sitename'])
    # TODO: either validate that the sitename is a properly-formatted slug, or run it through url decoding first
    site_name = event['pathParameters']['sitename']

    # Fetch from the DB and validate that a record WAS found
    site = Site.find(site_name)
    update_count = 0
    if site is None:
        return respond(
            '404', '{ "errorCode": "404", "errorMessage":"Invalid site name"}')

    # Check for fields being updated
    site_data = json.loads(event['body'])
    if 'name' in site_data:
        site.name = site_data['name']
        update_count += 1
    if 'xstreet' in site_data:
        site.xstreet = site_data['xstreet']
        update_count += 1
    if 'xcity' in site_data:
        site.xcity = site_data['xcity']
        update_count += 1
    if 'xzip' in site_data:
        site.xzip = site_data['xzip']
        update_count += 1
    if 'latitude' in site_data:
        site.latitude = site_data['latitude']
        update_count += 1
    if 'longitude' in site_data:
        site.longitude = site_data['longitude']
        update_count += 1
    if 'opentime' in site_data:
        site.opentime = site_data['opentime']
        update_count += 1
    if 'closetime' in site_data:
        site.closetime = site_data['closetime']
        update_count += 1
    if 'days' in site_data:
        site.days = site_data['days']
        update_count += 1
    if 'sitecoordinator' in site_data:
        site.sitecoordinator = site_data['sitecoordinator']
        update_count += 1
    if 'sitetype' in site_data:
        site.sitetype = site_data['sitetype']
        update_count += 1

    if update_count == 0:
        # return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: No (valid) fields updated in the request body."}')
        # On second thought, let's let this operation succeed. Why not?
        # As far as the requester is concerned, the updates they requested have already been applied.
        # Also, this will even be faster than submitting a PutItem request with no purpose.
        logger.debug(
            "No actual updates to run, so just return the site object as-is")
        return respond('200', site.to_json())

    results = site.save()
    if results is None:
        return respond(
            '500',
            '{ "errorCode": "500", "errorMessage":"Server error: failed to save"}'
        )

    # Reload the object from the database to ensure that any on-save hooks are accounted for
    response_body = Site.find(site.slug).to_json()
    return respond('200', response_body)
Esempio n. 18
0
    def site_apis(event):
        """ Handle all of the Site Management API endpoints """
        response_body = ''
        response_code = '200'

        site_name = None if event['pathParameters'] == None else event['pathParameters']['sitename']
        site_data = LambdaApiHandler.deserialize_site(event) # This will simply return None if there is no (correctly formatted) data in the request body
        
        if event['httpMethod'] == 'GET':
            if site_name == None:
                # Fetch all sites
                print("Fetching all sites")
                sites = Site.all()
                sites_json = []
                for site in sites:
                    sites_json.append(site.to_json())
                j = ','.join(sites_json)
                response_body = "[ " + j + " ]"
                response_code = '200'
                print("Compiled response: " + response_code + " : " + response_body)
            else:
                # Fetch single site
                print("Querying a single site: " + site_name)
                site = Site.find(site_name)
                response_body = site.to_json()
                response_code = '200'
        
        elif event['httpMethod'] == 'PUT':
            # Create a new site
            if site_data == None:
                response_body = '{"error":"Invalid Site data in request body"}'
                response_code = '400'
            else:
                if site_data.save():
                    response_body = Site.find(site_data.name).to_json() # Reload the object from the database to ensure that any on-save hooks are accounted for
                    response_code = '200'
                else:
                    response_body = '{"error":"failed to create site"}'
                    response_code = '500'
        
        elif event['httpMethod'] == 'POST':
            # Update an existing site status
            if site_name == None:
                response_body = '{"error":"bad request. Please specify the sitename path parameter"}'
                response_code = '400'
            elif site_data == None:
                response_body = '{"error":"Invalid Site data in request body"}'
                response_code = '400'
            else:
                if site_data.save():
                    response_body = ''
                    response_code = '200'
                else:
                    response_body = '{"error":"failed to update site"}'
                    response_code = '500'
        
        elif event['httpMethod'] == 'DELETE':
            # Destroy an existing Site
            if site_name == None:
                response_body = '{"error":"bad request. Please specify the sitename path parameter"}'
                response_code = '400'
            else:
                site = Site.find(site_name)
                if site == None:
                    response_body = '{"error":"Invalid site_name"}'
                    response_code = '400'
                elif site.delete():
                    response_body = ''
                    response_code = '200'
                else:
                    response_body = '{"error":"failed to delete site"}'
                    response_code = '400'
        else:
            response_body = '{"error":"bad request"}'
            response_code = '400'
        
        #utilities.respond(response_code, response_body) # TODO: test this method before implementing
        return {
            'statusCode': response_code,
            'body': response_body,
            'headers': {
                'Content-Type': 'application/json'
            },
        }
Esempio n. 19
0
def lambda_handler(event, context):
    logger.info('got event{}'.format(event))
    # Extract the ID from the path parameters
    if 'pathParameters' not in event:
        return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: No Site Slug specified in the path"}')
    if 'sitename' not in event['pathParameters']:
        return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: No Site Slug found in the path parameters"}')
    if 'body' not in event:
        return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: No Site data attached in the request body."}')
    if event['body'] is None:
        return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: No valid Site data attached in the request body."}')

    #site_name = urllib.parse.unquote(event['pathParameters']['sitename'])
    # TODO: either validate that the sitename is a properly-formatted slug, or run it through url decoding first
    site_name = event['pathParameters']['sitename']

    # Fetch from the DB and validate that a record WAS found
    site = Site.find(site_name)
    update_count = 0
    if site is None:
        return respond('404', '{ "errorCode": "404", "errorMessage":"Invalid site name"}')

    # Check for fields being updated
    site_data = json.loads(event['body'])
    if 'name' in site_data:
        site.name = site_data['name']
        update_count += 1
    if 'xstreet' in site_data:
        site.xstreet = site_data['xstreet']
        update_count += 1
    if 'xcity' in site_data:
        site.xcity = site_data['xcity']
        update_count += 1
    if 'xzip' in site_data:
        site.xzip = site_data['xzip']
        update_count += 1
    if 'latitude' in site_data:
        site.latitude = site_data['latitude']
        update_count += 1
    if 'longitude' in site_data:
        site.longitude = site_data['longitude']
        update_count += 1
    if 'opentime' in site_data:
        site.opentime = site_data['opentime']
        update_count += 1
    if 'closetime' in site_data:
        site.closetime = site_data['closetime']
        update_count += 1
    if 'days' in site_data:
        site.days = site_data['days']
        update_count += 1
    if 'sitecoordinator' in site_data:
        site.sitecoordinator = site_data['sitecoordinator']
        update_count += 1
    if 'sitetype' in site_data:
        site.sitetype = site_data['sitetype']
        update_count += 1

    if update_count == 0:
        # return respond('400', '{ "errorCode": "400", "errorMessage":"Bad Request: No (valid) fields updated in the request body."}')
        # On second thought, let's let this operation succeed. Why not?
        # As far as the requester is concerned, the updates they requested have already been applied.
        # Also, this will even be faster than submitting a PutItem request with no purpose.
        logger.debug("No actual updates to run, so just return the site object as-is")
        return respond('200', site.to_json())

    results = site.save()
    if results is None:
        return respond('500', '{ "errorCode": "500", "errorMessage":"Server error: failed to save"}')

    # Reload the object from the database to ensure that any on-save hooks are accounted for
    response_body = Site.find(site.slug).to_json()
    return respond('200', response_body)