Example #1
0
def upload_ajax(request):
    if request.method == 'POST':
        if not request.session.get('id'):
            return HttpResponse("请先登录后再上传")
        file_obj = request.FILES.get('file')
        type_list = ['.jpg', '.png']
        try:
            title = request.POST['title']
        except KeyError:
            title = "无标题"

        if os.path.splitext(file_obj.name)[1].lower() in type_list:
            savename = "%s_im_%s" % (random.randint(10000, 99999), file_obj.name)
            f = open(os.path.join(BASE_DIR, 'static', 'images', savename), 'wb')
            for chunk in file_obj.chunks():
                f.write(chunk)
            f.close()
            user = User.objects.get(id=request.session.get('id'))

            if os.path.getsize("%s/%s" % (os.path.join(BASE_DIR, 'static', 'images'), savename)) > 1024000:
                img = Image.open('%s/%s' % (os.path.join(BASE_DIR, 'static', 'images'), savename))
                w, h = img.size
                img.thumbnail((w / 2, h / 2), Image.ANTIALIAS)
                savename = "%s_%s" % ('new', savename)
                img.save("%s/%s" % (os.path.join(BASE_DIR, 'static', 'images'), savename), "JPEG")
            p = Picture(user=user, filename=savename, title=title, haveher=False, good=0, show=False)
            p.save()
            return HttpResponse('OK')
        return HttpResponse("错误上传类型")
Example #2
0
def upload():
    form = PictureForm()
    if form.validate_on_submit():
        if 'file' not in request.files:
            flash('No File!')
            return redirect(url_for('upload'))
        if form.file.data.filename == '':
            flash('No Selected File!')
            return redirect(url_for('upload'))
        if form.file and allowed_file(form.file.data.filename):
            filename = secure_filename(form.file.data.filename)
            extension = filename.rsplit('.', 1)[1].lower()
            picture = Picture(extension=extension,
                              description=form.description.data,
                              shot_time=form.shot_time.data,
                              place=form.place.data,
                              tags=form.tags.data)
            picture.save()
            unified_filename = str(picture.id) + '.' + extension
            f = form.file.data
            try:
                picture_handler(f, unified_filename)
            except:
                print("picture file may not be updated")
            flash('New picture uploaded!')
            return redirect(url_for('admin.upload'))
    return render_template('admin/upload.html', title='Upload', form=form)
Example #3
0
 def test_deletePictures(self, activeClient, testPicture):
     name = testPicture.name
     id = Picture.query.filter_by(name=name).first().id
     testform = form(None, deletePictures([id]))
     assert testPicture.is_file()
     Picture.deletePictures(testform)
     assert not testPicture.is_file()
Example #4
0
def users_upload_photos(user_id):
    user = User.query.filter_by(id=user_id).first()
    if user.id != current_user.id:
        return make_response(jsonify({'error': 'User not authenticated'}), 403)

    picture_file = request.files['picture']
    filename = picture_file.filename
    extension = filename.rsplit('.', 1)[1]

    picture = Picture()
    picture.extension = extension
    db.session.add(picture)
    db.session.commit()

    user.profile_picture_id = picture.id
    db.session.add(user)
    db.session.commit()

    upload_filename = "users/%d/profile_pictures/%d.%s" % (current_user.id,
        picture.id, extension)

    if os.environ.get('FLASK_ENV') == 'production':
        AWS_ACCESS_KEY = os.environ.get('AWS_ACCESS_KEY')
        AWS_SECRET_KEY = os.environ.get('AWS_SECRET_KEY')
        conn = tinys3.Connection(AWS_ACCESS_KEY, AWS_SECRET_KEY, tls=True)
        conn.upload(upload_filename, picture_file, 'neighborme-photos')
    else:
        save_path = os.path.join(config['UPLOAD_FOLDER'],
            upload_filename)
        if not os.path.exists(os.path.dirname(save_path)):
            os.makedirs(os.path.dirname(save_path))
        picture_file.save(save_path)

    return jsonify({'status': 'OK'})
Example #5
0
 def _start():
     if face.faceai(filepath + "/" + filename):
         p = Picture(filename=filename,
                     title="default",
                     haveher=True,
                     good=0)
         p.save()
         print("Upload Picture")
Example #6
0
def reviewEdit(id):
    review = Review.query.get(id)
    if request.method == 'GET':
        session['referrer'] = request.referrer
        form = ReviewEditForm(id=review.id,
                              name=review.provider.name,
                              category_id=review.category_id,
                              rating=review.rating,
                              cost=review.cost,
                              price_paid=review.price_paid,
                              description=review.description,
                              service_date=review.service_date,
                              comments=review.comments)
        form.populate_choices(review)
        return render_template("review_edit.html",
                               title="Review - Edit",
                               form=form,
                               review=review)
    else:
        form = ReviewEditForm()
        form.populate_choices(review)
        if form.validate_on_submit():
            if form.deletePictures.data is not None:
                try:
                    Picture.deletePictures(form)
                except FileNotFoundError as e:
                    flash(str(e))
            if form.picture.data:
                new_pictures = Picture.savePictures(form, review.pictures)
            try:
                review.update(category_id=form.category.data,
                              rating=form.rating.data,
                              cost=form.cost.data,
                              price_paid=form.price_paid.data,
                              description=form.description.data,
                              service_date=form.service_date.data,
                              comments=form.comments.data,
                              pictures=new_pictures)
                flash("Review updated.")
            except SQLAlchemyError as e:
                flash(str(e))
                return render_template("review_edit.html",
                                       title="Review - Edit",
                                       form=form), 422

            try:
                url = session['referrer']
                session.pop('referrer')
            except KeyError:
                url = url_for('main.user', username=current_user.username)
            finally:
                return redirect(url)

        flash("Please correct form errors.")
        return render_template("review_edit.html",
                               title="Review - Edit",
                               form=form), 422
Example #7
0
    def save_to_graph(self, photos):
        """
        parameters
        ----------
        photos: array - see the return of retrieve_photos_from_flickr() for the structure
        """

        self.stdout.write("* Saving photos information in the graph", ending='\r')

        # list of tags from all photos without duplicates (several photos may have the same tag)
        # used to cache the Interest objects and create the nodes if they don't exist
        # while reducing the number of queries on the database
        interests = {}

        index = 1
        for photo in photos:
            url = photo['url']

            try:
                picture = Picture(pictureURL=url)
                picture.save()
            except UniqueProperty:
                # a picture node with this url already exists in the graph
                # we will only update the interests it is RELATED_TO
                picture = Picture.nodes.get(pictureURL=url)

            for tag in photo['tags']:
                if tag == self.SEARCH_TAG:
                    # we don't add the 'couple' tag to the database because of course our app is about couples
                    continue

                # if the tag hasn't been added yet to the list of interests
                if tag not in interests:
                    try:
                        interest = Interest(label=tag)
                        interest.save()
                    except UniqueProperty:
                        # an interest node with this label already exists in the graph
                        interest = Interest.nodes.get(label=tag)

                    interests[tag] = interest
                else:
                    # the interest is already in the list, get it and avoid a useless query to the db
                    interest = interests[tag]

                picture.tags.connect(interest)

            self.stdout.write('* Photos saved: {}                         '.format(index),
                              ending='\r')

            index += 1

        self.stdout.write('')
Example #8
0
def img_upload_ui():
    img_obj = request.files.get("file")
    filename = img_obj.filename
    img_type = filename[filename.rfind(".") + 1:]
    from app.models import Picture
    # pic = Picture(image=img_obj)
    pic = Picture(family="swipers", creator="user open id", img_type=img_type)
    # 添加图片,并且 追加一个 content_type 属性进去,回头返回的时候,也好填写 Conten-Type 啊
    pic.image.put(img_obj, content_type=img_obj.content_type)
    rs = pic.save()
    # rs.id 是 objectId: Object of type 'ObjectId' is not JSON serializable,所以这里把它转成字符串str
    return jsonify({"pic_id": str(rs.id)})
Example #9
0
def classifier(request, classifier_name):
	classifier = Classifier.objects.get(name=classifier_name)
	if request.method == 'GET':
		context = { 'name': classifier.name, 'class0': classifier.class0,
					'class1': classifier.class1, 'algorithm': classifier.algorithm,
					'description': classifier.description }
		return render(request, 'classifier.html', context)
	else:
		pictureFiles = request.FILES.getlist('img')
		newPicsList = []
		for pic in pictureFiles:
			newPic = Picture(picture = pic)
			newPic.save()
			newPicsList.append(newPic)
		return classificationResult(request, classifier, newPicsList)
Example #10
0
def uploadpic():
    '''
    上传图片
    '''
    categorylist = Category.query.all()

    if request.method == 'POST' and 'photo' in request.files:
        # 获取后缀
        suffix = os.path.splitext(request.files['photo'].filename)[-1]
        # 合成图片名
        filename = gen_rnd_filename() + suffix
        # 保存图片
        piclink = photos.save(request.files['photo'], name=filename)

        # # 生成缩略图
        # pathname = os.path.join(current_app.config['UPLOADED_PHOTOS_DEST'], filename)
        # img = Image.open(pathname)
        # img.thumbnail((512, 512))
        # img.save(pathname)

        # print(piclink)
        # print(filename)

        # 获取图片标题
        name = request.form.get('name')
        # 获取图片分类
        category = request.form.get('category')
        # 获取图片描述
        describe = request.form.get('describe')

        # 判断图片分类是否已经存在,如果不存在则进行添加
        # if category
        # 插入数据库
        if describe:
            pic = Picture(picname=name,
                          piclink='upload/' + piclink,
                          category_id=category,
                          describe=describe)
        else:
            pic = Picture(picname=name,
                          piclink='upload/' + piclink,
                          category_id=category)
        db.session.add(pic)

        flash('图片上传成功')
        return redirect(url_for('aboutadmin.uploadpic'))
    return render_template('dandan_manage/form-line.html',
                           categorylist=categorylist)
Example #11
0
def testPicture(activeClient):
    # named tuples to mock form
    form = namedtuple('form', ['picture', 'deletePictures'])
    picture = namedtuple('picture', 'data')
    filename = "test1.jpg"
    p = os.path.join(current_app.config['MEDIA_FOLDER'], 'source', filename)
    f = open(p, 'rb')
    fs = FileStorage(stream=f, filename=filename, content_type='image/jpeg')
    testform = form(picture([fs]), None)
    pic = Picture.savePictures(testform)[0]
    pic.review_id = 1
    db.session.add(pic)
    db.session.commit()
    path = Path(
        os.path.join(
            current_app.config['MEDIA_FOLDER'], str(current_user.id),
            f'{current_user.username}_1.jpg'
        )
    )
    yield path
    try:
        rmtree(path.parent)
    except FileNotFoundError as e:
        print(e)
        pass
Example #12
0
def upload():
    """图片上传处理"""
    file = request.files.get('file')
    if not allowed_file(file.filename):
        res = {'code': 0, 'msg': '图片格式异常'}
    else:
        url_path = ''
        upload_type = current_app.config.get('H3BLOG_UPLOAD_TYPE')
        ex = os.path.splitext(file.filename)[1]
        filename = datetime.now().strftime('%Y%m%d%H%M%S') + ex
        if upload_type is None or upload_type == '' or upload_type == 'local':
            file.save(
                os.path.join(current_app.config['H3BLOG_UPLOAD_PATH'],
                             filename))
            url_path = url_for('admin.get_image', filename=filename)
        elif upload_type == 'qiniu':
            try:
                qiniu_cdn_url = current_app.config.get('QINIU_CDN_URL')
                url_path = qiniu_cdn_url + upload_file_qiniu(
                    file.read(), filename)
            except Exception as e:
                return jsonify({'success': 0, 'message': '上传图片异常'})
        #返回
        pic = Picture(
            name=file.filename if len(file.filename) < 32 else filename,
            url=url_path)
        db.session.add(pic)
        res = {'code': 1, 'msg': u'图片上传成功', 'url': url_path}
    return jsonify(res)
Example #13
0
    def post(self):
        form = PostForm()
        if request.method == 'POST':
            if form.validate_on_submit():
                post = Post.create()
                form.populate_obj(post)
                f = request.files.get('file')
                post.user = current_user

                if f:
                    picture = Picture.create()
                    picture.save_file(f, current_user)
                    post.cover_picture_id = picture.id if picture else 0

                post.update_score(page_view=1)
                post.save()

                if form.remain.data:
                    url = url_for('PostsView:put', id=post.id)
                else:
                    url = url_for('PostsView:get', id=post.id)

                return resp(url, redirect=True,
                            message=gettext('Stamp succesfully created'))
            else:
                return resp('admin/posts/edit.html', status=False, form=form,
                            message=gettext('Invalid submission, please check the message below'))

        return resp('admin/posts/edit.html', form=form)
Example #14
0
def img_upload():
    # for attr in dir(request):
    #     print(attr, getattr(request, attr))
    # print("request.files", request.files)
    img_obj = request.files.get("img")
    filename = img_obj.filename
    img_type = filename[filename.rfind(".") + 1:]
    from app.models import Picture
    # pic = Picture(image=img_obj)
    pic = Picture(family="avatar", creator="user open id", img_type=img_type)
    # 添加图片,并且 追加一个 content_type 属性进去,回头返回的时候,也好填写 Conten-Type 啊
    pic.image.put(img_obj, content_type=img_obj.content_type)
    rs = pic.save()
    print(rs.to_mongo())
    print(rs.id)
    return jsonify(rs)
Example #15
0
def downloadImages(current_user_id, lines):
    app = scheduler.app
    with app.app_context():
        for line in lines:
            urlString = str(line)
            idIndex = urlString.find("://")
            fileName = str(current_user_id) + "/" + urlString[idIndex +
                                                              3:] + ".jpg"
            filePath = os.path.join(app.config['UPLOAD_FOLDER'],
                                    secure_filename(fileName))
            urlPath = filePath.replace("app/static/", "")
            picture = Picture.query.filter_by(url=urlPath).first()
            if picture is None:
                with open(filePath, "wb") as imageFile:
                    response = requests.get(line)
                    imageFile.write(response.content)
                    imageFile.close()
                    img = Image.open(filePath).convert('L')
                    greyFilePath = filePath.replace(".jpg", "-greyscale.jpg")
                    greyUrlPath = urlPath.replace(".jpg", "-greyscale.jpg")
                    img.save(greyFilePath, "JPEG")
                    picture = Picture(url=urlPath,
                                      greyurl=greyUrlPath,
                                      width=img.width,
                                      height=img.height,
                                      user_id=current_user_id)
                    db.session.add(picture)
                    db.session.commit()
Example #16
0
def review():
    if request.method == 'GET':
        if len(request.args) != 0:
            form = ReviewForm(request.args)
        else:
            flash("Invalid request. Please search for provider first and then"
                  " add review.")
            return redirect(url_for('main.index'))
    elif request.method == 'POST':
        form = ReviewForm()
    provider = Provider.query.get(form.id.data)
    form.category.choices = [(c.id, c.name) for c in provider.categories]
    if form.validate_on_submit():
        pictures = Picture.savePictures(form)
        Review.create(user_id=current_user.id,
                      provider_id=form.id.data,
                      category_id=form.category.data,
                      rating=form.rating.data,
                      cost=form.cost.data,
                      price_paid=form.price_paid.data,
                      description=form.description.data,
                      service_date=form.service_date.data,
                      comments=form.comments.data,
                      pictures=pictures)
        flash("review added")
        return redirect(url_for('main.index'))
    elif request.method == "POST" and not form.validate():
        return render_template("review.html", title="Review", form=form), 422
    if not current_user.email_verified:
        disableForm(form)
        flash("Form disabled. Please verify email to unlock.")
    return render_template("review.html", title="Review", form=form)
Example #17
0
def upload(request):
    if request.method == "POST":
        print(request.FILES.get("file"), type(request.FILES.get("file")))
        temp_file = request.FILES.get("file")
        if request.POST.get("type") == "picture":
            img = Picture(file=temp_file,
                          name=temp_file.name,
                          size=temp_file.size,
                          point=request.POST.get("point", None),
                          title=request.POST.get("title", None),
                          type=request.POST.get("type_picture", None),
                          album=PhotoAlbum.objects.filter(
                              id=request.POST.get("album_id")).first(),
                          date=datetime.datetime.now().strftime('%Y-%m-%d'))
            img.save()
            obj = PhotoAlbum.objects.filter(id=request.POST.get("album_id"))
            length = Picture.objects.filter(album_id=obj)
            print(len(length), type(length))
            obj.update(count=len(length))
            return HttpResponse(json.dumps(
                {"data": {
                    "e": 0,
                    "code": "success"
                }}),
                                content_type="application/json")
        else:
            media = Media(file=temp_file,
                          name=temp_file.name,
                          size=temp_file.size,
                          point=request.POST.get("point", None),
                          title=request.POST.get("title", None),
                          date=datetime.datetime.now().strftime('%Y-%m-%d'))
            media.save()
            return HttpResponse(json.dumps(
                {"data": {
                    "e": 0,
                    "code": "success"
                }}),
                                content_type="application/json")
    return HttpResponse(json.dumps({
        "data": {
            "e": -1,
            "code": "{} method don't allow".format(request.method)
        }
    }),
                        content_type="application/json")
    def test_mkdir_edit_image_by_name(self):
        pic = Picture(name_picture="test")
        db.session.add(pic)
        db.session.commit()

        edit_folder_name_pic = os.path.join(
            self.path, os.path.join(Config.EDIT_IMAGE, pic.name_picture))
        result, folder_path = mkdir_edit_folder_name_pic(edit_folder_name_pic)
        self.assertTrue(result)
        self.assertEqual(folder_path, edit_folder_name_pic)
Example #19
0
    def upload_profile_picture(self, id):
        user = User.get_by_id(id)

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

        if f:
            picture = Picture.create()
            picture.save_file(f, current_user)
            user.profile_picture_id = picture.id if picture else 0
            user.save()

        return resp('', user=user)
Example #20
0
 def test_savePictures(self, activeClient):
     filename = "test.jpg"
     path = os.path.join(current_app.config['MEDIA_FOLDER'], 'source',
                         filename)
     f = open(path, 'rb')
     fs = FileStorage(stream=f,
                      filename=filename,
                      content_type='image/jpeg')
     testform = form(picture([fs]), None)
     try:
         Picture.savePictures(testform)
         path = Path(
             os.path.join(current_app.config['MEDIA_FOLDER'],
                          str(current_user.id), filename))
         check_path = Path(
             os.path.join(current_app.config['MEDIA_FOLDER'],
                          str(current_user.id),
                          f'{current_user.username}_1.jpg'))
         assert check_path.is_file()
     finally:
         path = os.path.join(current_app.config['MEDIA_FOLDER'],
                             str(current_user.id))
         rmtree(path)
Example #21
0
def pictures_by_tag(tag):
    """
    view photos by tag
    """
    pictures = Picture.objects(tags=tag).order_by('-shot_time')
    tag_dict = {
        'mountain': '高山',
        'water': '流水',
        'things': '万物',
        'people': '人间',
        'me': '我',
    }
    return render_template('main/pictures_by_tag.html',
                           pictures=pictures,
                           tag=tag,
                           tag_dict=tag_dict)
Example #22
0
def pictures_by_year():
    """
    view photos by year
    """
    pictures = Picture.objects().order_by('-shot_time')
    year = 0
    years = []
    pictures_by_year = defaultdict(list)
    for picture in pictures:
        year = picture.shot_time.year
        if year not in years:
            years.append(year)
        pictures_by_year[year].append(picture)
    return render_template('main/pictures_by_year.html',
                           pictures_by_year=pictures_by_year,
                           years=years)
Example #23
0
def add_picture():
    form = PostForm()
    if request.method == 'POST':
        file = request.files['file']
        if file and (file.content_type.rsplit('/', 1)[1]
                     in ALLOWED_EXTENSIONS).__bool__():
            filename = secure_filename(file.filename)
            file.save(UPLOAD_FOLDER + filename)
            url = os.path.join('uploads/', filename)
        today = datetime.datetime.today().strftime("%Y.%m.%d %H:%M")
        post = Picture(Title=form.title.data, photo=url, date=today)
        db.session.add(post)
        db.session.commit()
        flash('Your post is now live!')
        return redirect(url_for("add_picture", form=form))
    return render_template("gallery_add.html", form=form)
Example #24
0
    def post(self):
        form = PostForm()

        if form.validate_on_submit():
            try:
                if not form.validate():
                    raise Exception(_('ERROR_INVALID_SUBMISSION'))

                remain = request.values.get('remain', False, bool)
                post = Post.create()
                form.populate_obj(post)
                post.user = current_user

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

                if f:
                    picture = Picture.create()
                    picture.save_file(f, current_user)
                    post.cover_picture_id = picture.id if picture else 0

                # init the score
                post.update_score(page_view=1)

                post.editor_version = 1
                post.save()

                Feed.clear_feed_cache()

                if post.is_draft:
                    message = _('POST_DRAFT_SAVE_SUCESS')
                else:
                    message = _('POST_PUBLIC_SAVE_SUCESS')

                if remain:
                    url = url_for('PostsView:put', id=post.id, remain='y')
                else:
                    url = url_for('PostsView:get', id=post.id)

                return render_view(url, redirect=True, message=message)

            except Exception as e:
                flash(e.message, 'error')

        return render_view('admin/posts/edit.html',
                           form=form)
Example #25
0
def add_picture_submit():
    def allowed_file(filename):
        return '.' in filename and filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS
    if request.method == 'POST':
        file = request.files['file']
        file_m = request.files['file1']
        address = request.form.get("address")
        name = request.form.get("title")
        if file and allowed_file(file.filename) and file_m and allowed_file(file_m.filename):
            filetype = file.filename.rsplit('.',1)[1]
            filetype_m = file_m.filename.rsplit('.',1)[1]
            # 文档格式
            filename = secure_filename(file.filename)
            filename_m = secure_filename(file_m.filename)
            # 文件类型admin/product
            savename = name+"."+filetype
            savename_m = name+"."+filetype_m
            savepath = UPLOAD_FOLDER+address+"/"+savename
            address_p = DOWNLOAD_FOLDER+address+"/"+savename
            savepath_m = UPLOAD_FOLDER_MUSIC+address+"/"+savename_m
            address_m = DOWNLOAD_FOLDER_MUSIC+address+"/"+savename_m
            count1 = db.session.query(db.func.count('*')).select_from(Picture).filter(Picture.name==name).scalar()
            count2 = db.session.query(db.func.count('*')).select_from(Music).filter(Music.name==name).scalar()
            print "save name is ",savename
            print "save path is ",savepath
            if count1 > 0 and count2 >0:
                return "该文件已经存在,如果想继续储存,请修改文件英文名称"
            else:
                try:
                    pic = Picture(name=name,
                              situation=address,
                              address=address_p)
                    music = Music(name=name,
                              situation=address,
                              address=address_m)
                    db.session.add(pic)
                    db.session.add(music)
                    db.session.commit()
                except Exception, e:
                    raise e
                    # raise Exception("该文件已经存在")
                file.save(savepath)
                file_m.save(savepath_m)
                return redirect(url_for("main.add_picture"))
Example #26
0
def index():
    """
    main page of the blog:
    it shows 5pages carousel
    10 photos ordered by shot time per page
    """
    pictures = Picture.objects().order_by('-shot_time')
    l = len(pictures)
    if l > 5:
        carousel_pictures = random.sample(list(pictures), 5)
    else:
        carousel_pictures = random.sample(list(pictures), l)
    page = request.args.get('page', 1, type=int)
    paginated_pictures = pictures.paginate(
        page=page, per_page=current_app.config['PIC_PER_PAGE'])
    current_page = paginated_pictures.page
    total_page = paginated_pictures.pages

    page_start = 1
    page_end = 5
    if total_page < 5:
        page_end = total_page
    else:
        page_start = current_page - 2
        page_end = current_page + 2
        if page_start < 1:
            page_start = 1
            page_end = 5
        if page_end > total_page:
            page_start = total_page - 4
            page_end = total_page

    url_list = []
    for p in range(1, total_page + 1):  # so page number start from 1
        url = url_for('main.index', page=p)
        url_list.append(url)
    return render_template('main/index.html',
                           pictures=paginated_pictures.items,
                           carousel_pictures=carousel_pictures,
                           current_page=current_page,
                           total_page=total_page,
                           page_start=page_start,
                           page_end=page_end,
                           url_list=url_list)
Example #27
0
    def put(self, id):
        post = Post.get_by_id(id)

        if post is None or not post.can_edit():
            flash(gettext('The requested stamp was not found'), 'error')
            return redirect(url_for('PostsView:index'))

        if request.method in ['POST']:
            form = PostForm()
            if form.validate_on_submit():
                cover_picture_id = request.values.get('cover_picture_id', 0, int)
                remain = request.values.get('remain', False, bool)

                if post.cover_picture and cover_picture_id == 0:
                    # remove the picture, when user request its deletion
                    post.cover_picture.remove()
                c = form.category_id.data
                form.populate_obj(post)

                f = request.files.get('file')
                if f:
                    if post.cover_picture:
                        post.cover_picture.remove()
                    picture = Picture.create()
                    picture.save_file(f, current_user)
                    post.cover_picture_id = picture.id if picture else 0

                post.save()
                message = gettext('Stamp was succesfully saved')

                if remain:
                    return resp('admin/posts/edit.html', form=form, post=post, message=message)

                return resp(url_for('PostsView:get', id=post.id), redirect=True, message=message)
            else:
                return resp('admin/posts/edit.html', status=False, form=form, post=post,
                            message=gettext('Invalid submission, please check the message below'))
        else:
            form = PostForm(post)

        return resp('admin/posts/edit.html', form=form, post=post)
Example #28
0
def albumsAdd():
    form = AlbumForm()

    # 提交
    print(form.validate_on_submit())
    print(form.errors)
    if form.validate_on_submit():
        data = form.data
        print(data)

        # 图片处理
        images = request.values.get('images', '')
        imagesdata = images.split(';')
        imagesnew = ''
        print(images)
        print(imagesdata)
        album = Album(title=data["title"],
                      picture=data["picture"].replace('/temp/', '/images/'),
                      like_num=int(data["like_num"]),
                      sort=int(data["sort"]),
                      pictures=[])

        # if images:
        for index in range(len(imagesdata)):
            print(index)
            print(imagesdata[index])
            if imagesdata[index]:
                move_file(imagesdata[index])
                imagesnew = imagesdata[index].replace('/temp/', '/images/')
                album.pictures.append(Picture(path=imagesnew, sort=int(index)))

        db.session.add(album)
        db.session.commit()
        flash("success!", "ok")
        return redirect(url_for('admin.albums'))

    return render_template('admin/album/create.html', form=form)
Example #29
0
def seed_pictures():
    picture_1 = Picture(
        workout_id=1,
        url=
        'https://www.pixelstalk.net/wp-content/uploads/2016/12/Central-Park-HD-Wallpaper.jpg',
    )
    picture_2 = Picture(
        workout_id=1,
        url=
        'https://images.adsttc.com/media/images/5bc8/ad1e/f197/cc6b/2200/03c7/large_jpg/04_Alternative-Central-Park-4.jpg?1539878166',
    )
    picture_3 = Picture(
        workout_id=1,
        url=
        'https://upload.wikimedia.org/wikipedia/commons/thumb/1/13/Central_Park_-_The_Pond_%2848377220157%29.jpg/1200px-Central_Park_-_The_Pond_%2848377220157%29.jpg',
    )
    picture_4 = Picture(
        workout_id=2,
        url='http://www.parks.ca.gov/pages/417/images/wedding_rock.jpg',
    )
    picture_5 = Picture(
        workout_id=2,
        url=
        'https://www.visitcalifornia.com/sites/default/files/styles/welcome_image/public/VC_CoastalCamping_Module8_PatricksPoint_RM_643659404_1280x640.jpg',
    )
    picture_6 = Picture(
        workout_id=2,
        url=
        'https://i2.wp.com/rvplusyou.com/kb/wp-content/uploads/2017/02/Patricks-Point-6.jpg?ssl=1',
    )

    db.session.add(picture_1)
    db.session.add(picture_2)
    db.session.add(picture_3)
    db.session.add(picture_4)
    db.session.add(picture_5)
    db.session.add(picture_6)

    db.session.commit()
Example #30
0
 def profile_picture(self):
     if not self.profile_picture_id:
         return None
     from app.models import Picture
     return Picture.get_by_id(self.profile_picture_id)
Example #31
0
def seed_pictures():
    theed1 = Picture(img_url='https://skybnb.s3.amazonaws.com/theed5.jpg',
                     spot_id=3)
    theed2 = Picture(img_url='https://skybnb.s3.amazonaws.com/theed4.jpg',
                     spot_id=3)
    theed3 = Picture(img_url='https://skybnb.s3.amazonaws.com/theed3.jpg',
                     spot_id=3)
    theed4 = Picture(img_url='https://skybnb.s3.amazonaws.com/theed2.jpg',
                     spot_id=3)
    theed5 = Picture(img_url='https://skybnb.s3.amazonaws.com/theed1.jpg',
                     spot_id=3)

    db.session.add(theed1)
    db.session.add(theed2)
    db.session.add(theed3)
    db.session.add(theed4)
    db.session.add(theed5)

    yavin1 = Picture(img_url='https://skybnb.s3.amazonaws.com/temple1.jpg',
                     spot_id=1)
    yavin2 = Picture(img_url='https://skybnb.s3.amazonaws.com/temple2.jpg',
                     spot_id=1)
    yavin3 = Picture(img_url='https://skybnb.s3.amazonaws.com/temple3.jpg',
                     spot_id=1)
    yavin4 = Picture(img_url='https://skybnb.s3.amazonaws.com/temple4.jpg',
                     spot_id=1)
    yavin5 = Picture(img_url='https://skybnb.s3.amazonaws.com/temple5.jpg',
                     spot_id=1)

    db.session.add(yavin1)
    db.session.add(yavin2)
    db.session.add(yavin3)
    db.session.add(yavin4)
    db.session.add(yavin5)

    corouscant1 = Picture(
        img_url='https://skybnb.s3.amazonaws.com/corouscant1.jpg', spot_id=2)
    corouscant2 = Picture(
        img_url='https://skybnb.s3.amazonaws.com/corouscant2.jpg', spot_id=2)
    corouscant3 = Picture(
        img_url='https://skybnb.s3.amazonaws.com/corouscant3.jpg', spot_id=2)
    corouscant4 = Picture(
        img_url='https://skybnb.s3.amazonaws.com/corouscant4.jpg', spot_id=2)
    corouscant5 = Picture(
        img_url='https://skybnb.s3.amazonaws.com/corouscant5.jpg', spot_id=2)

    db.session.add(corouscant1)
    db.session.add(corouscant2)
    db.session.add(corouscant3)
    db.session.add(corouscant4)
    db.session.add(corouscant5)

    deathstar1 = Picture(
        img_url='https://skybnb.s3.amazonaws.com/deathstar1.jfif', spot_id=4)
    deathstar2 = Picture(
        img_url='https://skybnb.s3.amazonaws.com/deathstar2.jfif', spot_id=4)
    deathstar3 = Picture(
        img_url='https://skybnb.s3.amazonaws.com/deathstar3.jfif', spot_id=4)
    deathstar4 = Picture(
        img_url='https://skybnb.s3.amazonaws.com/deathstar4.jfif', spot_id=4)
    deathstar5 = Picture(
        img_url='https://skybnb.s3.amazonaws.com/deathstar5.jfif', spot_id=4)

    db.session.add(deathstar1)
    db.session.add(deathstar2)
    db.session.add(deathstar3)
    db.session.add(deathstar4)
    db.session.add(deathstar5)

    cloudcity1 = Picture(
        img_url='https://skybnb.s3.amazonaws.com/cloudcity1.jfif', spot_id=5)
    cloudcity2 = Picture(
        img_url='https://skybnb.s3.amazonaws.com/cloudcity2.jfif', spot_id=5)
    cloudcity3 = Picture(
        img_url='https://skybnb.s3.amazonaws.com/cloudcity3.jfif', spot_id=5)
    cloudcity4 = Picture(
        img_url='https://skybnb.s3.amazonaws.com/cloudcity4.jfif', spot_id=5)
    cloudcity5 = Picture(
        img_url='https://skybnb.s3.amazonaws.com/cloudcity5.jfif', spot_id=5)

    db.session.add(cloudcity1)
    db.session.add(cloudcity2)
    db.session.add(cloudcity3)
    db.session.add(cloudcity4)
    db.session.add(cloudcity5)

    yoda1 = Picture(img_url='https://skybnb.s3.amazonaws.com/yoda1.jfif',
                    spot_id=6)
    yoda2 = Picture(img_url='https://skybnb.s3.amazonaws.com/yoda2.jfif',
                    spot_id=6)
    yoda3 = Picture(img_url='https://skybnb.s3.amazonaws.com/yoda3.jfif',
                    spot_id=6)
    yoda4 = Picture(img_url='https://skybnb.s3.amazonaws.com/yoda4.jfif',
                    spot_id=6)
    yoda5 = Picture(img_url='https://skybnb.s3.amazonaws.com/yoda5.jfif',
                    spot_id=6)

    db.session.add(yoda1)
    db.session.add(yoda2)
    db.session.add(yoda3)
    db.session.add(yoda4)
    db.session.add(yoda5)

    chewy1 = Picture(img_url='https://skybnb.s3.amazonaws.com/chewy1.jfif',
                     spot_id=7)
    chewy2 = Picture(img_url='https://skybnb.s3.amazonaws.com/chewy2.jfif',
                     spot_id=7)
    chewy3 = Picture(img_url='https://skybnb.s3.amazonaws.com/chewy3.jfif',
                     spot_id=7)
    chewy4 = Picture(img_url='https://skybnb.s3.amazonaws.com/chewy4.jfif',
                     spot_id=7)
    chewy5 = Picture(img_url='https://skybnb.s3.amazonaws.com/chewy5.jfif',
                     spot_id=7)

    db.session.add(chewy1)
    db.session.add(chewy2)
    db.session.add(chewy3)
    db.session.add(chewy4)
    db.session.add(chewy5)

    luke1 = Picture(img_url='https://skybnb.s3.amazonaws.com/luke1.jfif',
                    spot_id=8)
    luke2 = Picture(img_url='https://skybnb.s3.amazonaws.com/luke2.jfif',
                    spot_id=8)
    luke3 = Picture(img_url='https://skybnb.s3.amazonaws.com/luke3.jfif',
                    spot_id=8)
    luke4 = Picture(img_url='https://skybnb.s3.amazonaws.com/luke4.jfif',
                    spot_id=8)
    luke5 = Picture(img_url='https://skybnb.s3.amazonaws.com/luke5.jfif',
                    spot_id=8)

    db.session.add(luke1)
    db.session.add(luke2)
    db.session.add(luke3)
    db.session.add(luke4)
    db.session.add(luke5)

    falcon1 = Picture(img_url='https://skybnb.s3.amazonaws.com/falcon1.jfif',
                      spot_id=9)
    falcon2 = Picture(img_url='https://skybnb.s3.amazonaws.com/falcon2.jfif',
                      spot_id=9)
    falcon3 = Picture(img_url='https://skybnb.s3.amazonaws.com/falcon3.jfif',
                      spot_id=9)
    falcon4 = Picture(img_url='https://skybnb.s3.amazonaws.com/falcon4.jfif',
                      spot_id=9)
    falcon5 = Picture(img_url='https://skybnb.s3.amazonaws.com/falcon5.jfif',
                      spot_id=9)

    db.session.add(falcon1)
    db.session.add(falcon2)
    db.session.add(falcon3)
    db.session.add(falcon4)
    db.session.add(falcon5)

    jabba1 = Picture(img_url='https://skybnb.s3.amazonaws.com/jabba1.jfif',
                     spot_id=10)
    jabba2 = Picture(img_url='https://skybnb.s3.amazonaws.com/jabba2.jfif',
                     spot_id=10)
    jabba3 = Picture(img_url='https://skybnb.s3.amazonaws.com/jabba3.jfif',
                     spot_id=10)
    jabba4 = Picture(img_url='https://skybnb.s3.amazonaws.com/jabba4.jfif',
                     spot_id=10)
    jabba5 = Picture(img_url='https://skybnb.s3.amazonaws.com/jabba5.jfif',
                     spot_id=10)

    db.session.add(jabba1)
    db.session.add(jabba2)
    db.session.add(jabba3)
    db.session.add(jabba4)
    db.session.add(jabba5)

    db.session.commit()
Example #32
0
    def put(self, id):
        post = Post.get_by_id(id)

        if post is None or not post.can_edit() or post.is_hidden:
            return render_view(url_for('PostsView:index'),
                               status=False,
                               redirect=True,
                               message=_('POST_NOT_FOUND'))

        form = PostForm(post=post)

        if form.is_submitted():
            try:
                if not form.validate():
                    raise Exception(_('ERROR_INVALID_SUBMISSION'))

                cover_picture_id = request.values.get('cover_picture_id', 0, int)
                is_draft = request.values.get('status', 0, int) == Post.POST_DRAFT
                remain = request.values.get('remain', False, bool)

                if post.cover_picture and cover_picture_id == 0:
                    # remove the picture, when user request its deletion
                    post.cover_picture.remove()

                form.populate_obj(post)

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

                if f:
                    if post.cover_picture:
                        post.cover_picture.remove()
                    picture = Picture.create()
                    picture.save_file(f, current_user)
                    post.cover_picture_id = picture.id if picture else 0

                if is_draft:
                    post.status = Post.POST_DRAFT
                else:
                    if post.save_count == 1 or post.created_at is None:
                        post.created_at = Post.current_date()
                        post.save_count = 1
                    post.status = Post.POST_PUBLIC
                    post.save_count += 1

                post.editor_version = 1
                post.save()

                Feed.clear_feed_cache()

                if post.is_draft:
                    message = _('POST_DRAFT_SAVE_SUCESS')
                else:
                    message = _('POST_PUBLIC_SAVE_SUCESS')

                if not remain:
                    return render_view(url_for('PostsView:get', id=post.id),
                                       redirect=True,
                                       message=message)
            except Exception as e:
                flash(e.message, 'error')

        return render_view('admin/posts/edit.html',
                           form=form,
                           post=post)
Example #33
0
 def profile_picture(self):
     if not self.profile_picture_id:
         return None
     from app.models import Picture
     return Picture.get_by_id(self.profile_picture_id)
Example #34
0
def updatePicture(photoUrl, workoutId):
    newPicture = Picture(url=photoUrl, workout_id=workoutId)

    db.session.add(newPicture)
    db.session.commit()
    return {"message": "ok"}
Example #35
0
    def form_valid(self, form):

        self.r = redis.StrictRedis(host='localhost', port=6379, db=0)
        self.socketid = self.request.POST['socketid-hidden']

        try:
            self.object = form.save()
            all_files = self.request.FILES.getlist('file')
            data = {'files': []}

        except:
            log_to_terminal(str(traceback.format_exc()), self.socketid)

        old_save_dir = os.path.dirname(conf.PIC_DIR)
        folder_name = str(shortuuid.uuid())
        save_dir = os.path.join(conf.PIC_DIR, folder_name)
        output_path = os.path.join(save_dir, 'results')
        # Make the new directory based on time
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)
            os.makedirs(os.path.join(save_dir, 'results'))

        if len(all_files) == 1:
            log_to_terminal(str('Downloading Image...'), self.socketid)
        else:
            log_to_terminal(str('Downloading Images...'), self.socketid)

        for file in all_files:
            try:
                a = Picture()
                tick = time.time()
                strtick = str(tick).replace('.', '_')
                fileName, fileExtension = os.path.splitext(file.name)
                file.name = fileName + strtick + fileExtension
                a.file.save(file.name, file)
                file.name = a.file.name
                imgfile = Image.open(os.path.join(old_save_dir, file.name))
                size = (500, 500)
                imgfile.thumbnail(size, Image.ANTIALIAS)
                imgfile.save(os.path.join(save_dir, file.name))
                thumbPath = os.path.join(folder_name, file.name)
                data['files'].append({
                    'url': conf.PIC_URL + thumbPath,
                    'name': file.name,
                    'type': 'image/png',
                    'thumbnailUrl': conf.PIC_URL + thumbPath,
                    'size': 0,
                })
            except:
                log_to_terminal(str(traceback.format_exc()), self.socketid)

        if len(all_files) == 1:
            log_to_terminal(str('Processing Image...'), self.socketid)
        else:
            log_to_terminal(str('Processing Images...'), self.socketid)

        time.sleep(.5)

        # This is for running it locally ie on Godel
        decaf_wrapper_local(save_dir, output_path, self.socketid,
                            os.path.join(conf.PIC_URL, folder_name))

        # This is for posting it on Redis - ie to Rosenblatt
        # classify_wrapper_redis(job_directory, socketid, result_folder)

        response = JSONResponse(data, {}, response_mimetype(self.request))
        response['Content-Disposition'] = 'inline; filename=files.json'
        return response
Example #36
0
    def form_valid(self, form):
        try:
            request_obj = Request()

            request_obj.socketid = self.request.POST['socketid-hidden']
            self.object = form.save()
            serialize(self.object)
            data = {'files': []}

            # List of Images: Url, Name, Type
            print data

            old_save_dir = os.path.dirname(conf.PIC_DIR)

            folder_name = str(shortuuid.uuid())
            save_dir = os.path.join(conf.PIC_DIR, folder_name)

            # Make the new directory based on time
            if not os.path.exists(save_dir):
                os.makedirs(save_dir)
                os.makedirs(os.path.join(save_dir, 'results'))

            all_files = self.request.FILES.getlist('file')

            for file in all_files:
                log_to_terminal(str('Saving file:' + file.name), request_obj.socketid)
                a = Picture()
                tick = time.time()
                strtick = str(tick).replace('.','_')
                fileName, fileExtension = os.path.splitext(file.name)
                file.name = fileName + strtick + fileExtension
                a.file.save(file.name, file)


                file.name = a.file.name

                # imgstr = base64.b64encode(file.read())
                # img_file = Image.open(BytesIO(base64.b64decode(imgstr)))
                # img_file.thumbnail(size, Image.ANTIALIAS)
                imgfile = Image.open(os.path.join(old_save_dir, file.name))
                size = (500,500)
                imgfile.thumbnail(size,Image.ANTIALIAS)

                imgfile.save(os.path.join(save_dir, file.name))
                thumbPath = os.path.join(folder_name, file.name)
                data['files'].append({
                    'url': conf.PIC_URL+thumbPath,
                    'name': file.name,
                    'type': 'image/png',
                    'thumbnailUrl': conf.PIC_URL+thumbPath,
                    'size': 0,
                })
            path, dirs, files = os.walk(save_dir).next()
            file_count = len(files)

            list = [os.path.join(conf.EXEC_DIR, 'stitch_full'), '--img', save_dir, '--verbose', '1', '--output',
                    os.path.join(save_dir, 'results/'), ]

            print list
            request_obj.run_executable(list, os.path.join(conf.PIC_URL, folder_name, 'results/result_stitch.jpg'))

            response = JSONResponse(data, mimetype=response_mimetype(self.request))
            response['Content-Disposition'] = 'inline; filename=files.json'

            return response
        except Exception as e:
            print traceback.format_exc()
            r.publish('chat', json.dumps({'message': str(traceback.format_exc()), 'socketid': str(self.socketid)}))
Example #37
0
def albumsEdit(id):
    album = Album.query.get_or_404(id)
    form = AlbumForm()

    if request.method == "GET":
        form.sort.data = album.sort
        form.title.data = album.title
        form.picture.data = album.picture
        form.like_num.data = album.like_num

    images = ''
    imagesarray = []
    for pictureitem in album.pictures:
        images = images + pictureitem.path + ';'
        imagesarray.append(pictureitem.path)

    print(imagesarray)
    # 提交
    print(form.validate_on_submit())
    print(form.errors)
    if form.validate_on_submit():
        data = form.data
        print(data)

        # 图片处理
        images = request.values.get('images', '')
        imagesdata = images.split(';')
        imagesnew = ''
        print(images)
        print(imagesdata)
        album.title = data["title"]
        album.picture = data["picture"].replace('/temp/', '/images/')
        album.like_num = data["like_num"]
        album.sort = data["sort"]
        album.pictures = []

        # 删除图片
        for oldimage in imagesarray:
            if oldimage not in imagesdata:
                print(oldimage)
                if oldimage and exists('app' + oldimage):
                    os.unlink('app' + oldimage)

        # if images:
        for index in range(len(imagesdata)):
            print(index)
            print(imagesdata[index])
            if imagesdata[index]:
                move_file(imagesdata[index])
                imagesnew = imagesdata[index].replace('/temp/', '/images/')
                album.pictures.append(Picture(path=imagesnew, sort=int(index)))

        db.session.add(album)
        db.session.commit()
        flash("success!", "ok")
        return redirect(url_for('admin.albums'))

    return render_template('admin/album/edit.html',
                           images=images,
                           form=form,
                           album=album)
Example #38
0
 def cover_picture(self):
     from app.models import Picture
     return Picture.get_by_id(self.cover_picture_id)
Example #39
0
 def cover_picture(self):
     from app.models import Picture
     return Picture.get_by_id(self.cover_picture_id)