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)
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)
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
def test_upload_invalid_file(self): with self.assertRaises(ValueError): img = Image(filename='invalid.txt') img.save()