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 profile_image_upload_to_S3(image_name, destination_dir): """ Upload the image to Amazon S3. """ # Full path where the image is stored temporary temp_image_path = Path( f"{current_app.root_path}/base/static/{temp_image_dir}") jpeg_extensions = [".jpg", ".jpeg"] _, file_ext = os.path.splitext(image_name) try: s3.upload_fileobj( open(f"{temp_image_path}/{image_name}", "rb"), aws_bucket_name, f"{destination_dir}{image_name}", ExtraArgs={ "ACL": "public-read", "ContentType": "image/jpeg" if file_ext in jpeg_extensions else "image/png", }, ) os.remove(f"{temp_image_path}/{image_name}" ) # Clean up by deleting the image in the temporary folder redis_client.delete( image_name) # Clean up by deleting the image in redis return "file uploaded" except Exception as err: print(err)
def update_image(): if get_jwt_header()['type'] == "Chef": chef = Chef.get_or_none(Chef.email == get_jwt_identity()) if request.content_length == 0: return jsonify(message="No images passed", status="failed"), 400 elif request.files['chef_image']: file = request.files.get('chef_image') s3.upload_fileobj( file, "foodapp-new", f"chefs/{chef.id}/{file.filename}", ExtraArgs={ "ACL": "public-read", "ContentType": file.content_type } ) update = Chef.update({Chef.image_path:f"https://foodapp-new.s3-ap-southeast-1.amazonaws.com/chefs/{chef.id}/{file.filename}"}).where(Chef.username == chef.username).execute() updated_chef = Chef.get(Chef.id == chef.id) return jsonify({ "message": "Successfully updated chefs's profile image", "user_id": updated_chef.id, "image": updated_chef.image_path, }), 200 else: return jsonify(message="You are not logged in as Chef"), 400
def updatepic(): profileImage = request.files.get('profileImage') current_user_id = get_jwt_identity() current_user = User.get_by_id(current_user_id) randomString = uuid.uuid4().hex randomString = randomString[0:8] profileImage.filename = randomString + '.png' try: s3.upload_fileobj( profileImage, os.environ.get('S3_BUCKET'), profileImage.filename, ExtraArgs={ "ACL": 'public-read', "ContentType": profileImage.content_type } ) User.update(profilepic=profileImage.filename).where( User.id == current_user_id).execute() except: flash('Upload unsuccessful') result = { "jwt": create_access_token(identity=current_user_id), "profileImage": current_user.profile_image_path, "message": "Successfully edited details." } return jsonify(result)
def property_image_upload_to_S3(image_name, redis_img_dict_key): """ Upload the image to Amazon S3. """ # Full path where the image is stored temporary temp_image_path = Path( f"{current_app.root_path}/base/static/{temp_image_dir}") jpeg_extensions = [".jpg", ".jpeg"] _, file_ext = os.path.splitext(image_name) try: s3.upload_fileobj( open(f"{temp_image_path}/{image_name}", "rb"), aws_bucket_name, # redis_images_key is used as a name for the folder where images will be saved f"{property_listing_images_dir}{redis_img_dict_key}/{image_name}", ExtraArgs={ "ACL": "public-read", "ContentType": "image/jpeg" if file_ext in jpeg_extensions else "image/png", }, ) os.remove(f"{temp_image_path}/{image_name}" ) # Clean up by deleting the image in the temporary folder redis_client.hdel( redis_img_dict_key, image_name) # Clean up by deleting the image in redis return "file uploaded" except Exception as err: print(err)
def upload_file_to_s3(acl="public-read"): s3.upload_fileobj(request.files.get('user_file'), S3_BUCKET, request.files.get('user_file').filename, ExtraArgs={ "ACL": acl, "ContentType": request.files.get('user_file').content_type })
def upload_file_to_s3(file, bucket_name, acl="public-read"): splitted_file_name = file.filename.rsplit('.', 1) unique_file_name = splitted_file_name[0] + "_" + str(int( time.time())) + "." + splitted_file_name[1] try: s3.upload_fileobj(file, bucket_name, unique_file_name, ExtraArgs={ "ACL": acl, "ContentType": file.content_type }) except Exception as e: raise e return "{}{}".format(config.S3_LOCATION, unique_file_name)
def upload_file_to_s3(file, bucket_name, acl="public-read"): """ Docs: http://boto3.readthedocs.io/en/latest/guide/s3.html """ from app import app, s3 try: s3.upload_fileobj(file, bucket_name, file.filename, ExtraArgs={ "ACL": acl, "ContentType": file.content_type }) except Exception as e: print("Something went wrong while uploading to S3: ", e) return e return "{}{}".format(app.config["S3_LOCATION"], file.filename)
def upload(): file = request.files.get('user_image') try: s3.upload_fileobj(file, app.config['S3_BUCKET'], file.filename, ExtraArgs={ "ACL": "public-read", "ContentType": file.content_type }) User.update(profile_picture=file.filename).where( User.id == current_user.id).execute() except Exception as e: flash(str(e)) return redirect(url_for('dashboard.index'))
def write_database_as_csv(): #Write local csv file filename = "database_dump.csv" path = os.path.join(Config.APP_ROOT, "app/static", filename) csv_file = open(path, 'w+') data = Sensor_data.query.all() for row in data: row_as_string = str(row) csv_file.write(row_as_string + '\n') csv_file.close() #Opload file to AWS S3 with open(path, "rb") as s3_file: s3_filename = "database_dump.csv" s3.upload_fileobj(s3_file, app.config["S3_BUCKET"], s3_filename, ExtraArgs={'ACL': 'public-read'}) return "File is available under: {}{}".format(app.config["S3_LOCATION"], s3_filename)
def create(): picture = request.files.get('picture') caption = request.form.get('caption') randomString = uuid.uuid4().hex randomString = randomString[0:11] picture.filename = randomString + '.png' try: s3.upload_fileobj(picture, os.environ.get("S3_BUCKET"), picture.filename, ExtraArgs={ "ACL": 'public-read', "ContentType": picture.content_type }) Pictures(picture=picture.filename, user=current_user.id, caption=caption).save() except: flash('Upload unsuccessful') return redirect(url_for('show', username=current_user.username))
def uploaded(): user_file = request.files.get('user_file') # to scramble filename randomString = uuid.uuid4().hex randomString = randomString[0:11] user_file.filename = randomString + '.png' # try: s3.upload_fileobj(user_file, os.environ.get("S3_BUCKET"), user_file.filename, ExtraArgs={ "ACL": 'public-read', "ContentType": user_file.content_type }) User.update(profile_picture=user_file.filename).where( User.id == current_user.id).execute() except: flash('Profile picture upload unsuccessful.') return redirect(url_for('accounts.edit'))
def upload_img(): file = request.files.get('image') if file: try: s3.upload_fileobj(file, os.environ.get('S3_BUCKET'), file.filename, ExtraArgs={ "ACL": 'public-read', "ContentType": file.content_type }) User.update(profile_picture=file.filename).where( User.id == current_user.id).execute() flash("Profile picture successfully updated", 'success') return redirect(url_for('users.edit', id=current_user.id)) except Exception as e: flash(f"Something Happened: {e} ", 'danger') return render_template('users/edit.html', id=current_user.id) else: flash("Please select a picture to upload", 'danger') return redirect(url_for('users.edit', id=current_user.id))
def create(): current_user_id = get_jwt_identity() file = request.files.get('image') if file: try: s3.upload_fileobj( file, Config.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(): return jsonify({ "image_path": i.image_path, "success": True }) except Exception as e: return jsonify({ "error": e, "success": False }) else: return jsonify({ "message": "No image provided", "status": "failed" })
def detect_landmarks_uri(): """Detects landmarks in the file.""" picture = request.files.get('user_image') current_user_id = get_jwt_identity() randomString = uuid.uuid4().hex randomString = randomString[0:8] picture.filename = randomString + '.png' try: s3.upload_fileobj( picture, os.environ.get('S3_BUCKET'), picture.filename, ExtraArgs={ "ACL": 'public-read', "ContentType": picture.content_type } ) except: flash('Upload unsuccessful') cred = service_account.Credentials.from_service_account_info({"type": "service_account","project_id": "landmarkit-1574492827189","private_key_id": "8516f1b9582bb8c3f93bf28e8ecf68db09a7e379","private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDQzLJb+EU62HYR\n8nAvypuitRc8gL7zFMiCwzGLpXVwZ9WcmEfYp7gcItKiYExk6t7CPjezulUx/mSR\nsWXMk4k9L87rgUS/SBsLjCkozugf9+lCCtr1ZMTmCodrtjqm1JED4/OEcBZYHowd\nOiYzCOUT6Mn5w2/Op62PasL+hMlNdPbxPfhPlJLqHerHA2qo6KOKIobeJYByjLKx\n97TNbQAzC0Ag83weK01761ypPRKm4vIuu/9tDt4h8qc7FZ+Di/Z0TF0PKQ6sHGg4\nb7I7B5wyWuzlsTWS7GdMI51VBY2dL8E7LU8RnY9JvOERKgZioewrRG6PV4yCu5QD\nYh3iEf/3AgMBAAECggEAA9+losb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DAoGBAPTrLSWomEonyoMCj/lm\noh16QM8fZqd9f0M47e3bIlxzailwF3ddYZ1xM3M6l5eGqnpfatNa8Sc+u0vXyjTb\n9WvmqZNJylkyC+FJuH5wy+BDnVtXUOR1mAZE5NgYUOSZC28T0n6sd0c6L7rt6iX1\nr2TEikVRckD69R1GmVDMVxCc\n-----END PRIVATE KEY-----\n","client_email": "*****@*****.**","client_id": "104823819347629366265","auth_uri": "https://accounts.google.com/o/oauth2/auth","token_uri": "https://oauth2.googleapis.com/token","auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs","client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/starting-account-2xyb6t56zwpw%40landmarkit-1574492827189.iam.gserviceaccount.com"}) client = vision.ImageAnnotatorClient(credentials=cred) image = vision.types.Image() path = f'https://{os.environ.get("S3_BUCKET")}.s3-eu-west-2.amazonaws.com/' + \ picture.filename image.source.image_uri = path response = client.landmark_detection(image=image) landmarks = response.landmark_annotations # print('Landmarks:') # kg_id = landmarks[0].mid # kg_request = requests.get( # f"https://kgsearch.googleapis.com/v1/entities:search?ids={kg_id}&key={os.environ.get('GOOGLE_KG_API_KEY')}&limit=1&indent=True") # kg = kg_request.json() result = [ { "mid": landmark.mid, "name": landmark.description, "score": landmark.score, "locations": [ { "lat_lng": { "latitude": landmark.locations[0].lat_lng.latitude, "longitude": landmark.locations[0].lat_lng.longitude } } ], # "description": kg["itemListElement"][0]["result"]["detailedDescription"]["articleBody"] } for landmark in landmarks ] name1 = result[0]["name"] wiki = wikipedia.summary(name1) width = random.randint(3, 4) height = random.randint(3, 4) add = Images(image=picture.filename, name=result[0]["name"], description=wiki, latitude=result[0]["locations"][0]["lat_lng"]["latitude"], longitude=result[0]["locations"][0]["lat_lng"]["longitude"], user_id=current_user_id, width=width, height=height) add.save() result2 = [ { "mid": landmark.mid, "name": landmark.description, "score": landmark.score, "id": add.id, "locations": [ { "lat_lng": { "latitude": landmark.locations[0].lat_lng.latitude, "longitude": landmark.locations[0].lat_lng.longitude } } ], # "description": kg["itemListElement"][0]["result"]["detailedDescription"]["articleBody"] } for landmark in landmarks ] return jsonify(result2)