示例#1
0
 def form_valid(self, form):
     campground = form.save(commit=False)
     g = geocoder.google(campground.location)
     if g.json is None:
         messages.error(
             self.request,
             'The location address you enter is invalid. Please enter a valid address.'
         )
         return redirect(reverse('campgrounds:add_campground'))
     campground.location = g.json.get('raw').get('formatted_address')
     campground.lat = g.json.get('raw').get('geometry').get('location').get(
         'lat')
     campground.lng = g.json.get('raw').get('geometry').get('location').get(
         'lng')
     if self.request.FILES.get('image'):
         destroy(campground.image_id)
         upload_result = upload(self.request.FILES['image'],
                                width=900,
                                height=500,
                                use_filename=True)
         campground.image_url = upload_result.get('secure_url')
         campground.image_id = upload_result.get('public_id')
     campground.save()
     messages.success(self.request,
                      '{} was edited successfully'.format(campground.name))
     return redirect('campgrounds:campground_details',
                     campground_id=campground.pk,
                     slug=campground.slug)
def delete_image(sender, instance, **kwargs):
    # We want to keep our review app placeholders
    if settings.HEROKU_APP_NAME:
        pass
    else:
        if instance.cloudinary_image:
            uploader.destroy(instance.cloudinary_image.public_id, invalidate=True)
示例#3
0
def delete_campground(request, campground_id, slug):
    campground = get_object_or_404(Campground, id=campground_id, slug=slug)
    name = campground.name
    destroy(campground.image_id)
    campground.delete()
    messages.success(request, '{} was deleted successfully'.format(name))
    return redirect(reverse('campgrounds:list_campgrounds'))
示例#4
0
 def delete(self):
     if self.uploaded:
         cloudinary_uploader.destroy(self.public_id,
                                     invalidate=True,
                                     resource_type=self.resource_type)
         self.instance = None
         self.uploaded = False
示例#5
0
def add_image(recipe_id): 
    #Validated @login covers non signed in users / validate_owner() prevents non owner from uploading new image
    if validate_owner(recipe_id) == True:
        ufile = request.files.get('file')
        # validate there is a file to upload
        if ufile:
            recipe = mongo.db.recipes.find_one({'_id': recipe_id})
            try:
                #if there is existing image delete from cloudinary
                destroy(recipe['image_public_id'], invalidate=True)
            except:
                pass
            #upload new image to cloudinary and add the associated information to the recipe in DB
            uploaded = upload(ufile)
            image_url = uploaded['secure_url']
            public_id = uploaded['public_id']

            mongo.db.recipes.update_one({'_id': recipe_id}, {"$set": {
                'img_url': image_url,
                'image_public_id': public_id,
            }}, upsert=True)
        else:
            pass
        return redirect(url_for('show_recipe', recipe_id=recipe_id))
    else:
        return redirect(url_for('show_recipe', recipe_id=recipe_id))
示例#6
0
def deleteSite(websiteid):
    """ Delete site route
    *   Deletes the website from the database

    Args:
    1.  websiteid (str): The website id

    Returns:
    *   Removes the website document as well as reference to website in user's
        array of websites. Also removes the website's image from cloudinary.
    """
    if session.get("user"):
        user_data = mongo.db.users.find_one({"username": session["user"]})
        if "websites" in user_data:
            if ObjectId(websiteid) in user_data["websites"]:
                mongo.db.users.find_one_and_update(
                    {'username': session["user"]},
                    {"$pull": {"websites": ObjectId(websiteid)}},
                    upsert=True)
                website = mongo.db.websites.find_one(
                    {"_id": ObjectId(websiteid)})
                destroy(website["image_id"])
                mongo.db.websites.delete_one({"_id": ObjectId(websiteid)})

                flash('Website was successfully removed', 'success')
                return redirect(url_for('user', username=session['user']))

    return redirect(url_for('index'))
示例#7
0
 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"})
示例#8
0
文件: views.py 项目: r4gus/Blogger
def edit_post(id):
    post = Post.query.get_or_404(id)
    form = EditPostForm()

    if post.author_id != current_user.id and not current_user.is_admin():
        flash("You can only edit your own posts.")
        return redirect(url_for('main.index'))

    if form.validate_on_submit():
        if 'image' in request.files:
            file = request.files['image']
            if file.filename != '':
                if file and allowed_file(file.filename):
                    filename = secure_filename(file.filename)
                    """
                    if os.path.isfile(os.path.join(current_app.config['UPLOAD_FOLDER'], filename)) == False:
                        if post.image_name and post.image_name != 'placeholder.jpg':
                            if os.path.isfile(os.path.join(current_app.config['UPLOAD_FOLDER'], post.image_name)):
                                os.remove(os.path.join(current_app.config['UPLOAD_FOLDER'], post.image_name))
                            file.save(os.path.join(current_app.config['UPLOAD_FOLDER'], filename))
                            post.image_name = filename
                    else:
                        flash('Invalid filename.')
                        return render_template(url_for('user.edit_post'), form=form)
                    """
                    if post.image_id:
                        destroy(public_id=post.image_id)  # delete old image
                    upload_result = upload(
                        file, folder="images",
                        unique_filename=True)  # upload new image

                    if upload_result:
                        secure_url = upload_result[
                            'secure_url']  # url that points to the image
                        public_id = upload_result['public_id']  # image id
                        post.image_url = secure_url
                        post.image_id = public_id
                    else:
                        flash("Couldn't upload the given file.")
                        return render_template(url_for('user.edit_post'),
                                               form=form)
                else:
                    flash('Invalid filename.')
                    return render_template(url_for('user.edit_post'),
                                           form=form)
        post.title = form.title.data
        post.short = form.short.data
        post.body = form.body.data
        db.session.add(post)
        db.session.commit()
        flash('The post has been updated.')
        return redirect(url_for('main.post', id=post.id))

    form.title.data = post.title
    form.short.data = post.short
    form.body.data = post.body
    return render_template('user/edit_post.html', form=form)
示例#9
0
def before_delete_page(request, page):
    """
    If ANY page is deleted that has the `cloudinary_image` field in it,
    check if the app is a review app (don't delete from review apps).
    Delete cloudinary_images from pages that have this field.
    """
    if hasattr(page, 'cloudinary_image'):
        if settings.REVIEW_APP:
            pass
        else:
            uploader.destroy(page.cloudinary_image.public_id, invalidate=True)
示例#10
0
    def test_uploading_landing_page(self):
        """
        Test case to check is method uploads landing page image to CLoudinary
        """
        self.new_project.save()
        url = 'https://themes.getbootstrap.com/wp-content/uploads/2019/08/quick-website-ui-kit-1.1.0-cover.jpg'
        details = self.new_project.upload_landing_page(url)

        self.assertEqual(self.new_project.landing_page_image,
                         details.get('url'))

        destroy(details.get('public_id'))
示例#11
0
文件: views.py 项目: r4gus/Blogger
def edit_profile():
    form = EditProfileForm()
    if form.validate_on_submit():

        if 'image' in request.files:
            file = request.files['image']
            if file.filename != '':
                if file and allowed_file(file.filename):
                    filename = secure_filename(file.filename)
                    """
                    if os.path.isfile(os.path.join(current_app.config['USER_PICTURES'], filename)) == False:
                        if current_user.image_name and current_user.image_name != 'user_placeholder.jpg':
                            if os.path.isfile(os.path.join(current_app.config['USER_PICTURES'], current_user.image_name)):
                                os.remove(os.path.join(current_app.config['USER_PICTURES'], current_user.image_name))
                        file.save(os.path.join(current_app.config['USER_PICTURES'], filename))
                        current_user.image_name = filename
                    else:
                        flash('Filename does already exist')
                        return render_template(url_for('user.edit_profile'), form=form)
                    """

                    if current_user.image_id:
                        destroy(public_id=current_user.image_id
                                )  # delete old image
                    upload_result = upload(
                        file, folder="images",
                        unique_filename=True)  # upload new image

                    if upload_result:
                        secure_url = upload_result[
                            'secure_url']  # url that points to the image
                        public_id = upload_result['public_id']  # image id
                        current_user.image_url = secure_url
                        current_user.image_id = public_id
                    else:
                        flash("Couldn't upload the given file.")
                        return render_template(url_for('user.edit_profile'),
                                               form=form)
                else:
                    flash('Invalid filename.')
                    return render_template(url_for('user.edit_profile'),
                                           form=form)

        current_user.username = form.username.data
        current_user.self_description = form.self_description.data
        db.session.add(current_user._get_current_object())
        db.session.commit()
        flash('Your profile has been updated.')
        return redirect(
            url_for('user.user_info', username=current_user.username))
    form.username.data = current_user.username
    form.self_description.data = current_user.self_description
    return render_template('user/edit_profile.html', form=form)
示例#12
0
def deletexp(experience_id):
    # find public_id of experience and delete the image on cloudinary
    experience = mongo.db.experiences.find_one(
        {"_id": ObjectId(experience_id)})
    destroy(experience['public_id'], invalidate=True)
    # then delete the experience from DB
    experiences = mongo.db.experiences.find()
    mongo.db.experiences.remove({"_id": ObjectId(experience_id)})
    flash("You have succesfully removed your experience")

    return render_template("profile.html",
                           username=session["user"],
                           experiences=experiences)
示例#13
0
文件: models.py 项目: tiagokick/first
def auto_delete_imagem_of_Destaque_on_change(sender, instance, **kwargs):
    if not instance.pk:
        return False
    try:
        old_file = Destaque.objects.get(pk=instance.pk).imagem.public_id
    except Destaque.DoesNotExist:
        return False
    new = True
    try:
        new_file = instance.imagem.public_id
    except:
        new = False
    if new == False:
        uploader.destroy(old_file, invalidate=True)
示例#14
0
    def test_upload_profile_pic(self):
        """
        Test case for checking is method uploads picture
        """
        url = 'https://cdn.business2community.com/wp-content/uploads/2017/08/blank-profile-picture-973460_640.png'

        details = self.new_user.upload_profile_pic(url)

        self.assertEqual(self.new_user.profile_pic, details.get('url'))
        destroy(details.get('public_id'))

        # Test if invalid image path is inserted
        with self.assertRaises(Exception):
            details = self.new_user.upload_profile_pic('Random path')
            self.assertEqual(self.new_user.profile_pic, details.get('url'))
def before_delete_page(request, page):
    """
    If ANY page is deleted that has the `cloudinary_image` field in it,
    check if the app is a review app (don't delete from review apps).
    Delete cloudinary_images from pages that have this field.
    """
    if hasattr(page, 'cloudinary_image'):
        if settings.REVIEW_APP or settings.DEBUG:
            pass
        else:
            uploader.destroy(page.cloudinary_image.public_id, invalidate=True)

    if isinstance(page, ProductPage) and page.votes:
        # Delete the vote from ProductPages
        page.votes.delete()
示例#16
0
    def _delete_file(self, **options):
        cloudinary_options = self.get_cloudinary_options()
        cloudinary_options.update(options.get('cloudinary', {}))

        file = self.get_file()
        if not file:
            return

        file_field = self.get_file_field()

        try:
            result = uploader.destroy(self.name,
                                      type=file_field.type,
                                      resource_type=file_field.resource_type,
                                      **cloudinary_options)
        except cloudinary.exceptions.Error:
            logger.exception("Couldn't delete Cloudinary file: {}".format(
                self.name))
            return

        status = result.get('result')
        if status == 'ok':
            self.set_file(None)
        else:
            logger.warning("Unable to delete Cloudinary file `{}`: {}".format(
                self.name, status))
        return result
示例#17
0
    def delete(self):
        """
        @api {DELETE}    /image/  Delete an image
        @apiName         DeleteImage
        @apiGroup        Delete
        @apiDescription  Delete an image of a student.

        @apiParam  {String}  image_id  The image identifier.

        @apiParamExample  {json}  Request Example
                          {"image_id": "x3f32gs33fewesf"}

        @apiSuccess {String}  success  ok

        @apiUse    RequestParsingErrors

        @apiVersion 1.0.0
        """
        try:
            image_id, data = self.read_request('image_id')

            _config()
            img = uploader.destroy(image_id)
            self.db.image.remove({'_id': image_id})

            self.response['success'] = 'ok'
            self.write_response()
        except base.ErrorSentException:
            pass
示例#18
0
    def delete_image(self, public_id):
        """Delete image from cloudinary

    returns: {'result': 'ok'}
    """

        return uploader.destroy(public_id)
示例#19
0
 def init_class(cls, storage):
     with open(cls.upload_file, 'rb') as fp:
         storage.resource = uploader.upload_resource(
             fp,
             type=cls.type,
             resource_type=cls.resource_type,
             folder='data/now',
             use_filename=True,
             unique_filename=True,
             overwrite=True)
     storage.file = CloudinaryFieldFile(storage.resource,
                                        checksum=cls.resource_checksum)
     yield
     uploader.destroy(storage.resource.public_id,
                      type=cls.type,
                      resource_type=cls.resource_type,
                      invalidate=True)
示例#20
0
文件: views.py 项目: r4gus/Blogger
def delete_post(id):
    post = Post.query.get_or_404(id)

    if post.author_id != current_user.id and not current_user.is_admin():
        flash("You can only delete your own posts.")
        return redirect(url_for('main.post', id=post.id))
    else:
        """
        if post.image_name and post.image_name != 'placeholder.jpg':
            if os.path.isfile(os.path.join(current_app.config['UPLOAD_FOLDER'], post.image_name)):
                os.remove(os.path.join(current_app.config['UPLOAD_FOLDER'], post.image_name))
        """

        if post.image_id:
            destroy(public_id=post.image_id)  # delete old image
        db.session.delete(post)
        db.session.commit()
        flash("Post successfully deleted.")
        return redirect(url_for('main.index'))
示例#21
0
def update_profile(user_id):
    """ Updates the users db record with the POST form data, also updates the cloadinary image data

   :return
       Redirect to profile.html

    """
    # REFERENCE CREDITS:
    # Cloudinary api ->
    # https://github.com/tiagocordeiro/flask-cloudinary

    file_to_upload = request.files.get('file')

    if file_to_upload:
        # Current user record
        current_user = DB_USERS.find_one({'_id': ObjectId(user_id)})

        if current_user['profile_image_id'] != 'xmt2q3ttok9cwjlux8j2':
            # Remove current profile image
            destroy(current_user['profile_image_id'], invalidate=True)

        # Upload new image to cloudinary
        upload_result = upload(file_to_upload)
        # Update users profile image in DB
        DB_USERS.update_one({'_id': ObjectId(user_id)}, {
            "$set": {
                'profile_image': upload_result['secure_url'],
                'profile_image_id': upload_result['public_id']
            }
        },
                            upsert=True)

    #  Update users profile data
    DB_USERS.update_one({'_id': ObjectId(user_id)}, {
        "$set": {
            'bio': request.form.get('bio'),
            'email': request.form.get('email')
        }
    },
                        upsert=True)

    return redirect(url_for('profile'))
示例#22
0
文件: views.py 项目: r4gus/Blogger
def delete_user(id):
    user = User.query.get_or_404(id)

    if current_user.id != id and not current_user.is_admin():
        flash("You can only delete your own account")
        return redirect(
            url_for('user.user_info', username=current_user.username))
    else:
        """
        if user.image_name and user.image_name != 'user_placeholder.jpg':
            if os.path.isfile(os.path.join(current_app.config['USER_PICTURES'], user.image_name)):
                os.remove(os.path.join(current_app.config['USER_PICTURES'], user.image_name))
        """
        if user.image_id:
            destroy(public_id=user.image_id)  # delete old image

        db.session.delete(user)
        db.session.commit()
        flash("Account successfully deleted")
        return redirect(url_for('main.index'))
示例#23
0
 def delete(self):
     """
     Delete passport image
     """
     user_id = get_jwt_identity()
     image = Image.query.filter_by(user=user_id).first()
     if not image:
         response = {
             'status': 'failed',
             'message': 'You do not have a passport image saved. '
         }
         return make_response(jsonify(response))
     else:
         destroy(str(user_id))
         image.delete()
         response = {
             'status': 'success',
             'message': 'Passport image has been successfully deleted'
         }
         return make_response(jsonify(response)), 200
示例#24
0
def delete_user(user_id):
    """ Deletes the users db record , also Delete the cloadinary image data and all users recipe data
       :return
           Redirect to sign in view
        """
    # REFERENCE CREDITS:
    # Cloudinary api ->
    # https://github.com/tiagocordeiro/flask-cloudinary

    # User exists in the database and Signed in
    if session.get('USERNAME', None):
        username = session['USERNAME']
        # user exists in the database
        current_user = DB_USERS.find_one({'username': username})
        requested_user = DB_USERS.find_one({'_id': ObjectId(user_id)})

        # if the current logged in user is the user requested
        if requested_user['_id'] == current_user['_id']:
            # Delete related user records
            DB_RECIPES.delete_many({'author_id': ObjectId(user_id)})
            DB_INGREDIENTS.delete_many({'author_id': ObjectId(user_id)})
            DB_METHODS.delete_many({'author_id': ObjectId(user_id)})

            # Delete the current user image form cloudinary
            current_user = DB_USERS.find_one({'_id': ObjectId(user_id)})
            if current_user['profile_image_id'] != 'wbzphoxefkdid3kheuqd':
                destroy(current_user['profile_image_id'], invalidate=True)

            # Delete main user record
            DB_USERS.remove({'_id': ObjectId(user_id)})
            return redirect(url_for('sign_out'))

        else:
            # raises a 404 error if any of these fail
            return abort(403, description="Forbidden")
    else:
        # raises a 404 error if any of these fail
        return abort(403, description="Forbidden")
示例#25
0
def update_recipe_image(user_id, recipe_id):
    """ Updates the recipe image in cloudinary

    :return
        returns the edit-recipe.html form image tab with updated image

    """
    # User not Signed in
    if not session.get('USERNAME', None):
        return redirect(url_for('sign_in'))

    # get the file from the form
    file_to_upload = request.files.get('file')

    if file_to_upload:
        # get the current recipe record
        current_recipe = DB_RECIPES.find_one({'_id': ObjectId(recipe_id)})
        # delete the current recipe image on cloudinary
        if current_recipe['image_url_id'] != 'gi5h7ejymbig1yybptcy':
            destroy(current_recipe['image_url_id'], invalidate=True)
        # upload the new image
        upload_result = upload(file_to_upload)

        # update record
        DB_RECIPES.update_one({'_id': ObjectId(recipe_id)}, {
            "$set": {
                'image_url': upload_result['secure_url'],
                'image_url_id': upload_result['public_id'],
                'date_updated': TODAY_STR
            }
        },
                              upsert=True)

    return redirect(
        url_for('edit_recipe',
                _anchor='image',
                user_id=user_id,
                recipe_id=recipe_id))
示例#26
0
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)
示例#27
0
def delete_file(key, resource_type, cld_type, cld_public_id):
    """
    A wrapper for the SDK destroy method
    """
    status_code, status_msg = 500, "delete_file failed"
    destroy_result = destroy(public_id=cld_public_id,
                             resource_type=resource_type,
                             type=cld_type,
                             invalidate=True)
    if destroy_result['result'] == "not found":
        # We should not arrive here usually, as there is a prelimnary search
        status_code, status_msg = 404, "File not found on Cloudinary while trying to delete"
    elif destroy_result['result'] == "ok":
        status_code, status_msg = 200, "OK"
    return status_code, status_msg
示例#28
0
def delFile():
    data = request.get_json(force=True)
    subform = mongo.db.subform
    res = subform.update(
        {},
        {'$pull': {
            'files': data['file']
        }},
    )
    result = uploader.destroy(data['file']['public_id'])
    if (result['result'] == 'ok'):
        updateData = subform.find_one({"_id": ObjectId(data['_id'])})
        updateData['_id'] = str(updateData['_id'])
        return jsonify({'success': True, 'data': updateData})
    return jsonify({'success': False})
示例#29
0
def parent_profile_upload(parent_username):
    form = json.loads(request.headers['Json'])
    token1 = request.headers['Token1']
    token2 = request.headers['Token2']

    if hashing.Decrypted([token1, token2]) != True:
        response = {'error_message': 'HTTP_403_FORBIDDEN, cannot access'}
        return jsonify(response), status.HTTP_403_FORBIDDEN

    org_profile_pic = None
    Edit = False  #True if this is an Edit request; otherwise it is the first time upload
    if handle.parent.find({'username': parent_username}).count() != 0:
        Edit = True
        cursor = handle.parent.find_one({'username': parent_username})
        org_profile_pic = cursor['profile_pic']
        handle.parent.delete_many({'username': parent_username})

    #delete existing profile/cover pictures
    if org_profile_pic != None:
        match = re.search('.*\/(\S+)\.\S+', org_profile_pic)
        if match:
            public_id = match.group(1)
            delete_res = destroy(public_id)

    #upload pictures and get pic urls
    upload_result = None
    profile_pic_url = None
    profile_pic = request.files['profile_pic']
    if profile_pic:
        upload_result = upload(profile_pic)
        profile_pic_url = upload_result['url']

    if profile_pic_url != None:
        form['profile_pic'] = profile_pic_url
    else:
        form['profile_pic'] = ""

    #upload the profile body
    parent = {'username': parent_username, 'profile_pic': form['profile_pic']}
    handle.parent.insert(parent)
    if Edit == True:
        response = {"message": "successfully updated parent profile"}
    else:
        response = {"message": "successfully inserted parent profile"}
    return jsonify(response), status.HTTP_200_OK
示例#30
0
    def delete_image(self, id):
        #get dictionary from db with id
        image = db.session.query(picture).filter_by(id = id).first()
        public_id = image.public_id

        #delete picture on cloudinary with the public_id
        result = uploader.destroy(public_id)

        #based on the respose delete from db or return error message
        if result['result'] == 'ok':
            db.session.delete(image)
            db.session.commit()
            return {
                "message":"Image deleted",
                "deleted":True
                }
        else:
            return {
                "message":"Image failed to delete, try again later",
                "deleted":False
                }
示例#31
0
文件: models.py 项目: swasher/sith
def purge_cloudinary(sender, instance, **kwargs):
    """Deletes file from cloudinary
    when corresponding `Image` object is deleted.
    """
    destroy(instance.picture.public_id)
示例#32
0
 def remove(path, public_id):
     res = uploader.destroy(public_id)
     return res
示例#33
0
 def _delete_file(self, filename):
     uploader.destroy(f'reports/{filename}')
示例#34
0
 def get(request, publication_id, *args, **kwargs):
     if Publication.objects.get(id=publication_id).author == request.user or request.user.is_superuser:
         p_id = 'p' + str(publication_id)
         uploader.destroy(p_id, invalidate=True)
         Publication.objects.get(id=publication_id).delete()
     return redirect(reverse('home'))