Ejemplo n.º 1
0
def solution_put_photo_info_ddb(user_id, filename, form, filesize):

    try:
        new_photo = Photo(id=filename,
                          user_id=user_id,
                          filename=filename,
                          filename_orig=form['file'].filename,
                          filesize=filesize,
                          upload_date=datetime.today(),
                          tags=form['tags'],
                          desc=form['desc'],
                          geotag_lat=form['geotag_lat'],
                          geotag_lng=form['geotag_lng'],
                          taken_date=datetime.strptime(form['taken_date'],
                                                       "%Y:%m:%d %H:%M:%S"),
                          make=form['make'],
                          model=form['model'],
                          width=form['width'],
                          height=form['height'],
                          city=form['city'],
                          nation=form['nation'],
                          address=form['address'])

        new_photo.save()

    except Exception as e:
        app.logger.error(
            "ERROR:failed to put item into Photo table:user_id:{}, filename:{}"
            .format(user_id, filename))
        app.logger.error(e)
        raise e
Ejemplo n.º 2
0
def solution_put_photo_info_ddb(user_id, filename, form, filesize):
    app.logger.info('RUNNING TODO#3 SOLUTION CODE:')
    app.logger.info('Update Photo information into User table!')
    app.logger.info(
        'Follow the steps in the lab guide to replace this method with your own implementation.'
    )

    new_photo = Photo(id=filename,
                      user_id=user_id,
                      filename=filename,
                      filename_orig=form['file'].filename,
                      filesize=filesize,
                      upload_date=datetime.today(),
                      tags=form['tags'],
                      desc=form['desc'],
                      geotag_lat=form['geotag_lat'],
                      geotag_lng=form['geotag_lng'],
                      taken_date=datetime.strptime(form['taken_date'],
                                                   "%Y:%m:%d %H:%M:%S"),
                      make=form['make'],
                      model=form['model'],
                      width=form['width'],
                      height=form['height'],
                      city=form['city'],
                      nation=form['nation'],
                      address=form['address'])

    new_photo.save()
Ejemplo n.º 3
0
def create_table():
    if not User.exists():
        app.logger.debug('Creating DynamoDB User table..')
        User.create_table(read_capacity_units=app.config['DDB_RCU'],
                          write_capacity_units=app.config['DDB_WCU'],
                          wait=True)
    if not Photo.exists():
        app.logger.debug('Creating DynamoDB Photo table..')
        Photo.create_table(read_capacity_units=app.config['DDB_RCU'],
                           write_capacity_units=app.config['DDB_WCU'],
                           wait=True)
Ejemplo n.º 4
0
 def test_get_mode_thumb_orig(self):
     """Ensure the /photos/<photo_id>?mode=thumbnail route behaves correctly."""
     access_token, _ = cognito_signin(boto3.client('cognito-idp'), existed_user)
     # 1. upload
     upload['file'] = (BytesIO(b'my file contents'), 'test_image.jpg')
     response = self.client.post(
         '/photos/file',
         headers=self.test_header,
         content_type='multipart/form-data',
         data=upload
     )
     self.assert200(response)
     photo_id = [item.id for item in Photo.scan(Photo.filename_orig.startswith('test_image.jpg'), limit=1)]
     # 2. thumbnails
     data = {'mode': 'thumbnails'}
     response = self.client.get(
         '/photos/{}'.format(photo_id[0]),
         headers=self.test_header,
         content_type='application/json',
         query_string=data
     )
     self.assert200(response)
     # 3. original
     data = {'mode': 'original'}
     response = self.client.get(
         '/photos/{}'.format(photo_id),
         headers=self.test_header,
         content_type='application/json',
         query_string=data
     )
     self.assert200(response)
    def delete(self, photo_id):
        """one photo delete"""
        token = get_token_from_header(request)
        user = get_cognito_user(token)
        try:
            photo = Photo.get(user['user_id'], photo_id)
            photo.delete()
            file_deleted = delete_s3(photo.filename, user['email'])

            if file_deleted:
                app.logger.debug(
                    'success:photo deleted: user_id:{}, photo_id:{}'.format(
                        user['user_id'], photo_id))
                return make_response(
                    {
                        'ok': True,
                        'photos': {
                            'photo_id': photo_id
                        }
                    }, 200)
            else:
                raise FileNotFoundError
        except FileNotFoundError as e:
            raise InternalServerError(e)
        except Exception as e:
            raise InternalServerError(e)
Ejemplo n.º 6
0
    def get(self, photo_id):
        """
        Return image for thumbnail and original photo.
        :param photo_id: target photo id
        :queryparam mode: None(original) or thumbnail
        :return: image url for authenticated user
        """
        try:
            mode = request.args.get('mode')
            user = get_jwt_identity()
            email = user['email']
            path = os.path.join(app.config['UPLOAD_FOLDER'],
                                email_normalize(email))
            full_path = Path(path)
            photo = Photo.get(user['user_id'], range_key=photo_id)

            if photo.id == photo_id:
                if mode == 'thumbnail':
                    full_path = full_path / 'thumbnails' / photo.filename
                else:
                    full_path = full_path / photo.filename

            with full_path.open('rb') as f:
                contents = f.read()
                resp = make_response(contents)

            app.logger.debug('filepath: {}'.format(str(full_path)))
            resp.content_type = 'image/jpeg'
            return resp
        except Exception as e:
            app.logger.error(
                'ERROR:get photo failed:photo_id:{}'.format(photo_id))
            app.logger.error(e)
            return 'http://placehold.it/400x300'
    def delete(self, photo_id):
        """one photo delete"""
        token = get_token_from_header(request)
        try:
            user = get_cognito_user(token)
            photo = Photo.get(user['user_id'], photo_id)
            photo.delete()

            file_deleted = delete_s3(photo.filename, user['email'])

            if file_deleted:
                app.logger.debug(
                    "success:photo deleted: user_id:{}, photo_id:{}".format(
                        user['user_id'], photo_id))
                return m_response({'photo_id': photo_id}, 200)
            else:
                raise FileNotFoundError

        except FileNotFoundError as e:
            app.logger.error('ERROR:not exist photo_id:{}'.format(photo_id))
            return err_response('ERROR:not exist photo_id:{}'.format(photo_id),
                                404)
        except Exception as e:
            app.logger.error(
                "ERROR:photo delete failed: photo_id:{}".format(photo_id))
            app.logger.error(e)
            return err_response(
                "ERROR:photo delete failed: photo_id:{}".format(photo_id), 500)
def solution_delete_photo_from_ddb(user, photo_id):
    app.logger.info('RUNNING TODO#4 SOLUTION CODE:')
    app.logger.info('Delete a photo from photos list, and update!')
    app.logger.info('Follow the steps in the lab guide to replace this method with your own implementation.')

    photo = Photo.get(user['user_id'], photo_id)
    photo.delete()
    filename = photo.filename

    return filename
Ejemplo n.º 9
0
def solution_put_photo_info_ddb(user_id, filename, form, filesize):
    new_photo = Photo(id=filename,
                      user_id=user_id,
                      filename=filename,
                      filename_orig=form['file'].filename,
                      filesize=filesize,
                      upload_date=datetime.today(),
                      tags=form['tags'],
                      desc=form['desc'],
                      geotag_lat=form['geotag_lat'],
                      geotag_lng=form['geotag_lng'],
                      taken_date=datetime.strptime(form['taken_date'], "%Y:%m:%d %H:%M:%S"),
                      make=form['make'],
                      model=form['model'],
                      width=form['width'],
                      height=form['height'],
                      city=form['city'],
                      nation=form['nation'],
                      address=form['address'])
    new_photo.save()
Ejemplo n.º 10
0
    def setUp(self):
        # Delete any test data that may be remained.
        for item in User.scan(User.username.startswith('test')):
            item.delete()
        for item in Photo.scan(Photo.filename_orig.startswith('test')):
            item.delete()

        # Create test user
        test_user = User(uuid.uuid4().hex)
        test_user.email = user['email']
        test_user.username = user['username']
        test_user.password = generate_password_hash(user['password'])
        test_user.save()
Ejemplo n.º 11
0
    def get(self):
        """Get all photos as list"""
        try:
            photos = [
                photo_deserialize(photo)
                for photo in Photo.query(get_jwt_identity()['user_id'])
            ]
            app.logger.debug('success:photos_list: {}'.format(photos))
            return make_response({'ok': True, 'photos': photos}, 200)

        except Exception as e:
            app.logger.error('Photos list retrieving failed')
            app.logger.error(e)
            raise InternalServerError('Photos list retrieving failed')
    def get(self):
        """Get all photos as list"""
        token = get_token_from_header(request)
        try:
            user = get_cognito_user(token)
            photos = Photo.query(user['user_id'])
            data = {'photos': []}
            [data['photos'].append(with_presigned_url(user, photo)) for photo in photos]
            app.logger.debug('success:photos_list: {}'.format(data))
            return make_response({'ok': True, 'photos': data['photos']}, 200)

        except Exception as e:
            app.logger.error('ERROR:photos list failed')
            app.logger.error(e)
            raise InternalServerError('Photos list retrieving failed')
Ejemplo n.º 13
0
    def get(self):
        """Get all photos as list"""

        data = {'photos': []}
        try:
            photos = Photo.query(get_jwt_identity()['user_id'])
            for photo in photos:
                data['photos'].append(photo_deserialize(photo))

            app.logger.debug("success:photos_list:{}".format(data))
            return m_response(data['photos'], 200)
        except Exception as e:
            app.logger.error("ERROR:photos list failed")
            app.logger.error(e)
            return err_response(e, 500)
Ejemplo n.º 14
0
def solution_put_photo_info_ddb(user_id, filename, form, filesize):
    app.logger.info("RUNNING TODO#3 SOLUTION CODE:")
    app.logger.info("Update Photo information into User table!")
    app.logger.info(
        "Follow the steps in the lab guide to replace this method with your own implementation."
    )

    try:
        new_photo = Photo(id=filename,
                          user_id=user_id,
                          filename=filename,
                          filename_orig=form['file'].filename,
                          filesize=filesize,
                          upload_date=datetime.today(),
                          tags=form['tags'],
                          desc=form['desc'],
                          geotag_lat=form['geotag_lat'],
                          geotag_lng=form['geotag_lng'],
                          taken_date=datetime.strptime(form['taken_date'],
                                                       "%Y:%m:%d %H:%M:%S"),
                          make=form['make'],
                          model=form['model'],
                          width=form['width'],
                          height=form['height'],
                          city=form['city'],
                          nation=form['nation'],
                          address=form['address'])

        new_photo.save()

    except Exception as e:
        app.logger.error(
            "ERROR:failed to put item into Photo table:user_id:{}, filename:{}"
            .format(user_id, filename))
        app.logger.error(e)
        raise e
Ejemplo n.º 15
0
    def get(self):
        """Get all photos as list"""
        token = get_token_from_header(request)
        try:
            user = get_cognito_user(token)
            photos = Photo.query(user['user_id'])

            data = {'photos': []}
            [data['photos'].append(with_presigned_url(user, photo)) for photo in photos]

            app.logger.debug("success:photos_list:{}".format(data))

            return m_response(data['photos'], 200)
        except Exception as e:
            app.logger.error("ERROR:photos list failed")
            app.logger.error(e)
            return err_response(e, 500)
Ejemplo n.º 16
0
    def get(self):
        """Get all photos as list"""

        try:
            user = get_jwt_identity()
            photos = Photo.query(get_jwt_identity()['user_id'])
            data = {'photos': []}
            [
                data['photos'].append(with_presigned_url(user, photo))
                for photo in photos
            ]
            app.logger.debug("success:photos_list:{}".format(data))
            return make_response({'ok': True, 'photos': data['photos']}, 200)

        except Exception as e:
            app.logger.error('Photos list retrieving failed')
            app.logger.error(e)
            raise InternalServerError('Photos list retrieving failed')
Ejemplo n.º 17
0
 def test_delete(self):
     """Ensure the /photos/<photo_id> route behaves correctly."""
     # 1. upload
     upload['file'] = (BytesIO(b'my file contents'), 'test_image.jpg')
     response = self.client.post(
         '/photos/file',
         headers=self.test_header,
         content_type='multipart/form-data',
         data=upload
     )
     self.assert200(response)
     photo_id = [item.id for item in Photo.scan(Photo.filename_orig.startswith('test_image.jpg'), limit=1)]
     # 2. delete
     response = self.client.delete(
         '/photos/{}'.format(photo_id[0]),
         headers=self.test_header,
         content_type='application/json',
     )
     self.assert200(response)
Ejemplo n.º 18
0
def create_photo_info(filename, filesize, form):
    new_photo = Photo(id=filename,
                      filename=filename,
                      filename_orig=form['file'].filename,
                      filesize=filesize,
                      upload_date=datetime.today(),
                      tags=form['tags'],
                      desc=form['desc'],
                      geotag_lat=form['geotag_lat'],
                      geotag_lng=form['geotag_lng'],
                      taken_date=datetime.strptime(form['taken_date'], "%Y:%m:%d %H:%M:%S"),
                      make=form['make'],
                      model=form['model'],
                      width=form['width'],
                      height=form['height'],
                      city=form['city'],
                      nation=form['nation'],
                      address=form['address'])

    app.logger.debug('new_photo: {0}'.format(photo_deserialize(new_photo)))
    return new_photo
Ejemplo n.º 19
0
def create_table():
    Photo.create_table()
    print("Dynamodb Photos table created")
    pass
Ejemplo n.º 20
0
def delete_table():
    Photo.delete_table()
    print("Dynamodb Users table deleted")
 def test_photo_table(self):
     """Ensure the DDB Photo table is available."""
     self.assertEqual(Photo.exists(), True)
from cloudalbum.database.model_ddb import Photo
from flask import current_app as app

if not Photo.exists():
    Photo.create_table(read_capacity_units=app.config['DDB_RCU'],
                       write_capacity_units=app.config['DDB_WCU'],
                       wait=True)
    app.logger.debug('DynamoDB Photo table created!')


def create_table():
    Photo.create_table()
    app.logger.debug("Dynamodb Photos table created")


def delete_table():
    Photo.delete_table()
    app.logger.debug("Dynamodb Users table deleted")
Ejemplo n.º 23
0
 def tearDown(self):
     # Delete test data
     for item in User.scan(User.username.startswith('test')):
         item.delete()
     for item in Photo.scan(Photo.filename_orig.startswith('test')):
         item.delete()
def create_table():
    Photo.create_table()
    app.logger.debug("Dynamodb Photos table created")
def delete_table():
    ### User table is no longer needed
    # if User.exists():
    #     User.delete_table()
    if Photo.exists():
        Photo.delete_table()
Ejemplo n.º 26
0
def delete_table():
    if User.exists():
        User.delete_table()
    if Photo.exists():
        Photo.delete_table()
from cloudalbum.database.model_ddb import User, Photo
from flask import current_app as app

if not User.exists():
    User.create_table(read_capacity_units=app.config['DDB_RCU'], write_capacity_units=app.config['DDB_WCU'], wait=True)
    app.logger.debug('DynamoDB User table created!')

if not Photo.exists():
    User.create_table(read_capacity_units=app.config['DDB_RCU'], write_capacity_units=app.config['DDB_WCU'], wait=True)
    app.logger.debug('DynamoDB User table created!')


def create_table():
    User.create_table()
    Photo.create_table()
    app.logger.debug("Dynamodb Users & Photos table created")


def delete_table():
    User.delete_table()
    Photo.delete_table()
    app.logger.debug("Dynamodb Users & Photos table deleted")
def create_table():
    User.create_table()
    Photo.create_table()
    app.logger.debug("Dynamodb Users & Photos table created")
def delete_table():
    User.delete_table()
    Photo.delete_table()
    app.logger.debug("Dynamodb Users & Photos table deleted")