Exemple #1
0
def upload_file():
    if request.method == 'POST':
        f = request.files['file']
        # 判断是否是图片
        name = f.filename
        suffix = name[name.find('.') + 1:]
        if suffix != 'bmp' and suffix != 'jpg' and suffix != 'jpeg' and suffix != 'png':
            return jsonify(code=500, message="the file is not pic")
        # 存入数据库
        # 重新生成名字
        randomCode = get_code()
        name = randomCode + '.' + suffix
        # 设置url
        url = request.url
        url = url[0:url.rfind('/') + 1] + 'pic/' + randomCode
        pic = Picture(name, url, 'Origin', -1)
        # 添加
        db.session.add(pic)
        db.session.commit()
        # 上传图片
        basepath = os.path.dirname(__file__)
        upload_path = os.path.join(basepath, 'myTest', secure_filename(name))
        f.save(upload_path)
        # 保存缩略图50x50
        url = convertToThumbnail(name, url, suffix)
        return jsonify(code=200, message="success upload", url=url, name=name)
Exemple #2
0
    def post(self):
        User_email = self.request.params.get('User_email')
        current_user = User.query(User.email == User_email).fetch(1)[0]
        activity = self.request.params.get('activity')
        upload = self.get_uploads()[0]
        if activity == 'FeedPad':
            content = self.request.params.get('content')
            latitude = self.request.params.get("latitude")
            longitude = self.request.params.get("longitude")

            newyeller = Yeller(author=User_email)
            newyeller.text = content
            newyeller.latitude = float(latitude)
            newyeller.longitude = float(longitude)
            newyeller.to_whom = 'public'
            newyeller.Anonymity = False
            newyeller.pictures.append(Picture(blob_key=upload.key()))
            yeller_key = newyeller.put()
            newyeller.key_id = str(newyeller.key.id())
            newyeller.put()
            current_user.yellers_owned.append(yeller_key)
        else:
            current_user.head_portrait = upload.key()

        current_user.put()
Exemple #3
0
def upload():
    if request.method == 'POST':
        f = request.files['file']
        basepath = os.path.dirname(__file__)  #当前文件路径
        upload_path = os.path.join(basepath, 'static/uploads/',
                                   secure_filename(f.filename))
        f.save(upload_path)
        print(upload_path)

        # vedio=Vedio(vediopath=basepath,vedio=f.save(upload_path))
        # db.session.add(vedio)
        # db.session.commit()
        #print(upload_path)
        # f.save(upload_path)
        #file=request.files['file'].read()

        classification, description, path = classify_all(upload_path)

        print('path分类为' + path)
        picture = Picture(path=path,
                          classification=classification,
                          description=description)

        db.session.add(picture)
        db.session.commit()

        return redirect(url_for('index'))
    else:
        #return render_template('uploadfile.html')
        return render_template('uploadfile.html')
Exemple #4
0
def handle_picture():
    """
    Create picture URL and retrieve all pictures
    """

    # POST request
    if request.method == 'POST':
        body = request.get_json()

        if body is None:
            raise APIException(
                "You need to specify the request body as a json object",
                status_code=400)
        if 'picture_url' not in body:
            raise APIException('You need to specify the picture URL',
                               status_code=400)

        address1 = Picture(picture_url=body['picture_url'],
                           photos_id=body['photos_id'])
        db.session.add(address1)
        db.session.commit()
        return "ok", 200

    # GET request
    if request.method == 'GET':
        all_pictures = Picture.query.all()
        all_pictures = list(map(lambda x: x.serialize(), all_pictures))
        return jsonify(all_pictures), 200

    return "Invalid Method", 404
Exemple #5
0
def from_json():
    """
    Load all content from dump.txt into Content.existing_content
    """
    dump_file = open('dump.txt', 'r')

    # read JSON string from dump_file
    json_string = dump_file.read()
    dump_file.close()

    # parse the JSON string into a list of dictionaries
    all_content_dicts = json.loads(json_string)

    # loop over list
    for d in all_content_dicts:
        if d['type'] == 'Article':
            # this automatically adds the Article or Picture to
            # Content.existing_content
            Article(d['year'], d['month'], d['day'], d['headline'],
                    d['content'], d['contributors'])

        elif d['type'] == 'Picture':
            Picture(d['year'], d['month'], d['day'], d['title'], d['caption'],
                    d['path'], d['contributors'])
        else:
            # pass quietly
            continue
Exemple #6
0
def question(request):

    # q = Picture.objects.get(id=randint(0, 14))
    r = randint(0, 14)
    while (r == StaticVar.last):
        r = randint(0, 14)
    StaticVar.last = r

    dataReader = csv.reader(open(os.path.join(BASE_DIR, 'pic.csv')),
                            delimiter=',',
                            quotechar='"')
    for row in dataReader:
        if int(row[0]) == r:
            q = Picture(id=row[0], name=row[1], sum=row[2], result=row[3])
            break

    path = '/static/pic/' + q.name + '.png'

    template = loader.get_template('j1.html')
    context = {
        'path': path,
        'n1': int(q.sum),
        'n2': int(q.sum) - int(q.result),
        'result': int(q.result)
    }

    return HttpResponse(template.render(context, request))
Exemple #7
0
def api_upload(request):
    if request.method == 'POST':
        picture = Picture()
        user = User.objects.get(email=request.POST['email'])
        picture.user = user
        form = UploadFileForm(request.POST, request.FILES, instance=picture)
        if form.is_valid():
            picture.picture = request.FILES['picture']
            if request.POST.has_key('gallery_id'):
                gallery = Gallery.objects.get(id=request.POST['gallery_id'],
                                              user=user)
                picture.gallery = gallery

            picture.picture.name = unidecode(picture.picture.name)
            picture.save()
            rotate_picture(picture)
            picture.update_thumb()

            if request.POST.has_key('description'):
                picture_description = PictureDescription(picture=picture)
                picture_description.text = request.POST['description']
                picture_description.save()

            response = {'status': 'OK'}
            response['data'] = serialize_picture(picture)
            return HttpResponse(json.dumps(response))

    return HttpResponse(content_200)
Exemple #8
0
def update(request):
    today = utils.getToday()
    prefix = settings.BASE_DIR + "/static/data/" + today
    if not os.path.exists(prefix):
        return HttpResponse("ERROR: today's pictures are not uploaded.")
    lunch9, lunch22, dinner9, dinner22 = utils.getFileLists()

    todayD = dateutil.parser.parse(today).date()
    pics = Picture.objects.filter(date__range=(todayD, todayD))
    cnt = 0
    for file in lunch9:
        if len(pics.filter(picName=file)) == 0:
            pic = Picture(picName=file,
                          mealTime="L",
                          floor=9,
                          like=0,
                          dislike=0)
            pic.save()
            cnt += 1
    for file in lunch22:
        if len(pics.filter(picName=file)) == 0:
            pic = Picture(picName=file,
                          mealTime="L",
                          floor=22,
                          like=0,
                          dislike=0)
            pic.save()
            cnt += 1
    for file in dinner9:
        if len(pics.filter(picName=file)) == 0:
            pic = Picture(picName=file,
                          mealTime="D",
                          floor=9,
                          like=0,
                          dislike=0)
            pic.save()
            cnt += 1
    for file in dinner22:
        if len(pics.filter(picName=file)) == 0:
            pic = Picture(picName=file,
                          mealTime="D",
                          floor=22,
                          like=0,
                          dislike=0)
            pic.save()
            cnt += 1
    return HttpResponse("INFO: updated %d pictures" % cnt)
Exemple #9
0
def upload(pic):
    if not pic:
        return 'No pic', 400
    filename = secure_filename(pic.filename)
    mimetype = pic.mimetype
    img = Picture(img=pic.read(), name=filename, mimetype=mimetype)
    db.session.add(img)
    db.session.commit()

    return img.id
Exemple #10
0
def upload_file():
    file = request.files['image']
    f = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
    # !!! add your custom code to check that the uploaded file is,
    # a valid image and not a malicious file
    file.save(f)
    upload_img_loc = Picture(ImageLocation=f)
    db.session.add(upload_img_loc)
    db.session.commit()
    return redirect(url_for("admin.index"))
Exemple #11
0
    def collect_data(self):
        self.device.shell("screencap -p /sdcard/screen.png")
        self.device.pull("/sdcard/screen.png", self.main_image_path)

        with Image.open(self.main_image_path) as main_image:

            main_image_crop = main_image.crop((
                0,
                int(self.screen_resolution_height *
                    (self.crops['main_image'][0])),
                self.screen_resolution_width,
                int(self.screen_resolution_height *
                    (self.crops['main_image'][1])),
            ))
            main_image_crop_jpg = main_image_crop.convert('RGB')
            main_image_crop_jpg.save(self.crop_image_path)

        # scroll down to bio # TINDER SPECIFIC, move to child class
        self.get_bio_page_ready()
        self.device.shell("screencap -p /sdcard/screen.png")
        self.device.pull("/sdcard/screen.png", self.tmp_image_path)
        with Image.open(self.tmp_image_path) as tmp_image:
            raw_crop = tmp_image.crop((
                0,
                int(self.screen_resolution_height * (self.crops['raw'][0])),
                self.screen_resolution_width,
                int(self.screen_resolution_height * (self.crops['raw'][1])),
            ))

            raw_crop.save(self.raw_image_path)
        # convert main_image
        raw_text = pytesseract.image_to_string(Image.open(self.raw_image_path))
        # logger.debug(raw_text)
        clean_data = self.cleanse_data(raw_text)
        logger.debug(clean_data)
        os.remove(self.main_image_path)
        os.remove(self.raw_image_path)
        os.remove(self.tmp_image_path)
        # initing db row for Person
        person = Person(
            gender='female',
            raw=clean_data,
            result=True,
            source_name=self.source_name,
        )
        session.add(person)
        session.commit()

        # adding row for picture
        picture = Picture(
            person_id=person.id,
            _uuid=str(self._uuid),
        )
        session.add(picture)
        session.commit()
Exemple #12
0
def picture():
    p = {"picture": "img/1.jpg"}
    if request.method == "POST":
        file = request.files.get("photo")
        file_name = file.filename
        file_path = "img/%s" % file_name
        save_path = os.path.join(STATICFILES_DIR, file_path)
        file.save(save_path)
        p = Picture()
        p.picture = file_path
        p.save()
    return render_template("picture.html", **locals())
Exemple #13
0
def picture():
    p={'picture':'img/photo.jpg'}
    if request.method == 'POST':
        file=request.files.get('photo')
        file_name=file.filename
        file_path='img/%s'%file_name
        save_path=os.path.join(STATICFILES_DIR,file_path)
        file.save(save_path)
        p=Picture()
        p.picture=file_path
        p.save()
    return render_template('picture.html',**locals())
Exemple #14
0
def create_picture(session, orga, name="testPicture"):
    picture = Picture(orga)
    picture.name = name
    picture.filename = name
    picture.radiotext = name
    picture.radiolink = name
    picture.image_url_prefix = name
    session.add(picture)
    session.commit()
    Channel.query.filter_by(id=1).first().default_picture_id = picture.id
    Channel.query.filter_by(id=2).first().default_picture_id = picture.id
    session.commit()
    time.sleep(config.SPI_GENERATION_INTERVAL * 3)
    return picture
Exemple #15
0
def convertToThumbnail(name, url, suffix):
    # 缩略图的保存
    path = os.path.join(os.getcwd(), 'myTest', name)
    img = Image.open(path)
    img = img.resize((50, 50), Image.BILINEAR)
    newname = name[0:name.find('.')] + '_50x50.' + suffix
    newpath = os.path.join(os.getcwd(), 'myTest', newname)
    img.save(newpath)
    # 缩略图记录的保存
    url = url + '_50x50'
    orig_pic = Picture.query.filter_by(name=name).first()
    pic = Picture(newname, url, 'Thumbnail_50x50', orig_pic.id)
    db.session.add(pic)
    db.session.commit()
    return url
Exemple #16
0
def upload():
    form = UploadForm()
    allCat = []
    allCat = info.query.all()
    print(allCat)

    if form.validate_on_submit():
        filename = secure_filename(form.file.data.filename)
        print('file', filename)
        form.file.data.save('static/uploads/' + filename)
        newPic = Picture(link='../static/uploads/' + filename)
        db.session.add(newPic)
        db.session.commit()
        return redirect(url_for('upload'))
    return render_template('upload.html', form=form, allCat=allCat)
Exemple #17
0
def create_picture(request):
	token = getToken(request.META)
	user = getUser(token)

	if(not user):
		return Response(status=status.HTTP_403_FORBIDDEN)
	serialized = PictureSerializer(data=request.DATA)

	image = request.FILES['image']
	if(serialized.is_valid):
		picture = Picture()
		picture.title = serialized.initial_data['title']
		picture.image.save(image.name, image)
		picture.save()

		return Response(status=status.HTTP_201_CREATED)
	else:
		return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #18
0
def index(request):
    pictures = Picture.objects.all()
    toppeople = picture_people.objects.all().select_related(
        "picture").order_by("person")
    toptags = picture_tag.objects.all().select_related("picture").order_by(
        "tag")
    toptags = toptags[:4]
    newTop = []
    names = []
    for item in toppeople:
        print(item.person)
        print(item.person not in newTop)
        if item.person != "" and item.person not in names:
            newTop.append(item)
            names.append(item.person)
    toppeople = newTop[:4]
    print(toppeople)
    print(toptags)
    if request.method == 'POST':
        fileupload = request.FILES.get('fileupload')
        tags = request.POST.get('tags')
        people = request.POST.get('people')
        location = request.POST.get('location')
        newPic = Picture(picture=fileupload, location=location)
        newPic.save()
        print(fileupload)
        indTags = tags.split(", ")
        indPeople = people.split(", ")
        print(indTags)
        print(indPeople)
        print(fileupload)
        for item in indTags:
            print(item)
            pic_tag = picture_tag(picture=newPic, tag=item)
            pic_tag.save()
        for item in indPeople:
            pic_people = picture_people(picture=newPic, person=item)
            pic_people.save()
        return redirect(index)
    return render(request, 'pictures/index.html', {
        'pictures': pictures,
        'toppeople': toppeople,
        'toptags': toptags,
    })
Exemple #19
0
def upload_picture(request):
    """Upload picture view.
    """
    if request.method == 'POST':
        picture = Picture()
        picture.user = request.user
        form = UploadFileForm(request.POST, request.FILES, instance=picture)
        response = {}

        if form.is_valid():
            picture.picture = request.FILES['picture']
            picture.picture.name = unidecode(picture.picture.name)
            picture.save()

            ### nasty error at 3:45 AM ;/
            try:
                rotate_picture(picture)
                picture.update_thumb()
                picture.save()
            except:
                import sys, traceback
                traceback.print_exc(file=sys.stdout)
                picture.delete()
                response[
                    'status'] = 'UPLOAD ERROR. PUT HELMET ON AND EVACUATE!!!'
                response = json.dumps(response)
                return HttpResponse(response)
            response['url'] = picture.picture_thumb.url
            response['id'] = picture.id
            response = json.dumps(response)
        else:
            response = "Failed to upload"
    else:
        if request.GET.has_key('gallery_id'):
            preffered_gallery = int(request.GET['gallery_id'])
        else:
            preffered_gallery = None
        galleries = Gallery.objects.filter(user=request.user)
        return render(request, "upload.html", {
            'galleries': galleries,
            'preffered_gallery': preffered_gallery
        })
    return HttpResponse(response)
Exemple #20
0
def upload_file(request, object_id):
    """
		takes every files sent by the request upload and insert them inside the database.
	"""
    a = get_object_or_404(Album, pk=object_id)

    if request.method == 'POST':
        for file in request.FILES.getlist('file'):
            p = Picture(picture=file, album=a)
            p.save()

        return render_to_response('success/url.html',
                                  RequestContext(request, {}))

    else:
        form = UploadFileForm()

    context = {'form': form, 'album': a}

    return render_to_response('admin/albums/upload.html',
                              RequestContext(request, context))
Exemple #21
0
def add_picture(request):
    if request.method == 'GET':
        return render(request, 'PicShare/uploadform.html', {
            'form': PhotoUploadForm,
            'user': request.user
        })

    if request.method == 'POST':
        form = PhotoUploadForm(request.POST, request.FILES)
        if form.is_valid():
            owner = request.user
            pic = Picture(owner=owner,
                          caption=form.data['caption'],
                          description=form.data['description'],
                          image=request.FILES['image'])
            pic.save()
            return HttpResponseRedirect(reverse('profile'))
        else:
            return render(request, 'PicShare/uploadform.html', {
                'form': form,
                'user': request.user
            })
Exemple #22
0
    def post(self):
        # 获取图片对象
        imgae = self.request.files["pic"][0]
        if imgae:
            img_name = imgae.filename
            img_data = imgae.body
            # 保存图片文件
            with open("./statics/images/" + img_name, "wb") as f:
                f.write(img_data)

            # 把图片保存进数据库
            # 连接数据库
            engine = create_engine(
                'postgresql://*****:*****@localhost:5432/exampledb', echo=True)
            # 创建会话对象,用来操作数据库
            Session = sessionmaker(bind=engine)
            session = Session()
            img_data = base64.b64encode(img_data)
            pic = Picture(name=img_name, imge=img_data)
            session.add(pic)
            session.commit()
        self.render("pic_show.html", name=img_name)
Exemple #23
0
def upscaling():
    data = json.loads(request.get_data(as_text=True))
    times = data['times']
    picname = data['picname']
    # 判断是否重复
    timespic = picname[0:picname.find('.')] + times + "x_"
    picture = Picture.query.filter(Picture.name.like(timespic + "%")).first()
    if picture != None:
        return jsonify(code=400, message="The picture has been processed")
    # 路径
    path = os.path.join(os.getcwd(), FLAGS.sample_dir, picname)
    print(path)
    # 名字
    picture = Picture.query.filter_by(name=picname).first()
    picname = picname[0:picname.find('.')] + times + 'x_.' + picture.suffix
    # url
    url = picture.url
    url = url[0:url.rfind('/')] + '/' + picname[0:picname.find('_') + 1]
    # 放大图片
    with tf.Session() as sess:
        srcnn = SRCNN(sess,
                      checkpoint_dir=FLAGS.checkpoint_dir,
                      sample_dir=FLAGS.sample_dir)
        srcnn.upscaling(picname, path, FLAGS, int(times))
    # 保存数据库
    action = 'Upscale_' + times + 'X'
    newpic = Picture(picname, url, action, picture.id)
    db.session.add(newpic)
    db.session.flush()
    db.session.commit()

    return jsonify(code=200,
                   message="success upscaling",
                   name=picname,
                   id=newpic.id,
                   url=url,
                   action=action)
def create_picture_object(filename):

    image = load_picture(filename)
    picture = Picture(image)

    return picture
    def post(self):
        upload_image = Config.UPLOAD_IMAGE
        if 'file' not in request.files:
            return {'status': '400', 'message': 'No file found'}, 400

        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(str(uuid.uuid4()))

            ok, upload_image = mkdir_upload_image(upload_image)
            if not ok:
                return {'status': '500', 'message': 'System error'}, 500

            file_path = os.path.join(upload_image, filename)
            try:
                file.save(file_path)
                if magic.from_file(file_path,
                                   mime=True) in Config.CONTENT_TYPE:
                    user = User.query.filter(User.email == g.email).first()
                    picture = Picture.query.join(User).filter(
                        Picture.user_id == user.id).first()
                    if not picture:
                        picture = Picture(name_picture=filename,
                                          user_id=user.id)
                        db.session.add(picture)
                        db.session.commit()
                        return {
                            'status':
                            '200',
                            'message':
                            "upload image {} success".format(
                                picture.name_picture)
                        }, 200

                    os.remove(os.path.join(upload_image, picture.name_picture))
                    shutil.rmtree(
                        os.path.join(
                            os.path.join(Config.EDIT_IMAGE,
                                         picture.name_picture)))
                    db.session.delete(picture)
                    db.session.commit()

                    picture = Picture(name_picture=filename, user_id=user.id)
                    db.session.add(picture)
                    db.session.commit()

                    return {
                        'status':
                        '200',
                        'message':
                        "upload image {} success".format(picture.name_picture)
                    }, 200

                else:
                    os.remove(file_path)
                    return {
                        'status':
                        '404',
                        'message':
                        "Please upload file format ({})".format(
                            (', ').join(Config.ALLOWED_EXTENSIONS))
                    }, 404

            except Exception as e:
                return {
                    'status': '500',
                    'message': 'System error, unable to upload file'
                }, 500

            else:
                return {
                    'status':
                    '404',
                    'message':
                    "Please upload file format ({})".format(
                        (', ').join(Config.ALLOWED_EXTENSIONS))
                }, 404
        else:
            return {
                'status':
                '404',
                'message':
                "Please upload file format ({})".format(
                    (', ').join(Config.ALLOWED_EXTENSIONS))
            }, 404
Exemple #26
0
def upload():
    # Calculate the total size of upload folder and download folder
    # Cleanup the folders if the size exceeds the limits
    upload_folder_size = size_calculate(app.config['UPLOAD_FOLDER'])
    download_folder_size = size_calculate(app.config['DOWNLOAD_FOLDER'])
    if upload_folder_size > UPLOAD_FOLDER_LIMIT:
        directory_cleanup(app.config['UPLOAD_FOLDER'])
    if download_folder_size > DOWNLOAD_FOLDER_LIMIT:
        directory_cleanup(app.config['DOWNLOAD_FOLDER'])

    if request.method == 'POST':
        # Get the name of the uploaded file
        file = request.files['file']
        # Check if the file is one of the allowed types/extensions
        if file and allowed_file(file.filename):
            # Make the filename safe, remove unsupported chars
            filename = secure_filename(file.filename)
            # Move the file form the temporal folder to the upload folder we setup
            file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            file.save(file_path)
            # Get the resize_mode the user requested
            resize_mode = request.form['resize_mode']
            width = request.form['width']
            height = request.form['width']
            fx = request.form['fx']
            fy = request.form['fx']
            # User-defined parameter dictionary
            params = {
                'resize_mode': resize_mode,
                'width': width,
                'height': width,
                'fx': fx,
                'fy': fx
            }

            # Save parameters to cookies
            session['filename'] = filename
            session['params'] = params
            # Read image
            file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            img = cv2.imread(file_path)
            if params['resize_mode'] == 'ratio_mode':
                fx = float(params['fx'])
                fy = float(params['fx'])
                res = resizer_ratio(img, fx=fx, fy=fx)
            else:  # defined_mode
                width = int(params['width'])
                height = int(params['width'])
                res = resizer_defined(img, width=width, height=width)

            # Save resized image
            filename_resized_prefix = filename.rsplit('.', 1)[0]
            filename_resized = filename_resized_prefix + '_resized.png'
            session['filename_resized'] = filename_resized

            dst_path = os.path.join(app.config['DOWNLOAD_FOLDER'],
                                    filename_resized)

            # Save resized image
            cv2.imwrite(filename=dst_path, img=res)

            # Original image file size in byte
            filesize_original = os.path.getsize(file_path)
            # Turn byte to KB
            filesize_original = int(filesize_original / 1024)

            # Resized image file size in byte
            filesize_resized = os.path.getsize(dst_path)
            # Turn byte to KB
            filesize_resized = int(filesize_resized / 1024)
            #add to db
            newpicture = Picture(imagename=filename,
                                 originalsize=filesize_original,
                                 newsize=filesize_resized)
            db.session.add(newpicture)
            db.session.commit()
            # Redirect the user to the resize_image route
            return redirect(url_for('resize_image'))
Exemple #27
0
def radiovis_gallery_edit(request, id):
    """Edit a channel."""

    object = None
    errors = []

    plugitapi = PlugItAPI(config.API_URL)
    orga = plugitapi.get_orga(
        request.args.get('ebuio_orgapk') or request.form.get('ebuio_orgapk'))

    sp = None
    if orga.codops:
        sp = ServiceProvider.query.filter_by(codops=orga.codops).order_by(
            ServiceProvider.codops).first()

    if id != '-':
        object = Picture.query.filter_by(orga=int(
            request.args.get('ebuio_orgapk')
            or request.form.get('ebuio_orgapk')),
                                         id=int(id)).first()

    if request.method == 'POST':

        if not object:
            object = Picture(int(request.form.get('ebuio_orgapk')))

        if sp:
            object.image_url_prefix = sp.image_url_prefix

        object.name = request.form.get('name')
        object.radiotext = request.form.get('radiotext')
        object.radiolink = request.form.get('radiolink')

        def add_unique_postfix(fn):
            """__source__ = 'http://code.activestate.com/recipes/577200-make-unique-file-name/'"""
            if not os.path.exists(fn):
                return fn

            path, name = os.path.split(fn)
            name, ext = os.path.splitext(name)

            make_fn = lambda i: os.path.join(path, '%s(%d)%s' % (name, i, ext))

            for i in xrange(2, sys.maxint):
                uni_fn = make_fn(i)
                if not os.path.exists(uni_fn):
                    return uni_fn

            return None

        def unique_filename(fn):

            path, name = os.path.split(fn)
            name, ext = os.path.splitext(name)

            make_fn = lambda i: os.path.join(path, '%s%s' %
                                             (str(uuid.uuid4()), ext))

            for i in xrange(2, sys.maxint):
                uni_fn = make_fn(i)
                if not os.path.exists(uni_fn):
                    return uni_fn

            return None

        new_file = False
        if request.files:
            new_file = True
            file = request.files['file']
            if file:
                filename = secure_filename(file.filename)
                full_path = unique_filename('media/uploads/radiovis/gallery/' +
                                            filename)
                path, name = os.path.split(full_path)
                file.save(full_path)
                if object.filename:
                    try:
                        os.unlink(object.filename)
                    except:
                        pass
                object.filename = name

            # Check errors
            if object.name == '':
                errors.append("Please set a name")

            if object.radiotext == '':
                errors.append("Please set a text")

            if object.radiolink == '':
                errors.append("Please set a link")

            if object.filename == '' or object.filename is None:
                errors.append("Please upload an image")
            else:

                if imghdr.what(full_path) not in ['jpeg', 'png']:
                    errors.append("Image is not an png or jpeg image")
                    os.unlink(full_path)
                    object.filename = None
                else:
                    im = Image.open(full_path)
                    if im.size != (320, 240):
                        errors.append("Image must be 320x240")
                        del im
                        os.unlink(full_path)
                        object.filename = None

        pieces = urlparse.urlparse(object.radiolink)

        if pieces.scheme not in ['http', 'https', 'ftp']:
            errors.append("The link is not valid")

        # If no errors, save
        if not errors:

            # Upload to s3
            if new_file:
                try:
                    if config.STANDALONE:
                        send_image_to_mock_api({name: open(full_path, 'rb')})
                    else:
                        awsutils.upload_public_image(sp, name, full_path)
                except:
                    pass
            # TODO Clean up old images on S3

            if not object.id:
                db.session.add(object)

            db.session.commit()

            try:
                # Remove local copy
                os.unlink(full_path)
            except:
                pass

            return PlugItRedirect('radiovis/gallery/?saved=yes')

        try:
            # Remove local copy
            os.unlink(full_path)
        except:
            pass

    if object:
        object = object.json

    return {'object': object, 'errors': errors}
Exemple #28
0
def radiovis_gallery_edit(request, id):
    """Edit a channel."""

    object = None
    errors = []

    if id != '-':
        object = Picture.query.filter_by(orga=int(
            request.args.get('ebuio_orgapk')
            or request.form.get('ebuio_orgapk')),
                                         id=int(id)).first()

    if request.method == 'POST':

        if not object:
            object = Picture(int(request.form.get('ebuio_orgapk')))

        object.name = request.form.get('name')
        object.radiotext = request.form.get('radiotext')
        object.radiolink = request.form.get('radiolink')

        def add_unique_postfix(fn):
            """__source__ = 'http://code.activestate.com/recipes/577200-make-unique-file-name/'"""
            if not os.path.exists(fn):
                return fn

            path, name = os.path.split(fn)
            name, ext = os.path.splitext(name)

            make_fn = lambda i: os.path.join(path, '%s(%d)%s' % (name, i, ext))

            for i in xrange(2, sys.maxint):
                uni_fn = make_fn(i)
                if not os.path.exists(uni_fn):
                    return uni_fn

            return None

        file = request.files['file']
        if file:
            filename = secure_filename(file.filename)
            full_path = add_unique_postfix('media/uploads/radiovis/gallery/' +
                                           filename)
            file.save(full_path)
            if object.filename:
                try:
                    os.unlink(object.filename)
                except:
                    pass
            object.filename = full_path

        # Check errors
        if object.name == '':
            errors.append("Please set a name")

        if object.radiotext == '':
            errors.append("Please set a text")

        if object.radiolink == '':
            errors.append("Please set a link")

        if object.filename == '' or object.filename is None:
            errors.append("Please upload an image")
        else:

            if imghdr.what(object.filename) not in ['jpeg', 'png']:
                errors.append("Image is not an png or jpeg image")
                os.unlink(object.filename)
                object.filename = None
            else:
                im = Image.open(object.filename)
                if im.size != (320, 240):
                    errors.append("Image must be 320x240")
                    del im
                    os.unlink(object.filename)
                    object.filename = None

        pieces = urlparse.urlparse(object.radiolink)

        if not pieces.scheme in ['http', 'https', 'ftp']:
            errors.append("The link is not valid")

        # If no errors, save
        if not errors:

            if not object.id:
                db.session.add(object)

            db.session.commit()

            return PlugItRedirect('radiovis/gallery/?saved=yes')

    if object:
        object = object.json

    return {'object': object, 'errors': errors}
def submit_on_the_road():
    try:
        form = OTRSubmissionForm()
        pictures_to_parse = [p for p in form.pictures if p.upload.data]
    except:
        flash("Something went wrong. Make sure that all of your pictures "
                "are smaller than %sMB." % app.config['MAX_CONTENT_MB']
        )
        log_generic_except()
        return redirect(url_for('submit_on_the_road'))
    slice_index = len(pictures_to_parse) if pictures_to_parse else 1
    if request.method == 'POST' and not pictures_to_parse:
        flash("You need to submit some pictures!")
        return render_template('submit_on_the_road.html', 
                form=form, config=app.config, slice_index=slice_index)        
    if form.validate_on_submit():
        if not app.config['LOCAL']:
            if ip_throttled(Submission, request.remote_addr):
                flash("Your IP address has been used to submit several posts recently. "
                        "Please try again in an hour or so."
                )
                return redirect(url_for('submit_on_the_road'))
        submission = Submission(
                nym=form.nym.data,
                email=form.email.data,
                introduction=form.introduction.data,
                status='pending',
                datetime_submitted=datetime.datetime.now(pytz.timezone('US/Eastern')),
                ip_address=request.remote_addr
        )
        submission_prefix = str(uuid.uuid1())
        for i, picture_form in enumerate(pictures_to_parse):
            if not picture_form.validate(request):
                for error in picture_form.errors: app.logger.error(error)
                return render_template('submit_on_the_road.html', 
                        form=form, config=app.config, slice_index=slice_index)
            picture_file = picture_form.upload.data
            extension = secure_filename(picture_form.upload.data.filename).split('.')[-1]
            extension = '.' + extension if extension else ''
            file_name = submission_prefix + str(i) + extension
            file_path = os.path.join(
                    app.config['APPLICATION_WORKING_DIRECTORY'], 
                    'static/submissions',
                    file_name
            )
            try:
                picture_file.save(file_path)
            except:
                app.logger.error("Picture upload error")
                log_generic_except()
                flash("Something went wrong uploading picture #%s, %s" % (
                        str(i+1), form.title.data)
                )
                continue
            submission.pictures.append(Picture(
                    title=picture_form.title.data,
                    date_taken=picture_form.date_taken.data,
                    place_taken=picture_form.place_taken.data,
                    picture_description=picture_form.picture_description.data,
                    file_location=file_path
            ))
        db.session.add(submission)
        db.session.commit()
        return redirect(url_for('thanks_on_the_road'))
    if form.errors:
        app.logger.error(form.errors)
        app.logger.error("Nym error?: %s, %s" % (form.nym.data, form.email.data))
    return render_template(
            'submit_on_the_road.html', form=form, config=app.config, 
            slice_index=slice_index
    )
Exemple #30
0
def add_image():
    """ Route for uploading a new image """

    form = UploadForm()

    if form.validate_on_submit():
        f = form.photo.data
        filename = secure_filename(f.filename)

        f.save(os.path.join(filename))

        image = Image.open(f'{filename}')

        # Only images taken by phone or camera will have exif info,
        # others would throw an AttricuteError because exif doesn't exist.
        # The try/except block catches the AttributeError
        # therefore all picture type can be uploaded.

        try:
            exif = {}
            for tag, value in image._getexif().items():
                if tag in TAGS:
                    exif[TAGS[tag]] = value

            picture = Picture(photographer=form.photographer.data,
                              caption=form.caption.data,
                              date_time=exif.get('DateTime'),
                              camera_make=exif.get('Make'),
                              camera_model=exif.get('Model'),
                              iso=exif.get('ISOSpeedRatings'),
                              flash=exif.get('Flash'),
                              pic_width=exif.get('ExifImageWidth'),
                              pic_height=exif.get('ExifImageHeight'),
                              image_url=IMAGE_URL,
                              file_name=filename)
        except AttributeError:
            picture = Picture(photographer=form.photographer.data,
                              caption=form.caption.data,
                              date_time=None,
                              camera_make=None,
                              camera_model=None,
                              iso=None,
                              flash=None,
                              pic_width=None,
                              pic_height=None,
                              image_url=IMAGE_URL,
                              file_name=filename)

        db.session.add(picture)
        db.session.commit()

        # upload the image to aws
        upload_file_bucket = BUCKET
        upload_file_key = picture.id
        client.upload_file(filename,
                           upload_file_bucket,
                           str(upload_file_key),
                           ExtraArgs={'ACL': 'public-read'})
        os.remove(filename)
        return redirect(f'/images/{picture.id}')
    else:
        return render_template("add_picture.html", form=form)