示例#1
0
    def test_image_model_save_and_extract(self):
        fname = 'test.jpg'
        img = Image(filename=fname)
        img.save()

        data = Image.query().first()

        self.assertEqual(data.id, img.id)
        self.assertEqual(data.filename, fname)
示例#2
0
    def __call__(self):
        if not self._test_files:
            raise RuntimeError('data already created')

        img_file = self._test_files.pop()
        filename = os.path.basename(img_file)
        target_path = os.path.join(TestConfig.STATIC_DIR,
                                   TestConfig.UPLOAD_DIR, filename)

        # if not exist, copy image to actual directory
        if not os.path.isfile(target_path):
            shutil.copy(img_file, target_path)
        saved_at = fake.past_date(start_date='-30d')

        return Image(filename=filename, saved_at=saved_at)
示例#3
0
    def test_update_image_state(self):
        fname = 'test.jpg'
        img = Image(filename=fname)
        img.save()

        # before update, no data is stored
        self.assertIsNotNone(img.original)

        img.update()

        target = f'{img.id:05d}.jpg'

        self.assertNotEqual(img.filename, fname)
        self.assertEqual(img.filename, target)
        # save original filename
        self.assertEqual(img.original, fname)
示例#4
0
def upload_image():
    img_file = request.files['file']

    if img_file:
        filename = secure_filename(img_file.filename)

        # rename if the same file name does exist
        if Image.query().filter_by(filename=filename).count() > 0:
            from datetime import datetime
            dttm = datetime.now()
            dttm = dttm.strftime('%Y%m%s%H%M%S')
            filename, ext = os.path.splitext(filename)
            # max length of filename is 64
            filename = f'{filename[:64-len(dttm)-len(ext)-1]}_{dttm}{ext}'
        elif len(filename) > 64:
            filename, ext = os.path.splitext(filename)
            # max length of filename is 64
            filename = f'{filename[:64-len(ext)]}{ext}'

        try:
            img = Image(filename=filename)
            img.save()
        except Exception:
            kwargs = {'status': 'error', 'message': 'failed to save image'}
            response = jsonify(kwargs)
            response.status_code = 400
        else:
            filepath = os.path.join(Config.UPLOAD_DIR, filename)
            img_file.save(os.path.join(Config.STATIC_DIR, filepath))

            kwargs = {'status': 'success', 'message': 'uploaded image'}
            data = {'img_id': img.id}
            response = jsonify(data=data, **kwargs)
            response.status_code = 201
    else:
        kwargs = {'status': 'error', 'message': 'failed to upload image'}
        response = jsonify(data=data, **kwargs)
        response.status_code = 400

    return response
示例#5
0
 def test_upload_invalid_file(self):
     with self.assertRaises(ValueError):
         img = Image(filename='invalid.txt')
         img.save()