def update_image_library(username): # A if "image_gallery" not in request.files: return "No user_file key in request.files" # B file = request.files["image_gallery"] print(file) # C. if file.filename == "": return "Please select a file" # D. if file and allowed_file(file.filename): file.filename = secure_filename(file.filename) output = upload_file_to_s3(file, app.config["S3_BUCKET"]) # Add image path to database Image.create(user_id=current_user.id, user_image_path=file.filename) flash('Profile photo updated') return redirect(url_for('users.show', username=username)) else: return render_template("home.html")
def upload(id): user = User.get_or_none(User.id == id) # profile_image = current_user.image_path if not current_user.image_path: flash(u"You must set a profile image first", 'danger') return redirect(url_for('users.edit', id=current_user.id)) if "user_image" not in request.files: flash(u"You must upload an image file", 'warning') return redirect(url_for('images.new')) desc = request.form.get("desc") file = request.files["user_image"] if file.filename == "": flash(u"Please select a file", 'warning') return redirect(url_for('images.new')) if file and allowed_file(file.filename): file.filename = secure_filename(file.filename) result = upload_file_to_s3(file) if re.search("http", str(result)): try: img = Image(image_path=file.filename, desc=desc, user_id=id) img.save() flash(u"Your Photo is uploaded!", 'success') return redirect(url_for('images.new')) except: flash(u"An error has occured. Please try again", 'warning') return redirect(url_for('images.new')) else: flash(u"Network error. Please try again", 'warning') return redirect(url_for('images.new')) else: flash(u"Unsupported file type", 'danger') return redirect(url_for('images.new'))
def create(): user = User.get_or_none(User.id == current_user.id) if user: if "image_file" not in request.files: return "No image_file key in request.files" file = request.files["image_file"] if file.filename == "": return "Please select a file" if file: file_path = upload_file_to_s3(file) image = Image(user=user, image_url=file_path) if image.save(): flash("Image uploaded successfully", "success") return redirect( url_for('users.show', username=current_user.username)) else: flash("Failed to upload images, try again", "danger") return redirect(url_for('images.new')) else: return redirect(url_for('images.new')) else: return "No such user found!"
def upload_img(): if "user_file" not in request.files: return flash("No user_file key in request.files") file = request.files["user_file"] caption = request.form.get('caption') if file.filename == "": return flash("Please select a file") if file and allowed_file(file.filename): file.filename = secure_filename(file.filename) output = upload_file_to_s3(file, Config.S3_BUCKET) p = Image(user=current_user.id, upload_image=file.filename, caption=caption) p.save() return redirect(url_for("sessions.profile", id=current_user.id)) else: flash("Please try again 🥺") return render_template("sessions/profile.html")
def upload_image(id): # get a file from request file = request.files["image"] # if no file in request if not file: flash("Please choose a file", 'danger') return render_template('images/new.html') # if there is a file in request & is allowed type elif file and allowed_file(file.filename): file.filename = secure_filename(file.filename) output = upload_file_to_s3(file) if not output: flash(f'Unable to upload {file.filename}, please try again.', 'danger') return render_template('images/new.html') else: user = User.get_by_id(current_user.id) image = Image(filename=output, user=user) image.save() flash(f'Successfully uploaded {file.filename}', 'success') return redirect(url_for('users.show', username=user.username))
def upload(user_id): user = User.get_or_none(User.id == user_id) if user: if current_user.id == int(user_id): # We check the request.files object for a user_file key. (user_file is the name of the file input on our form). If it's not there, we return an error message. if "image" not in request.files: flash("No file provided!") return redirect(url_for('images.new')) # If the key is in the object, we save it in a variable called file. file = request.files["image"] # we sanitize the filename using the secure_filename helper function provided by the werkzeurg.security module. file.filename = secure_filename(file.filename) # get path to image on S3 bucket using function in helper.py image_path = upload_file_to_s3(file, user.username) new_image = Image(user=user, image_url=image_path) if new_image.save(): flash("Successfully uploaded!","success") return redirect(url_for("users.show", username=user.username)) # then redirect to profile page else: flash("Upload failed :( Please try again") return redirect(url_for('images.new')) else: flash("Cannot uplaod images for other users", "danger") return redirect(url_for('users.show', username = user.username)) else: flash("No user found!") return redirect(url_for('home'))
def post(): user_id = get_jwt_identity() user = User.get_or_none(User.id == user_id) if "image" not in request.files: return jsonify({ "message": "No image provided", "status": "failed" }) file = request.files["image"] if file.filename == "": return jsonify({"message":"Please select a file"}) if file and allowed_file(file.filename): file_path = upload_to_s3(file, user_id) new_image = Image(image_url=file_path, user=user_id) if new_image.save(): return jsonify({ "image_path": app.config.get("AWS_S3_DOMAIN") + file_path, "success": "image uploaded" }) else: return jsonify({"Error": "Failed to save"}) else: return jsonify({ "message": "Not supported file format or file doesn't exist" })
def create(): user = User.get_or_none(User.id == current_user.id) if user: # Upload image if "new_image" not in request.files: flash("No file provided!") return redirect(url_for("images.new")) file = request.files["new_image"] if 'image' not in file.mimetype: flash("Please upload an image!") return redirect(url_for("images.new")) else: file_extension = file.mimetype file_extension = file_extension.replace('image/', '.') file.filename = str(datetime.now()) + file_extension file.filename = secure_filename(file.filename) image_path = upload_file_to_s3(file, user.username) image = Image(user_id=user.id, image_path=image_path) if image.save(): flash("Successfully uploaded your new photo!", "success") return redirect(url_for("users.show", username=user.username)) else: flash("Could not upload image. Please try again") return redirect(url_for("images.new")) return redirect(url_for('users.show', username=user.username)) else: return abort(404)
def create(): if "user_file" not in request.files: flash("Please select a file to upload", "warning") return redirect(url_for('images.new')) file = request.files["user_file"] comment = request.form.get('comment') if file.filename == "": flash("Please select a file to upload", "warning") return redirect(url_for('images.new')) if file and allowed_file(file.filename): i = Image(user=current_user.id, img_name=file.filename) i.save() c = Comment(comment=comment, image=i.id, user=current_user.id) c.save() output = upload_file_to_s3(file) flash("Image uploaded successfully", 'info') return redirect(url_for('users.show', username=current_user.username)) else: flash("Sorry, we were unable to upload your photo. Please try again.", "warning") return redirect(url_for('images.new'))
def get(self,id): if not id: # perform 'list' function if no ID given. limit = int(self.request.get('limit','10')) if limit > 50: limit = 50 #enforce max offset = int(self.request.get('offset','0')) images = Image.all().order("-created").fetch(limit,offset) acceptType = self.request.accept.best_match( listRenderers.keys() ) # TODO handle unknown accept type self.response.headers['Content-Type'] = acceptType listRenderers[acceptType](self.response.out, images) return logging.debug("ImagestoreHandler#get for file: %s", id) try: img = Image.get( id ) if not img: raise "Not found" except: self.error(404) self.response.headers['Content-Type'] = 'text/plain' self.response.out.write( "Could not find image: '%s'" % id ) return logging.debug( "Found image: %s, mime type: %s", img.name, img.mimeType ) dl = self.request.get('dl') # optionally download as attachment if dl=='1' or dl=='true': self.response.headers['Content-Disposition'] = 'attachment; filename="%s"' % str(img.name) self.response.headers['Content-Type'] = str(img.mimeType) self.response.out.write( img.data )
def create(): if current_user.is_authenticated: user = User.get_or_none(User.id == current_user.id) if "user_file" not in request.files: flash('No user_file key in request.files', 'alert alert-danger') return redirect(url_for('images.new')) file = request.files["user_file"] """ These attributes are also available file.filename # The actual name of the file file.content_type file.content_length file.mimetype """ if file and allowed_file(file.filename): file.filename = secure_filename(file.filename) output = upload_file_to_s3(file, S3_BUCKET) # User.update(image_path = file.filename).where(User.id==user.id).execute() image = Image(user=user, image_path=file.filename) if image.save(): flash('Upload successful', 'alert alert-success') return redirect( url_for('users.show', id_or_username=current_user.username)) flash('Upload failed', 'alert alert-danger') return redirect(url_for('images.new')) else: flash('Log in required', 'alert alert-danger') return redirect(url_for('home'))
def upload_user(id): if 'user_profile_image' not in request.files: flash('filedid not select yet') return (redirect(url_for('users.edit', id=id))) file = request.files['user_profile_image'] if file.filename == "": flash('Pleas select a file') return redirect(url_for('images.new', id=id)) else: if file and allowed_file(file.filename): file.filename = secure_filename(file.filename) output = upload_file_to_s3(file, app.config["S3_BUCKET"]) profile_image = Image(imageURL=file.filename, user_id=id) if profile_image.save(): flash(f'upload {str(output)} completed!') return redirect(url_for('images.new', id=id)) else: flash('the file is corrupted please try again') return render_template('images/new.html', id=id) else: flash( 'the file is not jpeg, png, gif. please upload with correct format' ) return redirect(url_for('images.new', id=id))
def create_image(username): if "upload_image" not in request.flies: flash("No Image selected", "warning") return redirect( url_for('users.upload_image', username=current_user.name)) else: file = request.files.get('upload_image') bucket_name = os.getenv('S3_BUCKET') s3.upload_fileobj(file, bucket_name, file.filename, ExtraArgs={ "ACL": "public-read", "ContentType": file.content_type }) image = Image( caption=request.form.get('caption'), url= f'https://kevinchan950-nextagram-flask.s3-ap-southeast-1.amazonaws.com/{file.filename}', user=current_user.id) if image.save(): flash("Image upload successfully", "success") return redirect(url_for('users.show', username=current_user.name)) else: flash("Upload failed, please try again") return render_template('users/upload_image.html')
def create(): file = request.files.get('image') caption = request.form.get('caption') if file: try: s3.upload_fileobj(file, os.environ.get('S3_BUCKET'), "user_images/" + file.filename, ExtraArgs={ "ACL": 'public-read', "ContentType": file.content_type }) i = Image(image_name=file.filename, user=current_user.id, caption=caption) if i.save(): flash("Image uploaded successfully", 'success') return redirect( url_for('users.show', username=current_user.username)) except Exception as e: flash(f"Something Happened: {e} ", 'danger') return redirect( url_for('users.show', username=current_user.username)) else: return redirect(url_for('users.show', username=current_user.username))
def upload_img(username): images = list(Image.select().join(User).where( User.username == current_user.username)) user = User.get_or_none(User.username == current_user.username) follow = Following.get_or_none(Following.fan_id == current_user.id and Following.idol_id == user.id) try: file = request.files.get("user_file") s3.upload_fileobj(file, S3_BUCKET, file.filename) flash("successfully updated") p = Image(description=request.form['description'], user_id=current_user.id, img_path=file.filename) p.save() return redirect( url_for("users.show", images=images, user=user, username=username, follow=follow)) except: return 'failed' flash("Something went wrong!!") return render_template("users/show.html", images=images, user=user)
def create(id): id = current_user.id caption = request.form.get('caption') user_id = current_user.id if "user_file" not in request.files: flash("Please select a file to upload", "danger") file = request.files["user_file"] if file.filename == "": flash("Please choose a file that has a name", "danger") if file and allowed_file(file.filename): file.filename = secure_filename( str(id) + "_" + file.filename + str(datetime.datetime.now())) output = upload_file_to_s3(file, app.config["S3_BUCKET"]) image = Image(caption=caption, user_id=user_id, image_path=output) if image.save(): flash("Successfully uploaded image", "success") return redirect(url_for('images.new', id=current_user.id)) else: flash("Failed to upload image", "danger") return redirect(url_for('images.new', id=current_user.id)) else: return redirect(url_for('users.profile'))
def upload_image(): # to upload to Amazon if "image" not in request.files: flash('No user_key in request.files') return redirect(url_for('home')) file = request.files["image"] if file and allowed_file(file.filename): file.filename = secure_filename(file.filename) output = upload_file_to_s3(file, S3_BUCKET) # to save to Image database upload_image = Image(image=file.filename, user_id=current_user.id) if upload_image.save(): flash('Successfully uploaded a photo!') return render_template('images/new.html') else: flash('An error occurred. Try again') return render_template('images/new.html') else: return redirect('/')
def create(): file = request.files.get("images") image_path = upload_file_to_s3(file, current_user.username) user = User.get(User.username == current_user.username) image = Image(user=user, images_pathway=image_path) if image.save(): flash('You have successfully upload a new image!', 'success') print(file.mimetype) # return "hehehe" # sendfile() # image_binary = read_image(file) # response = make_response(image_binary) # response.headers.set('Content-Type', 'image/jpeg') # response.headers.set( # 'Content-Disposition', 'attachment', filename='%s.jpg' % pid) # return response # return send_file(io.BytesIO(file.read()), # attachment_filename=file.filename, # mimetype='image/jpg') # return send_file(file.filename,mimetype=f'{file.mimetype}') # return jsonify(file) # return Response(file,mimetype="text/jpeg") return redirect(url_for('users.edit', id=user.id))
def create(): if "image" not in request.files: flash( "You haven't selected an image. Please choose one and try again.") return redirect(url_for('images.new')) file = request.files["image"] if file and allowed_file(file.filename): file.filename = secure_filename(file.filename) output = upload_file_to_s3(file, Config.S3_BUCKET) upload_image = Image(image=file.filename, user_id=current_user.id) if upload_image.save(): flash("Successfully uploaded your image!") return redirect( url_for("users.show", username=current_user.username)) else: flash('An error occurred. Try again') return render_template('images/new.html') else: for error in upload_image.errors: flash(error) return redirect(url_for("images.new"))
def create(): if 'image_file' not in request.files: flash('No image_file key in request.files') return render_template("home.html") file = request.files['image_file'] if file.filename == '': flash('No selected file') return render_template("home.html") if file and allowed_file(file.filename): file.filename = secure_filename( f"{str(datetime.datetime.now())}{file.filename}") output = upload_file_to_s3(file) if output: image = Image(user=current_user.id, image_path=file.filename, caption=request.form.get("caption")) image.save() flash("Image successfully uploaded", "success") return redirect( url_for('users.show', username=current_user.username)) else: flash(output, "danger") return render_template("home.html") else: flash("File type not accepted,please try again.") return render_template("home.html")
def uploadByFile(file): resp = {'code': 200, 'msg': '操作成功~~', 'data': {}} filename = secure_filename(file.get('filename')) ext = filename.rsplit(".", 1)[1] if ext not in UPLOAD['ext']: resp['code'] = -1 resp['msg'] = "不允许的扩展类型文件" return resp root_path = BASE_DIR + UPLOAD['prefix_path'] file_dir = datetime.datetime.now().strftime("%Y%m%d") save_dir = root_path + file_dir if not os.path.exists(save_dir): os.makedirs(save_dir) os.chmod(save_dir, stat.S_IRWXU | stat.S_IRGRP | stat.S_IRWXO) file_name = str(uuid.uuid4()).replace("-", "") + "." + ext with open(save_dir + '/' + file_name, 'wb') as f: f.write(file["body"]) model_image = Image() model_image.file_key = file_dir + "/" + file_name model_image.created_time = getCurrentDate() session.add(model_image) session.commit() resp['data'] = {'file_key': model_image.file_key} return resp
def insert_event_photos(base_url, db_path, event_ids_dict): current_file = os.path.basename(__file__) current_file_name = os.path.splitext(current_file)[0] for key in event_ids_dict: for event_id in event_ids_dict[key]: url = base_url + "/" + current_file_name + "/" + str(event_id) + "/" try: print(url) response = requests.get(url) except requests.exceptions.RequestException as e: print(e) sys.exit(1) if response.status_code == 200: doc = pq(response.text) connection = sqlite3.connect(db_path) try: event_info = select_events_info(db_path, event_id) # Event Photos for photo in doc("div.photo-item").items(): image_id = photo.find('a').attr('href').split('/')[2] image = Image(event_id, image_id, base_url) # Image URL image_response = requests.get(image.url) if image_response.status_code == 200: image_url = pq(image_response.text).find('#main-photo').find('img').attr('src') extension = image_url.rsplit('.')[-1] image_content = requests.get(image_url, stream=True) # Create target Directory if don't exist file = image_id + '.' + extension storage_path = get_storage_path(event_info, file) with open(storage_path, 'wb+') as out_file: shutil.copyfileobj(image_content.raw, out_file) del image_content insert_query = '''INSERT INTO images (id,event_id,created_at,updated_at,deleted_at) VALUES (?,?,?,?,?)''' connection.execute(insert_query, image.get_tuple()) connection.commit() except Exception as e: connection.rollback() raise e finally: connection.close()
def show(): user_id = request.args.get('userId') if user_id: images = Image.select().where(Image.user_id == user_id) response = [image.image_path for image in images] else: response = [image.image_path for image in Image.select()] return jsonify(response)
def test_defaults(self): image = Image() image.put() self.assertIsNone(image.data) self.assertIsNone(image.filename) self.assertIsNone(image.user) self.assertIsNone(image.content_type) self.assertAlmostEqual(datetime.datetime.now(), image.created, delta=datetime.timedelta(seconds=5))
def index(): if request.args.get('userId'): images = Image.select().where(Image.user_id == int(request.args['userId'])) else: images = Image.select() images = [image.image_url for image in images] return jsonify(images)
def userimg(user_id): user = User.get_by_id(user_id) if current_user.id == user.id: img_upload("userImg/") file = request.files.get('image').filename image = Image(userImg=file, user_id = current_user.id) image.save() flash("Image successfully uploaded" , "success") return redirect(url_for("users.profile", user_id=user_id))
def index(): # breakpoint() id = request.args.get("userId") imgs = [] if id: imgs = Image.select().where(Image.user_id == request.args["userId"]) else: imgs = Image.select() return jsonify([img.image_path for img in imgs])
def detect_license_plate(self, image_original): ''' Detect license plate in image. ''' if image_original.data is None: raise ValueError('Error to open image.') # Convert image to gray. image_original.convert_to_gray() # Reescale image to speed up detection and equalize image. image_resized = image_original.resize( self.resize_width, self.resize_width * image_original.height / image_original.width) # Pre process image for detection. image_for_detection = Image(image=image_resized.data) image_for_detection.smart_equalize() # Find license_plates using cascade classifier. self.license_plates = [] self.license_plates += self.cascade_classifier.detect_using_cascade_classifier( image_for_detection) # Find license_plates using rectangles. image_for_detection.filter_median(size=3) image_for_detection.contrast( ) # Increase contrast to improve rectangle detection. self.license_plates += image_for_detection.compute_rectangles_for_plates( ) # Filter misclassified license plates using SVM. lp_filter = FilterLicensePlate() self.license_plates = lp_filter.filter_using_svm( self.license_plates, image_for_detection, self.svm_detector, self.image_width, self.image_height) # Reescale license plates to original size. total_license_plates = range(len(self.license_plates)) for index in total_license_plates: self.license_plates[index] = reescale_license_plate(self.license_plates[index], \ image_original.width, self.resize_width) # Get best license plate found, computing character positions. best_license_plate = lp_filter.get_best_license_plate( self.license_plates, image_original) if best_license_plate is not None: # Adjust size of characters and predict the position of unrecognized characters. character_validator = CharacterValidator() best_license_plate = character_validator.adjust_characters( best_license_plate, image_original, self.resize_width) best_license_plate = get_license_plate_quadrilateral( best_license_plate) self.license_plates = [best_license_plate] else: self.license_plates = [] return best_license_plate
def _store_image(self, name, file, content_type): """POST handler delegates to this method for actual image storage; as a result, alternate implementation may easily override the storage mechanism without rewriting the same content-type handling. This method returns a tuple of file name and image URL.""" img = Image( name=name, data=file.read(), mimeType=content_type ) img.put() logging.info("Saved image to key %s", img.key() ) return ( str(img.name), urlBase % img.key() )
def get_image(id): response = [] find_user = Image.get_or_none(Image.user_id == id) if find_user: for i in Image.select().where(Image.user_id == id): image = {"id": i.id, "url": i.full_image_path} response.append(image) else: error = {"message": "User does not exist", "status": "failed"} response.append(error) return jsonify(response)
def upload_image(): file = request.files.get('profile_image') source = 'profile_image' if not file: file = request.files.get('user_image') source = 'user_image' if not file: abort(http.HTTPStatus.BAD_REQUEST) if source == 'user_image': user_images = Image.get_user_images(g.current_user.id) if len(user_images) >= 4: abort(http.HTTPStatus.FORBIDDEN) if allowed_file(file.filename): bucket_name = current_app.config.get('IMAGES_BUCKET_NAME') filename = f"{uuid.uuid4()}.{file.filename.rsplit('.', 1)[1].lower()}" file.seek(0, os.SEEK_END) file_length = file.tell() file.seek(0, os.SEEK_SET) try: storage.connection.put_object(bucket_name, filename, file, file_length, file.mimetype) except MinioError: abort(http.HTTPStatus.BAD_REQUEST) current_user = g.current_user if source == 'profile_image': # Delete old from bucket if current_user.profile_image: old_filename = current_user.profile_image.split('/')[-1] storage.connection.remove_object(bucket_name, old_filename) # Update current_user.profile_image = url_for('images.get_image', filename=filename, _external=True, _scheme='https') current_user.update() return jsonify({"ok": True}) if source == 'user_image': new_image = Image.from_dict({ 'user_id': current_user.id, 'image_src': url_for('images.get_image', filename=filename, _external=True, _scheme='https') }) new_image.create() return jsonify(ok=True) return jsonify({"ok": False})
def post(self): """ Post to User """ user_inputs = self.request.POST.get('image') file_obj = functions.gcs_upload(user_inputs) file_info = Image.save(file_obj) file_json = Image.to_dict(file_info) response = self.construct_response_details(200, "Ok!", file_json) self.render(response)
def test_get_tracking_image(self): image = Image( filename=self.DEFAULT_FILENAME, content_type=self.DEFAULT_CONTENT_TYPE) image.put() response = self.app.get( self.uri_for('tracking_image', filename=image.filename)) self.assertOk(response) self.assertEqual(image.content_type, response.content_type) self.assertLength(1, Visit.query()) self.assertLength(1, Visitor.query()) visit = Visit.query().get() visitor = Visitor.query().get() self.assertEqual(image.key, visit.image) self.assertEqual(visitor.key, visit.visitor)
def get(self, filename): image = Image.get_by_filename(filename) if not image: return self.abort(404) # Gather the information we take from the user. identifier = self.request.get('identifier', '') ip_address = self.request.remote_addr referrer = self.request.referrer user_agent = self.request.headers.get('User-Agent', '') visitor_uuid = self.request.cookies.get('VISITOR_UUID', '') # If they're not in our database, create a new entity to track them. visitor = Visitor.get_by_uuid(visitor_uuid) if visitor is None: visitor = Visitor() visitor.put() visit = Visit(identifier=identifier, ip_address=ip_address, user_agent=user_agent, referrer=referrer, image=image.key, visitor=visitor.key) visit.put() # Dispatch a task to send the visit to keen.io for analysis. visit_key = visit.key.urlsafe() logging.info('Dispatching task to process {visit_key}' .format(visit_key=visit_key)) taskqueue.add(url=self.uri_for('analytics'), params={'visit_key': visit_key}) self.response.content_type = str(image.content_type) self.response.set_cookie(key='VISITOR_UUID', value=visitor.uuid) self.response.out.write(image.data)
def load_demo_explorations(cls): """Initializes the demo explorations.""" for index, exploration in enumerate(feconf.DEMO_EXPLORATIONS): assert len(exploration) in [3, 4], ( 'Invalid format for demo exploration: %s' % exploration) yaml_filename = '%s.yaml' % exploration[0] yaml_file = utils.get_file_contents( os.path.join(feconf.SAMPLE_EXPLORATIONS_DIR, yaml_filename)) title = exploration[1] category = exploration[2] image_filename = exploration[3] if len(exploration) == 4 else None image_id = None if image_filename: with open(os.path.join( feconf.SAMPLE_IMAGES_DIR, image_filename)) as f: raw_image = f.read() image_id = Image.create(raw_image) exploration = cls.create_from_yaml( yaml_file=yaml_file, user=None, title=title, category=category, exploration_id=str(index), image_id=image_id) exploration.is_public = True exploration.put()
def post(self): """Saves an image uploaded by a content creator.""" raw = self.request.get('image') if raw: image_id = Image.create(raw) self.response.write(json.dumps({'image_id': image_id})) else: raise self.InvalidInputException('No image supplied')
def get(self): counts = {} counts["content"] = Content.all(keys_only=True).count() counts["image"] = Image.all(keys_only=True).count() counts["image_data"] = ImageData.all(keys_only=True).count() counts["link"] = Link.all(keys_only=True).count() counts["style"] = Style.all(keys_only=True).count() counts["workspace"] = Workspace.all(keys_only=True).count() self.response.out.write(str(counts) + "<p><form method='POST' action='/cleanup'><input type=submit value='Clean up'></form>")
def test_duplicate_visitors_not_made(self): image = Image( filename=self.DEFAULT_FILENAME, content_type=self.DEFAULT_CONTENT_TYPE) image.put() response = self.app.get( self.uri_for('tracking_image', filename=image.filename)) self.assertOk(response) self.assertLength(1, Visit.query()) self.assertLength(1, Visitor.query()) response = self.app.get( self.uri_for('tracking_image', filename=image.filename)) self.assertOk(response) self.assertLength(2, Visit.query()) self.assertLength(1, Visitor.query()) visit1, visit2 = Visit.query() visitor = Visitor.query().get() self.assertEqual(visitor.key, visit1.visitor, visit2.visitor) self.assertEqual(image.key, visit1.image, visit2.image)
def get(self, image_id): """Returns an image. Args: image_id: string representing the image id. """ image = Image.get_by_id(image_id) if image: # TODO(sll): Support other image types. self.response.headers['Content-Type'] = str('image/%s' % image.format) self.response.write(image.raw) else: self.response.write('No image')
def post(self): user = users.get_current_user() if user and user.nickname() == "coolcucumber": # Deletes all Datastore data!!! db.delete(Content.all(keys_only=True).fetch(None)) db.delete(Image.all(keys_only=True).fetch(None)) db.delete(ImageData.all(keys_only=True).fetch(None)) db.delete(Link.all(keys_only=True).fetch(None)) db.delete(Style.all(keys_only=True).fetch(None)) db.delete(Workspace.all(keys_only=True).fetch(None)) self.response.out.write("Cleaned up") else: self.response.out.write("Unauthorized user")
def post(self): error = None user = users.get_current_user() if not user: return self.abort(404) filename = self.request.POST.get('filename', '') image_source = self.request.POST.get('image_source', '') if Image.get_by_filename(filename): error = ('File with filename {filename} already exists.' .format(filename=filename)) logging.error(error) try: response = urlfetch.fetch(image_source) except urlfetch.DownloadError as e: error = ('Failed to download file \'{filename}\'' .format(filename=filename)) logging.exception(e.message) if response.status_code == 404: error = '{filename} not found.'.format(filename=filename) if error is not None: self.session.add_flash(value=error, level='error') return self.render_to_response('images.haml') # Store the image in the datastore and ensure the write is fully applied # before redirecting. image_data = response.content content_type = response.headers.get('Content-Type', '') image = Image(data=image_data, filename=filename, user=user, content_type=content_type) image.put().get() return self.redirect_to('image')
def get(self): #get the original image data url = self.request.get("url").replace(" ", "%20") w = int(self.request.get("w")) h = int(self.request.get("h")) blob_key = "" image_entry = Image.gql("WHERE url = :1",url).get() if(not image_entry): # Create the file file_name = files.blobstore.create(mime_type='image/png') #retrieve img_file = urlfetch.fetch(url=str(url), deadline=15).content # Open the file and write to it with files.open(file_name, 'a') as f: f.write(img_file) # Finalize the file. Do this before attempting to read it. files.finalize(file_name) # Get the file's blob key blob_key = files.blobstore.get_blob_key(file_name) i = Image(url = url, blob_key=str(blob_key)) i.put() else: blob_key = image_entry.blob_key #resize the image img = images.Image(blob_key=blob_key) img.resize(width=w, height=h, crop_to_fit = True) thumbnail = img.execute_transforms(output_encoding = images.PNG) #produce result self.response.headers['Content-Type'] = 'image/png' self.response.out.write(thumbnail)
def delete(self,id): logging.info( "ImagestoreHandler#DELETE file: %s", id ) img = None try: img = Image.get( id ) if not img: raise "Not found" except: self.error(404) self.response.headers['Content-Type'] = 'text/plain' self.response.out.write( "Could not find image: '%s'" % id ) return img.delete()
def get(self): images = Image.get_by_user(users.get_current_user()) return self.render_to_response('images.haml', {'images': images})
def test_get_by_filename(self): image = Image(filename=self.DEFAULT_FILENAME) image.put() self.assertEqual(image.key, Image.get_by_filename(image.filename).key) self.assertIsNone(Image.get_by_filename('not.jpg'))