def test09_delete_resources(self): """ should allow deleting resources """ uploader.upload("tests/logo.png", public_id="api_test3") resource = api.resource("api_test3") self.assertNotEqual(resource, None) api.delete_resources(["apit_test", "api_test2", "api_test3"]) self.assertRaises(api.NotFound, api.resource, ("api_test3"))
def test_upload_async(self, mocker): """should pass async value """ mocker.return_value = MOCK_RESPONSE async_option = {"async": True} uploader.upload(TEST_IMAGE, tags=[UNIQUE_TAG], **async_option) params = mocker.call_args[0][2] self.assertTrue(params['async'])
def test09a_delete_resources_by_prefix(self): """ should allow deleting resources by prefix """ uploader.upload("tests/logo.png", public_id="api_test_by_prefix") resource = api.resource("api_test_by_prefix") self.assertNotEqual(resource, None) api.delete_resources_by_prefix("api_test_by") self.assertRaises(api.NotFound, api.resource, ("api_test_by_prefix"))
def test09b_delete_resources_by_prefix(self): """ should allow deleting resources by tags """ uploader.upload("tests/logo.png", public_id="api_test4", tags=["api_test_tag_for_delete"]) resource = api.resource("api_test4") self.assertNotEqual(resource, None) api.delete_resources_by_tag("api_test_tag_for_delete") self.assertRaises(api.NotFound, api.resource, ("api_test4"))
def setUp(self): self.timestamp_tag = "api_test_tag_{0}".format(utils.now()) if ApiTest.initialized: return ApiTest.initialized = True cloudinary.reset_config() if not cloudinary.config().api_secret: return try: api.delete_resources(["api_test", "api_test2", "api_test3"]) except Exception: pass for transformation in ["api_test_transformation", "api_test_transformation2", "api_test_transformation3"]: try: api.delete_transformation(transformation) except Exception: pass for transformation in ["api_test_upload_preset", "api_test_upload_preset2", "api_test_upload_preset3", "api_test_upload_preset4"]: try: api.delete_upload_preset(transformation) except Exception: pass for id in ["api_test", "api_test2"]: uploader.upload("tests/logo.png", public_id=id, tags=["api_test_tag", self.timestamp_tag], context="key=value", eager=[{"width": 100, "crop": "scale"}])
def test_rename(self): """should successfully rename a file""" result = uploader.upload("tests/logo.png") uploader.rename(result["public_id"], result["public_id"]+"2") self.assertIsNotNone(api.resource(result["public_id"]+"2")) result2 = uploader.upload("tests/favicon.ico") self.assertRaises(api.Error, uploader.rename, result2["public_id"], result["public_id"]+"2") uploader.rename(result2["public_id"], result["public_id"]+"2", overwrite=True) self.assertEqual(api.resource(result["public_id"]+"2")["format"], "ico")
def test_rename(self): """should successfully rename a file""" result = uploader.upload(TEST_IMAGE, tags=[UNIQUE_TAG]) uploader.rename(result["public_id"], result["public_id"]+"2") self.assertIsNotNone(api.resource(result["public_id"]+"2")) result2 = uploader.upload(TEST_ICON, tags=[UNIQUE_TAG]) self.assertRaises(api.Error, uploader.rename, result2["public_id"], result["public_id"]+"2") uploader.rename(result2["public_id"], result["public_id"]+"2", overwrite=True) self.assertEqual(api.resource(result["public_id"]+"2")["format"], "ico")
def setUpClass(cls): cloudinary.reset_config() if not cloudinary.config().api_secret: return print("Running tests for cloud: {}".format(cloudinary.config().cloud_name)) for id in [API_TEST_ID, API_TEST_ID2]: uploader.upload("tests/logo.png", public_id=id, tags=[API_TEST_TAG, ], context="key=value", eager=[{"width": 100, "crop": "scale"}], overwrite=True)
def test19_delete_derived(self): """ should allow deleting all resource """ uploader.upload(TEST_IMAGE, public_id=API_TEST_ID5, eager=[{"width": 101, "crop": "scale"}]) resource = api.resource(API_TEST_ID5) self.assertNotEqual(resource, None) self.assertEqual(len(resource["derived"]), 1) api.delete_all_resources(keep_original=True) resource = api.resource(API_TEST_ID5) self.assertNotEqual(resource, None) self.assertEqual(len(resource["derived"]), 0)
def test19_delete_derived(self): """ should allow deleting all resource """ uploader.upload("tests/logo.png", public_id="api_test5", eager=[{"width": 101,"crop": "scale"}]) resource = api.resource("api_test5") self.assertNotEqual(resource, None) self.assertEqual(len(resource["derived"]), 1) api.delete_all_resources(keep_original=True) resource = api.resource("api_test5") self.assertNotEqual(resource, None) self.assertEqual(len(resource["derived"]), 0)
def setUpClass(cls): cloudinary.reset_config() if not cloudinary.config().api_secret: return print("Running tests for cloud: {}".format(cloudinary.config().cloud_name)) for id in [API_TEST_ID, API_TEST_ID2]: uploader.upload(TEST_IMAGE, public_id=id, tags=[API_TEST_TAG, ], context="key=value", eager=[API_TEST_TRANS_SCALE100], overwrite=True)
def test_remove_all_tags(self): """should successfully remove all tags""" result = uploader.upload(TEST_IMAGE, public_id=TEST_ID1) result2 = uploader.upload(TEST_IMAGE, public_id=TEST_ID2) uploader.add_tag("tag1", [result["public_id"], result2["public_id"]]) uploader.add_tag("tag2", result["public_id"]) self.assertEqual(api.resource(result["public_id"])["tags"], ["tag1", "tag2"]) self.assertEqual(api.resource(result2["public_id"])["tags"], ["tag1"]) uploader.remove_all_tags([result["public_id"], result2["public_id"]]) self.assertFalse("tags" in api.resource(result["public_id"])) self.assertFalse("tags" in api.resource(result2["public_id"]))
def test08_delete_derived(self): """ should allow deleting derived resource """ uploader.upload("tests/logo.png", public_id="api_test3", eager=[{"width": 101,"crop": "scale"}]) resource = api.resource("api_test3") self.assertNotEqual(resource, None) self.assertEqual(len(resource["derived"]), 1) derived_resource_id = resource["derived"][0]["id"] api.delete_derived_resources([derived_resource_id]) resource = api.resource("api_test3") self.assertNotEqual(resource, None) self.assertEqual(len(resource["derived"]), 0)
def test_quality_override(self, mocker): """should pass quality_override """ mocker.return_value = MOCK_RESPONSE test_values = ['auto:advanced', 'auto:best', '80:420', 'none'] for quality in test_values: uploader.upload(TEST_IMAGE, tags=TEST_TAG, quality_override=quality) params = mocker.call_args[0][2] self.assertEqual(params['quality_override'], quality) # verify explicit works too uploader.explicit(TEST_IMAGE, quality_override='auto:best') params = mocker.call_args[0][2] self.assertEqual(params['quality_override'], 'auto:best')
def test_tags(self): """should successfully upload file """ result = uploader.upload("tests/logo.png") result2 = uploader.upload("tests/logo.png") uploader.add_tag("tag1", [result["public_id"], result2["public_id"]]) uploader.add_tag("tag2", result["public_id"]) self.assertEqual(api.resource(result["public_id"])["tags"], ["tag1", "tag2"]) self.assertEqual(api.resource(result2["public_id"])["tags"], ["tag1"]) uploader.remove_tag("tag1", result["public_id"]) self.assertEqual(api.resource(result["public_id"])["tags"], ["tag2"]) uploader.replace_tag("tag3", result["public_id"]) self.assertEqual(api.resource(result["public_id"])["tags"], ["tag3"])
def test_tags(self): """should successfully upload file """ result = uploader.upload(TEST_IMAGE, tags=[UNIQUE_TAG]) result2 = uploader.upload(TEST_IMAGE, tags=[UNIQUE_TAG]) uploader.add_tag("tag1", [result["public_id"], result2["public_id"]]) uploader.add_tag("tag2", result["public_id"]) self.assertEqual(api.resource(result["public_id"])["tags"], ["tag1", "tag2", UNIQUE_TAG]) self.assertEqual(api.resource(result2["public_id"])["tags"], ["tag1", UNIQUE_TAG]) uploader.remove_tag("tag1", result["public_id"]) self.assertEqual(api.resource(result["public_id"])["tags"], ["tag2", UNIQUE_TAG]) uploader.replace_tag("tag3", result["public_id"]) self.assertEqual(api.resource(result["public_id"])["tags"], ["tag3"]) uploader.replace_tag(UNIQUE_TAG, result["public_id"])
def test_access_control(self, request_mock): request_mock.return_value = MOCK_RESPONSE # Should accept a dictionary of strings acl = OrderedDict((("access_type", "anonymous"), ("start", "2018-02-22 16:20:57 +0200"), ("end", "2018-03-22 00:00 +0200"))) exp_acl = '[{"access_type":"anonymous","start":"2018-02-22 16:20:57 +0200","end":"2018-03-22 00:00 +0200"}]' uploader.upload(TEST_IMAGE, access_control=acl) params = get_params(request_mock.call_args[0]) self.assertIn("access_control", params) self.assertEqual(exp_acl, params["access_control"]) # Should accept a dictionary of datetime objects acl_2 = OrderedDict((("access_type", "anonymous"), ("start", datetime.strptime("2019-02-22 16:20:57Z", "%Y-%m-%d %H:%M:%SZ")), ("end", datetime(2019, 3, 22, 0, 0, tzinfo=UTC())))) exp_acl_2 = '[{"access_type":"anonymous","start":"2019-02-22T16:20:57","end":"2019-03-22T00:00:00+00:00"}]' uploader.upload(TEST_IMAGE, access_control=acl_2) params = get_params(request_mock.call_args[0]) self.assertEqual(exp_acl_2, params["access_control"]) # Should accept a JSON string acl_str = '{"access_type":"anonymous","start":"2019-02-22 16:20:57 +0200","end":"2019-03-22 00:00 +0200"}' exp_acl_str = '[{"access_type":"anonymous","start":"2019-02-22 16:20:57 +0200","end":"2019-03-22 00:00 +0200"}]' uploader.upload(TEST_IMAGE, access_control=acl_str) params = get_params(request_mock.call_args[0]) self.assertEqual(exp_acl_str, params["access_control"]) # Should accept a list of all the above values list_of_acl = [acl, acl_2, acl_str] # Remove starting "[" and ending "]" in all expected strings and combine them into one string expected_list_of_acl = "[" + ",".join([v[1:-1] for v in(exp_acl, exp_acl_2, exp_acl_str)]) + "]" uploader.upload(TEST_IMAGE, access_control=list_of_acl) params = get_params(request_mock.call_args[0]) self.assertEqual(expected_list_of_acl, params["access_control"]) # Should raise ValueError on invalid values invalid_values = [[[]], ["not_a_dict"], [7357]] for invalid_value in invalid_values: with self.assertRaises(ValueError): uploader.upload(TEST_IMAGE, access_control=invalid_value)
def setUp(self): if TestApi.initialized: return TestApi.initialized = True cloudinary.reset_config() if not cloudinary.config().api_secret: return try: api.delete_resources(["api_test", "api_test2", "api_test3"]) except: pass try: api.delete_transformation("api_test_transformation") except: pass uploader.upload("tests/logo.png", public_id="api_test", tags="api_test_tag", eager=[{"width": 100,"crop": "scale"}]) uploader.upload("tests/logo.png", public_id="api_test2", tags="api_test_tag", eager=[{"width": 100,"crop": "scale"}])
def test_upload_url(self): """should successfully upload file by url """ result = uploader.upload("http://cloudinary.com/images/old_logo.png", tags=TEST_TAG) self.assertEqual(result["width"], TEST_IMAGE_WIDTH) self.assertEqual(result["height"], TEST_IMAGE_HEIGHT) expected_signature = utils.api_sign_request(dict(public_id=result["public_id"], version=result["version"]), cloudinary.config().api_secret) self.assertEqual(result["signature"], expected_signature)
def test_upload_unicode_url(self): """should successfully upload file by unicode url """ result = uploader.upload(u"http://cloudinary.com/images/old_logo.png") self.assertEqual(result["width"], 241) self.assertEqual(result["height"], 51) expected_signature = utils.api_sign_request(dict(public_id=result["public_id"], version=result["version"]), cloudinary.config().api_secret) self.assertEqual(result["signature"], expected_signature)
def convert(jsonData): fileURL = jsonData['files'][0]['url'] randID = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for x in range(10)) try: wgetOutput = subprocess.check_output('wget -O temp/'+randID+'.mid '+fileURL, shell=True) midilyOutput = subprocess.check_output('midi2ly -o temp/ temp/'+randID+'.mid', stderr=subprocess.STDOUT, shell=True) app.logger.info("Midi2ly Output: %s" % midilyOutput) if "expect bad output" in midilyOutput: return False lilypondOutput = subprocess.check_output('lilypond -f png -o temp/output temp/'+randID+'-midi.ly', stderr=subprocess.STDOUT, shell=True) app.logger.info("lilypond Output: %s" % lilypondOutput) rmMidiOutput = subprocess.check_output('rm temp/output/'+randID+'-midi.midi', shell=True) lsFilesOutput = subprocess.check_output('ls temp/output/ > list.txt', shell=True) rmLyOutput = subprocess.check_output('rm temp/'+randID+'-midi.ly', shell=True) midiToWav(randID+'.mid') mvMidiOutput = subprocess.check_output('mv temp/'+randID+'.mid static/midi', shell=True) except subprocess.CalledProcessError: return False else: filenames = open('list.txt','r').readlines() imageData = [] for i in filenames: result = uploader.upload('temp/output/'+i.rstrip('\n')) imageData.append(result) rmTempFilesOutput = subprocess.check_output('rm temp/output/'+i.rstrip('\n'), shell=True) jsonData['images'] = imageData jsonData['data'] = midiTo64('static/midi/'+randID+'.mid') jsonData['randID'] = randID jsonData['usergenerated'] = True response = db.songs.insert(jsonData) jsonData['id'] = str(response) return jsonData
def post(self): """ @api {POST} /image/ Insert an image @apiName InsertImage @apiGroup Insert @apiDescription Insert an image. @apiParam {String} id The student ID. @apiParam {String} url The image URL or absolute local file path. @apiParamExample {json} Request-Example: {"id": "001", "name":"jmei"} @apiSuccess {String} success ok @apiUse RequestParsingErrors @apiError 409 Inserting image ID have already exist. @apiVersion 1.0.0 """ try: id, url, data = self.read_request('id', 'url') _config() logging.info(urllib2.unquote(url)) img = uploader.upload(urllib2.unquote(url)) try: self.db.image.insert({'_id': img['public_id'], 'sid': id}) except errors.DuplicateKeyError: self.send_error(409, message="image id have already exist.") self.response['success'] = 'ok' self.write_response() except base.ErrorSentException: pass
def profile(request, username): from django.core.exceptions import ObjectDoesNotExist import cloudinary.uploader as cup from core.models import Profile print request.user print username if request.method == 'POST': try: profile = Profile.objects.get(user=request.user) except(ObjectDoesNotExist): profile = Profile() profile.user = request.user profile_picture = request.FILES['profile_photo'] print profile_picture uploaded_image = cup.upload( profile_picture, crop='limit', width=600, height=550, ) filename=uploaded_image["secure_url"] print filename profile.picture = filename print profile.picture profile.save() if request.method == 'GET': try: profile = Profile.objects.get(user=request.user) except(ObjectDoesNotExist): return render(request, 'users/profile.html', {"user": request.user, "profile": ""}) else: pass return render(request, 'users/profile.html', {"user": request.user, "profile": profile})
def test_upload_custom_filename(self): """should successfully use custom filename regardless actual file path""" custom_filename = UNIQUE_ID + "_" + os.path.basename(TEST_IMAGE) result = uploader.upload(TEST_IMAGE, tags=[UNIQUE_TAG], filename=custom_filename) self.assertEqual(os.path.splitext(custom_filename)[0], result["original_filename"]) with io.BytesIO() as temp_file, open(TEST_IMAGE, 'rb') as input_file: temp_file.write(input_file.read()) temp_file.seek(0) result = uploader.upload(temp_file, tags=[UNIQUE_TAG], filename=custom_filename) self.assertEqual(os.path.splitext(custom_filename)[0], result["original_filename"])
def test_upload(self): """should successfully upload file """ result = uploader.upload("tests/logo.png") self.assertEqual(result["width"], 241) self.assertEqual(result["height"], 51) expected_signature = utils.api_sign_request(dict(public_id=result["public_id"], version=result["version"]), cloudinary.config().api_secret) self.assertEqual(result["signature"], expected_signature)
def test_responsive_breakpoints(self): result = uploader.upload( TEST_IMAGE, tags=[UNIQUE_TAG], responsive_breakpoints=dict(create_derived=False, transformation=dict(angle=90))) self.assertIsNotNone(result["responsive_breakpoints"]) self.assertEqual(result["responsive_breakpoints"][0]["transformation"], "a_90") result = uploader.explicit( result["public_id"], type="upload", tags=[UNIQUE_TAG], responsive_breakpoints=[dict(create_derived=False, transformation=dict(angle=90)), dict(create_derived=False, transformation=dict(angle=45))]) self.assertIsNotNone(result["responsive_breakpoints"]) self.assertEqual(result["responsive_breakpoints"][0]["transformation"], "a_90") self.assertEqual(result["responsive_breakpoints"][1]["transformation"], "a_45")
def test_upload_data_uri(self): """should successfully upload file by unicode url """ result = uploader.upload(u"data:image/png;base64,iVBORw0KGgoAA\nAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD///+l2Z/dAAAAM0l\nEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4Ug9C9zwz3gVLMDA/A6\nP9/AFGGFyjOXZtQAAAAAElFTkSuQmCC") self.assertEqual(result["width"], 16) self.assertEqual(result["height"], 16) expected_signature = utils.api_sign_request(dict(public_id=result["public_id"], version=result["version"]), cloudinary.config().api_secret) self.assertEqual(result["signature"], expected_signature)
def upload_image(name, file): try: pubname = str(name) + '_' + str(random.randrange(1, 1000000)) resp = upload(file, public_id=pubname) return (pubname, resp) except Exception: #TODO: Add Logging statment here return False
def test_upload(self): """should successfully upload file """ result = uploader.upload(TEST_IMAGE, tags=[UNIQUE_TAG]) self.assertEqual(result["width"], TEST_IMAGE_WIDTH) self.assertEqual(result["height"], TEST_IMAGE_HEIGHT) expected_signature = utils.api_sign_request(dict(public_id=result["public_id"], version=result["version"]), cloudinary.config().api_secret) self.assertEqual(result["signature"], expected_signature)
def post(request, *args, **kwargs): photo_src = request.POST.get("photo_src") user_id = request.user.id uploader.destroy(request.user, invalidate=True) user = Account.objects.get(id=user_id) user.photo = uploader.upload(photo_src, public_id=user_id, invalidate=True)['url'] user.save() return JsonResponse({"done": "true"})
def put(self, id): parsed_args = self.parser.parse_args() user = session.query(User).filter(User.id == id).first() if user.id != g.user.id: abort(403, message="user {0} is not allowed to modify user {1}".format(id, g.user.id)) if parsed_args['new_username'] is not None: user.username = parsed_args['new_username'] if parsed_args['new_description'] is not None: user.description = parsed_args['new_description'] if 'image' in request.files: image = request.files['image'] if image.filename != '': cloudinary_struct = uploader.upload(image, public_id='{0}_{1}'.format(user.username, image.filename)) user.pic_url = cloudinary_struct['url'] if parsed_args['new_password'] is not None: password_reset = parsed_args['new_password'] if not user.verify_password(password_reset['old_password']) or password_reset['new_password'] != \ password_reset['new_password_confirm']: abort(400, message="wrong old_password or new_password and new_password_confirm mismatch") user.hash_password(password_reset['new_password']) session.add(user) session.commit() return user, 201
def analytics(): form = ClassificationForm() if form.validate_on_submit(): print(form) if form.picture.data: img = form.picture.data upload_result = upload(img) thumbnail_url1, options = cloudinary_url( upload_result['public_id'], format='jpg', crop='fill', width=299, height=299) result = q.enqueue_call(func=prepare_img, args=([thumbnail_url1]), result_ttl=600) return redirect(f'/analytics/{result.get_id()}') # return jsonify(picture_file) return render_template('results.html', results=picture_file, form=form, picture_path=picture_path) return render_template("analytics.html", title='Data Analytics', form=form)
def post(self): parsed_args = self.parser.parse_args() username = parsed_args['username'] password = parsed_args['password'] description = parsed_args['description'] if username is None or password is None: abort(400, message="Missing arguments") if session.query(User).filter(User.username == username).first() is not None: abort(400, message="User {} already exists".format(username)) user = User(username=username) user.hash_password(password) if description is not None: user.description = description if 'image' in request.files: image = request.files['image'] if image.filename != '': cloudinary_struct = uploader.upload(image, public_id='{0}_{1}'.format(username, image.filename)) user.pic_url = cloudinary_struct['url'] session.add(user) session.commit() return user, 201
def file_uploader(file: any) -> dict: temp = tempfile.NamedTemporaryFile() results = {} try: write_data = file.read() temp.write(write_data) temp.seek(0) if int(settings.MAX_UPLOAD_SIZE) > len(write_data): results = upload(temp.name) temp.close() except Exception as ex: logger.info(ex) pass finally: temp.close() return results
def setUpClass(cls): cls.ready = False cloudinary.reset_config() if not cloudinary.config().api_secret: return for public_id in public_ids: res = uploader.upload(TEST_IMAGE, public_id=public_id, tags=[TEST_TAG, UNIQUE_TAG], context="stage=value") upload_results.append(res) attempt = 0 while attempt < MAX_INDEX_RETRIES: time.sleep(1) results = Search().expression( "tags={0}".format(UNIQUE_TAG)).execute() if len(results['resources']) == len(public_ids): cls.ready = True break attempt += 1
def test_face_coordinates(self): """Should allow sending face coordinates""" coordinates = [[120, 30, 109, 150], [121, 31, 110, 151]] result_coordinates = [[120, 30, 109, 51], [121, 31, 110, 51]] result = uploader.upload(TEST_IMAGE, face_coordinates=coordinates, faces=True, tags=[UNIQUE_TAG]) self.assertEqual(result_coordinates, result["faces"]) different_coordinates = [[122, 32, 111, 152]] custom_coordinates = [1, 2, 3, 4] uploader.explicit(result["public_id"], face_coordinates=different_coordinates, custom_coordinates=custom_coordinates, type="upload") info = api.resource(result["public_id"], faces=True, coordinates=True) self.assertEqual(different_coordinates, info["faces"]) self.assertEqual( { "faces": different_coordinates, "custom": [custom_coordinates] }, info["coordinates"])
def uploadFrames(): data = request.json #name = data["name"] #collection.insert_one({"name": name}) productName = request.form.get("productName") framePrice = request.form.get("framePrice") available = request.form.get("available") description = request.form.get("description") slashPrice = request.form.get("slashPrice") slug = slugify(productName) # working on image frame_img = request.files["frame_img"] if productName and framePrice and description and slashPrice and frame_img: uploadToCloud = uploadit.upload(frame_img, ) getImageUrl = uploadToCloud["url"] priceToFloat = float(framePrice) slashToFloat = float(slashPrice) availableToBol = bool(available) collection.insert_one({ "productname": productName, "frameprice": priceToFloat, "available": availableToBol, "imgUrl": getImageUrl, "slashprice": slashToFloat, "slug": slug, "description": description }) return "product uploaded...", 200 else: return "enter important values", 400
def imgedit(experience_id): upload_result = None experience_id = experience_id experience = mongo.db.experiences.find_one( {"_id": ObjectId(experience_id)}) if request.method == "POST": # Gets the image for upload file_to_upload = request.files.get("image") # If there's a new image if file_to_upload: # Delete the previous one destroy(experience['public_id'], invalidate=True) # And continue with the new one upload_result = upload(file_to_upload) imagelink = upload_result['secure_url'] public_id = upload_result['public_id'] flash("Image updated succesfully") return render_template('editxp.html', experience=experience, imagelink=imagelink, experience_id=experience_id, public_id=public_id) # If user didn't change the image else: imagelink = experience['imagelink'] public_id = experience['public_id'] return render_template('editxp.html', experience=experience, imagelink=imagelink, experience_id=experience_id, public_id=public_id) return render_template("imgedit.html", experience_id=experience_id, experience=experience)
def upload_file(): upload_result = None thumbnail_url1 = None thumbnail_url2 = None thumbnail_pixelate = None if request.method == 'POST': file_to_upload = request.files['file'] if file_to_upload: upload_result = upload(file_to_upload) thumbnail_url1, options = cloudinary_url( upload_result['public_id'], format="jpg", crop="fill", width=100, height=100) thumbnail_url2, options = cloudinary_url( upload_result['public_id'], format="jpg", crop="fill", width=200, height=100, radius=20, effect="sepia") thumbnail_pixelate, options = cloudinary_url( upload_result['public_id'], format="jpg", crop="fill", width=200, height=300, radius=20, effect="pixelate_faces:9", gravity="face") return render_template('upload_form.html', upload_result=upload_result, thumbnail_url1=thumbnail_url1, thumbnail_url2=thumbnail_url2, thumbnail_pixelate=thumbnail_pixelate)
def upload(): if request.method == 'GET': return render_template("admin_upload.html") else: file = request.files.getlist('image')[0] # upload image cloudinary img_cloud = uploader.upload(file) img_link = img_cloud['url'] name = request.form['name'] code = request.form['code'] price = request.form['price'] detail = request.form['detail'] cate_name = request.form['cate_name'] product = Product(image=img_link, name=name, code=code, cate_name=cate_name, price=price, detail=detail) product.save() return redirect(url_for('index'))
def post(self, path=None): if 'x-access-token' in request.headers: self.token = request.headers['x-access-token'] if self.token is None: return {"error": "login as admin"}, 401 if path is not None: qs = Post.query.filter_by(public_id=str(path)).first() if qs is not None: qs.draft = False qs.publish = datetime.utcnow() db.session.commit() else: return {"error": "article doesnt exist"}, 400 return {"message": "successfully published"} self.parse.add_argument('file', type=FileStorage, location='files') self.parse.add_argument('title') self.parse.add_argument('subtitle') self.parse.add_argument('content') args = self.parse.parse_args() # Image image_file = args['file'] # print(image_file) upload_result = upload(image_file, folder='Blog') # print('This is upload result ' + str(upload_result)) (image_url, options) = cloudinary_url(upload_result['public_id']) # print('Image url = ' + str(image_url)) # Store this info in the database (self, title, subtitle, content, image_url): article = Post(args['title'], args['subtitle'], args['content'], str(image_url), upload_result['public_id']) db.session.add(article) db.session.commit() return {'message': 'Article was successfully posted'}
def post(self, request): """ Handles post request of form data at route campgrounds/add""" form = CampgroundForm(request.POST, request.FILES) if form.is_valid(): campground_form = form.save(commit=False) g = geocoder.google(campground_form.location) if g.json is None: messages.error( request, 'The location address you enter is invalid. Please enter a valid address.' ) return redirect(reverse('campgrounds:add_campground')) campground_form.location = g.json.get('raw').get( 'formatted_address') campground_form.lat = g.json.get('raw').get('geometry').get( 'location').get('lat') campground_form.lng = g.json.get('raw').get('geometry').get( 'location').get('lng') campground_form.user = request.user file_to_upload = request.FILES['image'] if file_to_upload: upload_result = upload(file_to_upload, width=900, height=500, use_filename=True) campground_form.image_url = upload_result.get('secure_url') campground_form.image_id = upload_result.get('public_id') campground_form.save() messages.success( request, '{} was added successfully'.format(campground_form.name)) return redirect('campgrounds:list_campgrounds') return render(request, 'campgrounds/new_campground.html', { 'form': form, 'title': 'Add Campground' })
def edit_student(student_id): student = Student.get_by_id(student_id) if not student: raise RouteError("Student does not exist.", 404) if (current_user.teacher and student.teacher == current_user.teacher) or ( current_user.student and current_user.student == student): data = flask.request.values image = flask.request.files.get("green_form") extra_data = dict() if (current_user.teacher ): # only teacher is allowed to edit num of lessons and theory try: price = int(data.get("price", "")) except ValueError: price = None car = current_user.teacher.cars.filter_by( id=data.get("car_id")).first() if not car: raise RouteError("Car does not exist.") extra_data = dict( theory=data.get("theory", False) == "true", number_of_old_lessons=float( data.get("number_of_old_lessons", 0)), car=car, price=price, ) if image: extra_data["green_form"] = upload(image)["public_id"] student.update(doctor_check=data.get("doctor_check", False) == "true", eyes_check=data.get("eyes_check", False) == "true", id_number=data.get("id_number"), **extra_data) return {"data": student.user.to_dict()} raise RouteError("Not authorized.", 401)
def test_explicit(self): """Should support explicit """ result = uploader.explicit("cloudinary", type="twitter_name", eager=[TEST_TRANS_SCALE2_PNG], tags=[UNIQUE_TAG]) params = dict(TEST_TRANS_SCALE2_PNG, type="twitter_name", version=result["version"]) url = utils.cloudinary_url("cloudinary", **params)[0] actual = result["eager"][0]["url"] self.assertEqual(parse_url(actual).path, parse_url(url).path) # Test explicit with metadata resource = uploader.upload(TEST_IMAGE, tags=[UNIQUE_TAG]) result_metadata = uploader.explicit(resource['public_id'], type="upload", metadata=METADATA_FIELDS, tags=[UNIQUE_TAG]) self.assertIn(METADATA_FIELD_UNIQUE_EXTERNAL_ID, result_metadata['metadata']) self.assertEqual( result_metadata['metadata'].get(METADATA_FIELD_UNIQUE_EXTERNAL_ID), METADATA_FIELD_VALUE)
def set_post_attachment(postid): """ Uploads the image to cloudinary and stores the url in the post object with the given ID. """ print('request.files[\'file\']: ' + str(request.files)) print('request.json ' + str(request.json)) print('request.forms ' + str(request.form)) sys.stdout.flush() post = Post.query.filter_by(id=postid).scalar() if post is None: return respond( plain_response('No post with given ID. Resource not found.'), 404) if 'file' in request.files: file = request.files['file'] extension = get_file_extention(file.filename) if file and extension == ALLOWED_EXTENSION: # Upload the image to cloudinary and store the URL in the post object. url = uploader.upload(file)['url'] post.attachment_uri = url db.session.commit() return respond(url, 200) return respond(plain_response('Invalid filename/extension.'), 409) return respond(plain_response('No file sent.'), 409)
def add_image(): if not session.get('logged_in'): abort(401) _db = get_db() file_to_upload = request.files['file'] if file_to_upload: upload_result = upload(file_to_upload) if "error" in upload_result: return redirect(url_for('temp')) # TODO : create error dialog url, options = cloudinary_url(upload_result['public_id'], format="jpg", crop="fill", width=300, height=300) cur = _db.cursor() cur.execute('insert into images (public_id, url) values (%s,%s)', (upload_result['public_id'], url)) _db.commit() flash('New entry was successfully posted') # Emit value to client print(" posted ") sio.emit('notify', 'updated') return redirect(url_for('show_images'))
def test_responsive_breakpoints(self): result = uploader.upload("tests/logo.png", responsive_breakpoints=dict( create_derived=False, transformation=dict(angle=90))) self.assertIsNotNone(result["responsive_breakpoints"]) self.assertEqual(result["responsive_breakpoints"][0]["transformation"], "a_90") result = uploader.explicit(result["public_id"], type="upload", responsive_breakpoints=[ dict(create_derived=False, transformation=dict(angle=90)), dict(create_derived=False, transformation=dict(angle=45)) ]) self.assertIsNotNone(result["responsive_breakpoints"]) self.assertEqual(result["responsive_breakpoints"][0]["transformation"], "a_90") self.assertEqual(result["responsive_breakpoints"][1]["transformation"], "a_45")
def put(self, request, *args, **kwargs): """ To save a new profile picture. """ serializer = ProfilePictureSerializer(data=request.data) if serializer.is_valid(): image = serializer.validated_data['file'] profile = request.user.profile upload_response = uploader.upload(image, tags=["profile picture"], folder="profilepics") if ("public_id" not in upload_response): #TODO: log error return get_api_server_error() profile.profile_pic = upload_response["secure_url"] profile.save() response = SaveProfilePictureSerializer(profile) return get_api_response(StatusCodes.Success, data=response.data, httpStatusCode=status.HTTP_200_OK) return get_400_error(serializer.errors)
def add_suggestion(): title = request.form['title'] icon = "" already_suggested = mongo.db.suggestions.find_one({'title': title}) is not None already_category = mongo.db.categories.find_one({'title': title}) is not None if not (already_category or already_suggested): if request.form['has_file'] == "true": files = request.files img = files['file'] if os.environ.get('ENV') == 'development': fake_id = str(random.randint(0, 10000)) img.save('/usr/src/web/app/static/icons/' + fake_id) icon = "http://localhost:" + os.environ.get( 'PORT') + "/static/icons/" + fake_id else: upload_result = upload(img) icon = cloudinary.utils.cloudinary_url( upload_result['public_id'])[0] new_suggestion = Suggestion(title=title, icon=icon) mongo.db.suggestions.insert_one(new_suggestion.__dict__) response = flask.make_response(jsonify({'inserted': True})) response.headers['Access-Control-Allow-Origin'] = '*' return response, 201 else: response = flask.make_response( jsonify({ 'inserted': False, 'error_msg': 'There is already a suggestion or category with that name' })) response.headers['Access-Control-Allow-Origin'] = '*' return response, 409
def updateFrame(id): productName = request.form.get("productName") framePrice = request.form.get("framePrice") available = request.form.get("available") description = request.form.get("description") slashPrice = request.form.get("slashPrice") slug = slugify(productName) # working on image frame_img = request.files["frame_img"] if productName and framePrice and available and description and slashPrice and frame_img: uploadToCloud = uploadit.upload(frame_img, ) getImageUrl = uploadToCloud["url"] priceToFloat = float(framePrice) slashToFloat = float(slashPrice) #availableToBol = bool(available) collection.update_one({"_id": ObjectId(id)}, { "$set": { "productname": productName, "frameprice": priceToFloat, "available": available, "imgUrl": getImageUrl, "slashprice": slashToFloat, "description": description, "slug": slug } }) return "product updated..", 200 else: return "enter all required fields..", 400
def post_view(request): user = check_validation(request) if user: #already logged in if request.method == "GET": form = Post_form() return render(request, 'post.html', {'post_form': form}) else: form = Post_form(request.POST, request.FILES) if form.is_valid(): image = form.cleaned_data.get('image') caption = form.cleaned_data.get('caption') result = upload(image) new_post = postmodel(user=user, image=image, image_url=result['secure_url'], caption=caption) new_post.save() return HttpResponseRedirect("/feed/", "Image Saved in database") else: return HttpResponse("Error Saving in database") else: return redirect("/login/")
def view_bill_pie(_id): bills = Bill.all_bills_for_manager(_id) # print(bills.count()) - to check if the pymongo cursor returned does not countain any value if bills.count() == 0: bills = Bill.all_bills_for_employee(_id) accept = reject = pending = 0 for bill in bills: print(bill) if bill['status'] == 'accept': accept = accept + 1 elif bill['status'] == 'reject': reject = reject + 1 else: pending = pending + 1 sum = accept + pending + reject print(sum, accept, reject, pending) if sum is not 0: labels = "Pending", "Accept", "Reject" sizes = [pending / sum, accept / sum, reject / sum] # pd.DataFrame(sizes, columns=labels) colors = ['gold', 'yellowgreen', 'lightskyblue'] fig1, ax1 = plt.subplots() ax1.pie(sizes, labels=labels, colors=colors, autopct='%.0f%%', shadow=True, startangle=90, radius=0.5) ax1.axis('equal') plt.savefig('plot.png') upload_result = upload('plot.png') url = upload_result['url'] thumbnail_url1, options = cloudinary_url(upload_result['public_id'], format="png", crop="fill", width=100, height=100) # plt.show() return url
def test_auto_tagging(self): """ should support requesting auto_tagging """ with self.assertRaisesRegexp(api.Error, 'Must use'): uploader.upload("tests/logo.png", auto_tagging=0.5)
def test_detection(self): """ should support requesting detection """ with self.assertRaisesRegexp(api.Error, 'Illegal value'): uploader.upload("tests/logo.png", detection="illegal")
def test_similarity_search(self): """ should support requesting similarity_search """ with self.assertRaisesRegexp(api.Error, 'Illegal value'): uploader.upload("tests/logo.png", similarity_search="illegal")
def test_raw_conversion(self): """ should support requesting raw_convert """ with self.assertRaisesRegexp(api.Error, 'Illegal value'): uploader.upload("tests/docx.docx", raw_convert="illegal", resource_type="raw")
def test_ocr_info(self): """ should support requesting ocr info """ with self.assertRaisesRegexp(api.Error, 'Illegal value'): uploader.upload("tests/logo.png", ocr="illegal")
def test_manual_moderation(self): """ should support setting manual moderation status """ resource = uploader.upload("tests/logo.png", moderation="manual") self.assertEqual(resource["moderation"][0]["status"], "pending") self.assertEqual(resource["moderation"][0]["kind"], "manual")
def test_context(self): """should allow sending context""" context = {"caption": "some caption", "alt": "alternative"} result = uploader.upload("tests/logo.png", context=context) info = api.resource(result["public_id"], context=True) self.assertEquals({"custom": context}, info["context"])
def test_allowed_formats_with_format(self): """should allow non whitelisted formats if type is specified and convert to that type""" result = uploader.upload("tests/logo.png", allowed_formats=['jpg'], format='jpg') self.assertEquals("jpg", result["format"])