def post(self): image_url = None thumbnail_url1 = None thumbnail_url2 = None file = self.request.get('file') if file: str_file = StringIO.StringIO(file) str_file.name = 'file' upload_result = upload(str_file) image_url = upload_result['url'] 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") template_values = { 'image_url': image_url, 'thumbnail_url1': thumbnail_url1, 'thumbnail_url2': thumbnail_url2 } path = os.path.join(os.path.dirname(__file__), 'index.html') self.response.write(template.render(path, template_values))
def upload_file(): upload_result = None thumbnail_url1 = None thumbnail_url2 = 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") return render_template('upload_form.html', upload_result=upload_result, thumbnail_url1=thumbnail_url1, thumbnail_url2=thumbnail_url2)
def _populate_video_source_tags(self, source, options): """ Helper function for video tag, populates source tags from provided options. source_types and sources are mutually exclusive, only one of them can be used. If both are not provided, source types are used (for backwards compatibility) :param source: The public ID of the video :param options: Additional options :return: Resulting source tags (may be empty) """ source_tags = [] # Consume all relevant options, otherwise they are left and passed as attributes video_sources = options.pop('sources', []) source_types = options.pop('source_types', []) source_transformation = options.pop('source_transformation', {}) if video_sources and isinstance(video_sources, list): # processing new source structure with codecs for source_data in video_sources: transformation = options.copy() transformation.update(source_data.get("transformations", {})) source_type = source_data.get("type", '') src = utils.cloudinary_url(source, format=source_type, **transformation)[0] codecs = source_data.get("codecs", []) source_tags.append( "<source {attributes}>".format(attributes=utils.html_attrs( { 'src': src, 'type': self._video_mime_type(source_type, codecs) }))) return source_tags # processing old source_types structure with out codecs if not source_types: source_types = self.default_source_types() if not isinstance(source_types, (list, tuple)): return source_tags for source_type in source_types: transformation = options.copy() transformation.update(source_transformation.get(source_type, {})) src = utils.cloudinary_url(source, format=source_type, **transformation)[0] source_tags.append( "<source {attributes}>".format(attributes=utils.html_attrs( { 'src': src, 'type': self._video_mime_type(source_type) }))) return source_tags
def upload_images(): now = int(time.time() * 1000) # ms ids = [] filename = uuid.uuid4().hex for i in request.form: if 'links' in i: item = request.form[i] urllib.request.urlretrieve(item, filename) else: raise Exception(f'Unknown form filetype {i}') upload_result = upload(filename) thumbnail_url, options = cloudinary_url(upload_result['public_id'], format="png", crop="fit", width=200, height=200) os.remove(filename) image = Image(created_date=now, updated_date=now, url=upload_result['url'], thumbnail_url=thumbnail_url) db.session.add(image) db.session.commit() ids.append(image.id) for i in request.files: if 'files' in i: item = request.files[i] item.save(filename) else: raise Exception(f'Unknown form filetype {i}') upload_result = upload(filename) thumbnail_url, options = cloudinary_url(upload_result['public_id'], format="png", crop="fit", width=200, height=200) os.remove(filename) image = Image(created_date=now, updated_date=now, url=upload_result['url'], thumbnail_url=thumbnail_url) db.session.add(image) db.session.commit() ids.append(image.id) notify(f'Added images {ids} to 3800 be') return jsonify({'ids': ids})
def upload_files(): print("--- Upload a local file with custom public ID") response = upload( "pizza.jpg", tags=DEFAULT_TAG, public_id=n, ) dump_response(response) url, options = cloudinary_url(response['public_id'], format=response['format'], width=200, height=150, crop="fit") print("Fit into 200x150 url: " + url) print("n =" + str(n)) print("") print( "--- Upload a local file with eager transformation of scaling to 200x150" ) response = upload( "pizza.jpg", tags=DEFAULT_TAG, public_id=(n + 1), eager=dict(width=200, height=150, crop="scale"), ) dump_response(response) url, options = cloudinary_url( response['public_id'], format=response['format'], width=200, height=150, crop="scale", ) print("scaling to 200x150 url: " + url) print("n =" + str(n + 1)) print("") print("--- Upload by fetching a remote image") response = upload( "http://res.cloudinary.com/demo/image/upload/couple.jpg", tags=DEFAULT_TAG, ) dump_response(response) url, options = cloudinary_url( response['public_id'], format=response['format'], width=200, height=150, crop="thumb", gravity="faces", ) print("Face detection based 200x150 thumbnail url: " + url) print("")
def upload_file(): upload_result = None thumbnail_url1 = None thumbnail_url2 = None if request.method == 'POST': file = request.files['file'] if file: upload_result = upload(file) 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") return render_template('upload_form.html', upload_result = upload_result, thumbnail_url1 = thumbnail_url1, thumbnail_url2 = thumbnail_url2)
def create_new_image(cls, file_from_request): instance = cls() upload_result = upload(file_from_request) instance.public_id = upload_result.get('public_id') instance.thumbnail_path, options = cloudinary_url(upload_result['public_id'], format="jpg", crop="fill", width=100, height=100) instance.avatar_path, options = cloudinary_url(upload_result['public_id'], format="jpg", crop="fill", width=100, height=100, radius=20, effect="sepia") instance.main_image_path = upload_result.get('url') instance.file_name = upload_result.get('original_filename') instance.save() return instance
def video(self, **options): public_id = options.get('public_id', self.public_id) source = re.sub("\.{0}$".format("|".join(self.default_source_types())), '', public_id) source_types = options.pop('source_types', []) source_transformation = options.pop('source_transformation', {}) fallback = options.pop('fallback_content', '') options['resource_type'] = options.pop('resource_type', self.resource_type or self.default_resource_type or 'video') if len(source_types) == 0: source_types = self.default_source_types() video_options = options.copy() if 'poster' in video_options: poster_options = video_options['poster'] if isinstance(poster_options, dict): if 'public_id' in poster_options: video_options['poster'] = utils.cloudinary_url(poster_options['public_id'], **poster_options)[0] else: video_options['poster'] = self.video_thumbnail(public_id=source, **poster_options) else: video_options['poster'] = self.video_thumbnail(public_id=source, **options) if not video_options['poster']: del video_options['poster'] html = '<video '; nested_source_types = isinstance(source_types, list) and len(source_types) > 1 if not nested_source_types: source = source + '.' + utils.build_array(source_types)[0]; video_url = utils.cloudinary_url(source, **video_options) video_options = video_url[1] if not nested_source_types: video_options['src'] = video_url[0] if 'html_width' in video_options: video_options['width'] = video_options.pop('html_width') if 'html_height' in video_options: video_options['height'] = video_options.pop('html_height') html = html + utils.html_attrs(video_options) + '>' if nested_source_types: for source_type in source_types: transformation = options.copy() transformation.update(source_transformation.get(source_type, {})) src = utils.cloudinary_url(source, format = source_type, **transformation)[0] video_type = "ogg" if source_type == 'ogv' else source_type mime_type = "video/" + video_type html = html + '<source ' + utils.html_attrs({'src': src, 'type': mime_type}) + '>' html = html + fallback html = html + '</video>' return html
def video(self, **options): public_id = options.get('public_id', self.public_id) source = re.sub("\.({0})$".format("|".join(self.default_source_types())), '', public_id) source_types = options.pop('source_types', []) source_transformation = options.pop('source_transformation', {}) fallback = options.pop('fallback_content', '') options['resource_type'] = options.pop('resource_type', self.resource_type or self.default_resource_type or 'video') if len(source_types) == 0: source_types = self.default_source_types() video_options = options.copy() if 'poster' in video_options: poster_options = video_options['poster'] if isinstance(poster_options, dict): if 'public_id' in poster_options: video_options['poster'] = utils.cloudinary_url(poster_options['public_id'], **poster_options)[0] else: video_options['poster'] = self.video_thumbnail(public_id=source, **poster_options) else: video_options['poster'] = self.video_thumbnail(public_id=source, **options) if not video_options['poster']: del video_options['poster'] html = '<video '; nested_source_types = isinstance(source_types, list) and len(source_types) > 1 if not nested_source_types: source = source + '.' + utils.build_array(source_types)[0]; video_url = utils.cloudinary_url(source, **video_options) video_options = video_url[1] if not nested_source_types: video_options['src'] = video_url[0] if 'html_width' in video_options: video_options['width'] = video_options.pop('html_width') if 'html_height' in video_options: video_options['height'] = video_options.pop('html_height') html = html + utils.html_attrs(video_options) + '>' if nested_source_types: for source_type in source_types: transformation = options.copy() transformation.update(source_transformation.get(source_type, {})) src = utils.cloudinary_url(source, format = source_type, **transformation)[0] video_type = "ogg" if source_type == 'ogv' else source_type mime_type = "video/" + video_type html = html + '<source ' + utils.html_attrs({'src': src, 'type': mime_type}) + '>' html = html + fallback html = html + '</video>' return html
def __generate_single_srcset_url(self, breakpoint, **options): """ Helper function. Generates a single srcset item url. :param width: Width in pixels of the srcset item :param options: A dict with additional options :return: Resulting URL of the item """ # The following line is used for the next purposes: # 1. Generate raw transformation string # 2. Cleanup transformation parameters from options. # We call it intentionally even when the user provided custom transformation in srcset raw_transformation, options = utils.generate_transformation_string( **options) # Handle custom transformation provided for srcset items if "srcset" in options and "transformation" in options[ "srcset"] and options["srcset"]["transformation"]: options["transformation"] = options["srcset"]["transformation"] raw_transformation, options = utils.generate_transformation_string( **options) options[ "raw_transformation"] = raw_transformation + "/c_scale,w_{}".format( breakpoint) # We might still have width and height params left if they were provided. # We don't want to use them for the second time for key in {"width", "height"}: options.pop(key, None) return utils.cloudinary_url(self.public_id, **options)[0]
def to_dict(self, with_user=True): green_form = "" if self.green_form: try: green_form = cloudinary_url(self.green_form)[0] except Exception: pass if with_user: return self.user.to_dict() # returns user dict with student info return { "student_id": self.id, "my_teacher": self.teacher.to_dict(), "balance": self.balance, "lessons_done": self.lessons_done, "is_approved": self.is_approved, "is_active": self.is_active, "theory": self.theory, "eyes_check": self.eyes_check, "doctor_check": self.doctor_check, "number_of_old_lessons": self.number_of_old_lessons, "green_form": green_form, "price": self.price, "id_number": self.id_number, "car": self.car.to_dict(), }
def to_dict(self): image = "" if self.image: try: image = cloudinary_url( self.image, width=PROFILE_SIZE, height=PROFILE_SIZE, crop="thumb", gravity="face", )[0] except Exception: pass attrs = { "id": self.id, "email": self.email, "created_at": self.created_at, "last_login": self.last_login, "area": self.area, "name": self.name, "image": image, "phone": self.phone, } return dict(**attrs, **self.role_info())
def upload_image(city): """ Takes the value of 'city' passed in the url and uses it to identify the document in the database. flashes a message to the user to confirm the update. If the url contains a value for 'author, (the user routed from their account page) redirect to account template. Else, (the user routed from the thingstodo page) redirect to thingstodo template. """ if current_user.is_admin is False: flash("Not Allowed.", "danger") return redirect(url_for('suggestion_list', city=city)) if g.updateimage.validate_on_submit(): uploaded_image = upload( g.updateimage.image.data, folder="locations", format="jpg", ) image_url, options = cloudinary_url(uploaded_image["public_id"]) CITIES.update_one( {"location": city}, {"$set": {"bg_img": image_url}}, ) flash("Image Updated.", "success") return redirect(url_for("index")) else: flash("Unsuccessful.", "danger") return redirect(url_for("index"))
def test_http_client_get_json_invalid_url(self): non_existing_url = cloudinary_url(HTTP_CLIENT_TEST_ID + "_non_existing")[0] with six.assertRaisesRegex(self, GeneralError, "Server returned unexpected status code*"): self.http_client.get_json(non_existing_url)
def post(self, path=None): 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 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)
def dashboard(): # QUERIES topics = db.session.query(Topic).order_by(Topic.topic_name).all() form = UploadForm() if form.validate_on_submit(): # check if the post request has the file part if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] # if user does not select file, browser also # submit an empty part without filename if file.filename == '': flash('No selected file') return redirect(request.url) if file and allowed_file(file.filename): # filename = secure_filename(file.filename) # file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) response = upload(file, tags=DEFAULT_TAG) dump_response(response) url = cloudinary_url(response['public_id'], format=response['format'], width=200, height=150, crop="fill") # pipeshelf = Cloud.uploader.upload(filename) return redirect(url_for('pyp.dashboard')) return redirect(url_for('pyp.dashboard')) return render_template('pyp/new.html', form=form, topics=topics)
def icon_32(self): url, options = cloudinary_url(self.icon.name, width=32, height=32, crop="fill") return format_html('<img style="height:32px; width:32px" src="{}"/>', url)
def analytics_response(jobID): 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()}') job = Job.fetch(jobID, connection=conn) while not job.is_finished and not job.is_failed: job = Job.fetch(jobID, connection=conn) return 'Currently processing image. Please wait!', 202 if job.is_failed: return str( 'Sorry. We experienced an error when processing your image.') print(job.result[0]['predictions']) return render_template('results.html', form=form, results=job.result[0], picture_path=job.result[1])
def test_http_client_get_json(self): json_url = cloudinary_url(HTTP_CLIENT_TEST_ID, width="auto:breakpoints:json")[0] json_resp = self.http_client.get_json(json_url) self.assertIn("breakpoints", json_resp) self.assertIsInstance(json_resp["breakpoints"], list)
def post(self): """ Method to upload image to a remote server(Cloudinary) and save image url to the database """ user_id = get_jwt_identity() data = request.files response = upload(data["image_url"], public_id=user_id) user = Image.query.filter_by(user=user_id).first() if user: response = { 'status': 'failed', 'message': 'You have a saved passport. Delete to update' } return make_response(jsonify(response)), 400 else: url, options = cloudinary_url(response['public_id'], format=response['format'], width=250, height=250, gravity="faces", crop="fill") new_image = Image(image_url=url, user=user_id) new_image.save() response = { "status": "success", "message": "Passport image has been successfully uploaded" } return make_response(jsonify(response)), 201
def put(self, path=None): if path is None: return abort(400, error="no response from the server") 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 self.parse.add_argument('title') self.parse.add_argument('subtitle') self.parse.add_argument('content') self.parse.add_argument('file', type=FileStorage, location='files') args = self.parse.parse_args() article = Post.query.filter_by(public_id=str(path)).first() # Image image_file = args['file'] if image_file is not None: upload_result = upload(image_file, folder='Blog') (image_url, options) = cloudinary_url(upload_result['public_id']) article.image_url = image_url article.image_id = upload_result['public_id'] article.title = args['title'] article.subtitle = args['subtitle'] article.content = args['content'] db.session.commit() return {"message": "Update was successful"}
def uploadImage(): image = request.files['image'] print("hello image here") if image: upload_result = uploader.upload(image) # image = Cloud.CloudinaryImage(request.form.get('image')) thumbnail_url1, options = cloudinary_url( upload_result['public_id'], crop="fill", ) print(thumbnail_url1) c = Chats() c.message = thumbnail_url1 c.username = request.form.get('imageusername') c.wid = request.form.get('imagewid') c.channel_id = request.form.get('imagecid') c.image = 1 room = Workspace.query.filter_by( id=request.form.get('imagewid')).first() session['name'] = room.name if c.message and c.username and c.wid and c.channel_id: db.session.add(c) db.session.commit() if Chats.query.filter_by(message=thumbnail_url1).count() == 1: image = Chats.query.filter_by(message=thumbnail_url1).first() session['imageid'] = image.id return redirect(url_for('views.chat'))
def test_explicit(self): """should support explicit """ result = uploader.explicit("cloudinary", type="twitter_name", eager=[dict(crop="scale", width="2.0")]) url = utils.cloudinary_url( "cloudinary", type="twitter_name", crop="scale", width="2.0", format="png", version=result["version"] )[0] self.assertEqual(result["eager"][0]["url"], url)
def luxury(): try: img = os.path.join("profile", "profile.png") except IOError: img = None random_number = random.randint(1, 3) selected_image = str("luxury"+str(random_number)) try: luxury_image = os.path.join("profile", selected_image+".jpg") except IOError: luxury_image = None print("Luxury image couldn't be retrieved.") position_options = ["north", "south", "east", "west"] response = upload( "profile/profile.png", background_removal="cloudinary_ai", tags=DEFAULT_TAG, public_id=random.randint(1, 50000) * random.randint(1, 50000), transformation=[ {'height': 375, 'crop': "scale"}, {'underlay': selected_image, 'gravity': position_options[random.randint(0, 3)], 'width': 800} ] ) converted, options = cloudinary_url( response['public_id'], format=response['format'], crop="fit" ) return render_template('luxury.html', image=img, luxury_image=luxury_image, converted=converted)
def home(): if request.method == 'GET': return render_template('home.html', data={}) else: # get the images from the form files = request.files.getlist("image[]") image_urls = [] if len(files) != 2: flash("Please upload 2 files") return redirect(url_for('home')) for file in files: if file.filename == "": flash("Please select file") return redirect(url_for('home')) else: #upload each of the image to cloudinary try: upload_result = upload(file) # fetch the urls of the image uploaded to cloudinary image_url, options = cloudinary_url(upload_result['public_id'], format="jpg") image_urls.append(image_url) except Exception as E: flash(str(E)) return redirect(url_for('home')) # call the grcp here # pass the images to grpc client so that it can make rpc to server response_data = remote_procedure_call(image_urls) return render_template('home.html', data=response_data)
def allrandom(): try: img = os.path.join("profile", "profile.png") except IOError: img = None random_number = random.randint(1, 4) selected_image = str("random"+str(random_number)) try: random_image = os.path.join("profile", selected_image + ".jpg") except IOError: print("Random image couldn't be retrieved.") response = upload( "profile/profile.png", background_removal="cloudinary_ai", tags=DEFAULT_TAG, public_id=random.randint(1, 50000) * random.randint(1, 50000), transformation=[ {'height': 375, 'crop': "scale"}, {'underlay': selected_image, 'gravity': "south", 'width': 800} ] ) converted, options = cloudinary_url( response['public_id'], format=response['format'], crop="fit" ) return render_template('random.html', image=img, random_image=random_image, converted=converted)
def upload_and_no_transform(): ''' Uploads file to cloudinary and returns image URL ''' response = upload_files() image_url = cloudinary_url(response['public_id'], format=response['format']) print(image_url[0]) return image_url[0]
def upload_files(): print("--- Upload a local file") isDifferent = False ## foto que se tomo recientemente response = upload("img/escala.jpg", tags="") dump_response(response) ## se obtiene la imagen url, options = cloudinary_url( response['public_id'], format=response['format'], ) public_id = response['public_id'] ## abrir la imagen url_response = urllib.urlopen(url) img_array = np.array(bytearray(url_response.read()), dtype=np.uint8) duplicate = cv2.imdecode(img_array, -1) ## url de la imagen original originalUrl = "https://res.cloudinary.com/choskas/image/upload/v1607385168/cg9lnefzs5wbdslubtzz.jpg" url_response2 = urllib.urlopen(originalUrl) img_array2 = np.array(bytearray(url_response2.read()), dtype=np.uint8) original = cv2.imdecode(img_array2, -1) print(duplicate, original) # duplicate = cv2.imread(img) image1 = original.shape image2 = duplicate.shape print(image1, image2) if original.shape == duplicate.shape: difference = cv2.subtract(original, duplicate) b, g, r = cv2.split(difference) print(b, g, r) if cv2.countNonZero(b) == 0 and cv2.countNonZero(g) == 0 and cv2.countNonZero(r) == 0: print("Las imagenes son iguales") delete_resources(public_id) url = "" else: ## correo en html html = f"""\ <html> <head></head> <body> <p>Hola!<br> Se ha detectado movimiento inusual<br> <img width=300 height=200 src={url}> </img> </p> </body> </html> """ ## funciones para mandar emails part2 = MIMEText(html, 'html') msg.attach(part2) s = smtplib.SMTP('smtp.gmail.com', 587) s.starttls() s.login('*****@*****.**', EMAIL_PASSWORD) s.sendmail(me, you, msg.as_string()) s.quit() print("las imagenes son diferentes") print("mostando la imagen diferente ->") isDifferent = True return jsonify({"isComplete": True, "url": url, "isDifferent" : isDifferent})
def test_explicit(self): """should support explicit """ result = uploader.explicit("cloudinary", type="twitter_name", eager=[dict(crop="scale", width="2.0")], tags=[UNIQUE_TAG]) url = utils.cloudinary_url("cloudinary", type="twitter_name", crop="scale", width="2.0", format="png", version=result["version"])[0] actual = result["eager"][0]["url"] self.assertEqual(parse_url(actual).path, parse_url(url).path)
def get_url(public_id, sizes): url, _ = cloudinary_url(public_id, format="png", width=sizes.get('width'), height=sizes.get('height'), crop='fill', secure=True) return url
def __build_url(self, **options): combined_options = dict(format=self.format, version=self.version, type=self.type, resource_type=self.resource_type or "image") combined_options.update(options) public_id = combined_options.get('public_id') or self.public_id return utils.cloudinary_url(public_id, **combined_options)
def save_upload(self): if secure_filename(self.uploaded_file.filename) == '': return None file_id = self.generate_file_id() upload_result = upload(self.uploaded_file, public_id=file_id) return cloudinary_url(upload_result['public_id'])[0]
def test_explicit(self): """should support explicit """ result = uploader.explicit("cloudinary", type="twitter_name", eager=[dict(crop="scale", width="2.0")]) url = utils.cloudinary_url("cloudinary", type="twitter_name", crop="scale", width="2.0", format="png", version=result["version"])[0] if result["eager"][0]["url"].startswith("/res/"): actual = result["eager"][0]["url"][4:] else: actual = result["eager"][0]["url"] self.assertEqual(actual, parse_url(url).path)
def post(self): image_url = None thumbnail_url1 = None thumbnail_url2 = None file = self.request.get('file') if file: str_file = StringIO.StringIO(file) str_file.name = 'file' upload_result = upload(str_file) image_url = upload_result['url'] 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") template_values = { 'image_url': image_url, 'thumbnail_url1': thumbnail_url1, 'thumbnail_url2': thumbnail_url2 } path = os.path.join(os.path.dirname(__file__), 'index.html') self.response.write(template.render(path, template_values))
def upload_file(file): name, ext = os.path.splitext(file.filename) file.filename = str(counter('post-img')) save_path = 'static/tmp/' file.save(save_path) # appends upload.filename automatically response = upload(save_path + file.filename, public_id = file.filename) dump_response(response) url, options = cloudinary_url(response['public_id'], format = response['format']) print url return url
def upload_files(filename, width, height, tag, pid): if logMSG==1: logger.info("--- Upload a local file with custom public ID") response = upload(filename, tags = tag, public_id = pid, ) dump_response(response) url, options = cloudinary_url(response['public_id'], format = response['format'], width = width, height = height, crop = "fit" ) if logMSG==1: logger.info("Image uploaded to url: " + url)
def url_with_options_chain(self, *options): # Allow transformations to be chained together by passing in array of # transformations # XXX Note that some fancy transformations will only work in the first # XXX transformation, we'll build this functionality out further in the # XXX future if we need it # Generate a base url based on the first transformation url = utils.cloudinary_url(self.name, **options[0][0])[0] # For the rest of transformations in the chain, insert into the image # url appropriately for transformation in options[0][1:]: split_pos = re.search('upload/.+?/',url).end() url = url[:split_pos] + \ utils.generate_transformation_string(**transformation)[0] + '/' + \ url[split_pos:] return url
def build_url(self, **options): options.update(format = self.format, version = self.version) return utils.cloudinary_url(self.public_id, **options)[0]
def __build_url(self, **options): combined_options = dict(format = self.format, version = self.version, type = self.type, resource_type = self.resource_type or self.default_resource_type) combined_options.update(options) public_id = combined_options.get('public_id') or self.public_id return utils.cloudinary_url(public_id, **combined_options)
def test_http_client_get_json_non_json(self): non_json_url = cloudinary_url(HTTP_CLIENT_TEST_ID)[0] with six.assertRaisesRegex(self, GeneralError, "Error parsing server response*"): self.http_client.get_json(non_json_url)
def __build_url(self, **options): combined_options = dict(format = self.format, version = self.version, type = self.type) combined_options.update(options) return utils.cloudinary_url(self.public_id, **combined_options)
def register(): try: if request.method == "POST": entered_full_name = request.form['full_name'] entered_license_number = request.form['license_number'] entered_address = request.form['address'] entered_mobile_number = request.form['mobile_number'] entered_username = request.form['username'] entered_password = request.form['password'] entered_taxi_number = request.form['taxi_number'] file = request.files['file'] c, conn = connection() c.execute("""Select * From Driver where mobile_number = %s""",[entered_mobile_number]) x= c.fetchone() c.close() conn.commit() gc.collect() if x: flash("This Mobile Number is already taken") return render_template("register.html") else: pass c, conn = connection() c.execute("""Select * From Driver where username = %s""",[entered_username]) x=c.fetchone() conn.commit() c.close() gc.collect() if x: flash("This Username is already taken") return render_template("register.html") else: pass c, conn = connection() c.execute("""Select * From Driver where taxi_number = %s""",[entered_taxi_number]) x=c.fetchone() conn.commit() c.close() gc.collect() if x: flash("This Taxi Number is already taken") return render_template("register.html") else: pass if file: upload_result = upload(file, public_id = entered_username) photo_url1 = str(cloudinary_url(entered_username+ ".jpg")) photo_url = photo_url1[2:-6] c, conn = connection() c.execute("""INSERT INTO Driver (full_name,license_number,address,mobile_number,username,password,taxi_number,profile_photo) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)""",(entered_full_name, entered_license_number,entered_address,entered_mobile_number,entered_username,entered_password,entered_taxi_number,photo_url)) conn.commit() c.close() gc.collect() return redirect(url_for(".dashboard")) else: return render_template("register.html") else: return render_template("register.html") except Exception as e: return e
def get_absolute_url(self): return cloudinary_url(self.picture).build_url()
def upload_files(): print("--- Upload a local file") response = upload("pizza.jpg", tags = DEFAULT_TAG) dump_response(response) url, options = cloudinary_url(response['public_id'], format = response['format'], width = 200, height = 150, crop = "fill" ) print("Fill 200x150 url: " + url) print("") print("--- Upload a local file with custom public ID") response = upload("pizza.jpg", tags = DEFAULT_TAG, public_id = "custom_name", ) dump_response(response) url, options = cloudinary_url(response['public_id'], format = response['format'], width = 200, height = 150, crop = "fit" ) print("Fit into 200x150 url: " + url) print("") print("--- Upload a local file with eager transformation of scaling to 200x150") response = upload("lake.jpg", tags = DEFAULT_TAG, public_id = "eager_custom_name", eager = dict( width = 200, height = 150, crop = "scale" ), ) dump_response(response) url, options = cloudinary_url(response['public_id'], format = response['format'], width = 200, height = 150, crop = "scale", ) print("scaling to 200x150 url: " + url) print("") print("--- Upload by fetching a remote image") response = upload("http://res.cloudinary.com/demo/image/upload/couple.jpg", tags = DEFAULT_TAG, ) dump_response(response) url, options = cloudinary_url(response['public_id'], format = response['format'], width = 200, height = 150, crop = "thumb", gravity = "faces", ) print("Face detection based 200x150 thumbnail url: " + url) print("") print("--- Fetch an uploaded remote image, fitting it into 500x500 and reducing saturation") response = upload("http://res.cloudinary.com/demo/image/upload/couple.jpg", tags = DEFAULT_TAG, width = 500, height = 500, crop = "fit", effect = "saturation:-70", ) dump_response(response) url, options = cloudinary_url(response['public_id'], format = response['format'], width = 200, height = 150, crop = "fill", gravity = "faces", radius = 10, effect = "sepia", ) print("Fill 200x150, round corners, apply the sepia effect, url: " + url) print("")
def cloudinary_url(source, options_dict={}, **options): options = dict(options_dict, **options) return utils.cloudinary_url(source, **options)[0]
def image(self, **options): options.update(format = self.format, version = self.version) src, attrs = utils.cloudinary_url(self.public_id, **options) return u"<img src='{0}' {1}/>".format(src, ' '.join(sorted([u"{0}='{1}'".format(key, value) for key, value in attrs.items() if value])))
def url_with_options(self, **options): return utils.cloudinary_url(self.name, **options)[0]
def upload_image(): result = None if 'file' in request.files: upload_result = upload(request.files['file']) result = cloudinary_url(upload_result['public_id'])[0] return jsonify(filename=result)