Exemple #1
0
def changepic(id):
	user= User.query.filter_by(id=id).one()
	form = UploadForm()
	print form.validate_on_submit()
	if form.validate_on_submit():
		filename = images.save(request.files['upload'])
		url = images.url(filename)
		user.profile_url = url
		user.profile_filename= filename
		db.session.add(user)
		db.session.commit()
		flash('Profile Picture Changed.')
		return redirect(url_for('myprofile',id=id))
	return render_template('changepic.html',user=user, form=form)
Exemple #2
0
def upload():
    formupload = UploadForm()
    if formupload.validate_on_submit():
        filename = photos.save(formupload.file.data)
        file_url = photos.url(filename)
        return redirect(file_url)
    return render_template("upload.html", formupload=formupload)
Exemple #3
0
def upload_file():
	form=UploadForm()
	if form.validate_on_submit():
		if form.file.data is None or form.file.data.filename =='':
			flash('No selected file.')
			return redirect(url_for('upload'))
		file=request.files['file']
		if file and allowed_file(file.filename):
			filename = secure_filename(file.filename)
			filetype=filename.rsplit('.',1)[1].lower()
			directory=app.config['UPLOAD_FOLDER'] + hashlib.md5(current_user.username).hexdigest()
			if not os.path.exists(directory):
				os.mkdir(directory)

			file.save(os.path.join(directory,filename))
			filehash=None
			with open(os.path.join(directory,filename)) as f:
				filehash = hashlib.md5(f.read(400)).hexdigest()
				f.close()

			os.rename(os.path.join(directory,filename),os.path.join(directory,filehash+'.'+filetype))
			f=File(file_name=filename,file_hash=filehash,file_type=filetype,uploader=current_user.get_id())

			db.session.add(f)
			db.session.commit()
			current_user.set_hashed_name()
			db.session.add(current_user)
			db.session.commit()

			if(form.prof_pic.data is True):
				current_user.set_profile_image(f.id)
				db.session.add(current_user)
				db.session.commit()
			return redirect(url_for('user',username=current_user.username))
	return render_template('upload.html',title='Upload',form=form)
Exemple #4
0
def sports_players():

    plat = platform.system()
    if plat == 'Windows':
        pathlib.PosixPath = pathlib.WindowsPath

    learner_path = Path()

    learn = load_learner(learner_path / 'export.pkl')

    form = UploadForm()

    direct = 'static/uploads'
    for file in os.scandir(direct):
        os.remove(file.path)

    if form.validate_on_submit():
        filename = secure_filename(form.file.data.filename)
        form.file.data.save(f'static/uploads/{filename}')
        img = PILImage.create(f'static/uploads/{filename}')
        pred_class, pred_idx, outputs = learn.predict(img)
        flash(f'This picture is of a {pred_class} player', 'success')
        flash(f"Probability: {outputs[pred_idx]:.04f}", 'info')
        return render_template('sports-players.html', form=form, user_image=f"static/uploads/{filename}")

    return render_template('sports-players.html', form=form, user_image="static/default_img/question.jpg")
Exemple #5
0
def upload():
    if not session.get('logged_in'):
        abort(401)

    # Instantiate your form class

    uploadform = UploadForm()

    if request.method == 'POST' and uploadform.validate_on_submit():

        upload = uploadform.upload.data  # we could also use request.files['photo']

        filename = secure_filename(upload.filename)
        upload.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

        flash('File Saved', 'success')
        return render_template('home.html')
        # return render_template('upload.html', form=uploadform)

    else:
        flash_errors(uploadform)
        return render_template('upload.html', form=uploadform)

    # Validate file upload on submit
    if request.method == 'POST':
        # Get file data and save to your uploads folder

        flash('File Saved', 'success')
        return render_template('home.html')

    return render_template('upload.html')
Exemple #6
0
def upload():
    if g.user.files.count() >=100:
        flash("You can't upload more than 100 files")
        return redirect(url_for('index'))
    form=UploadForm()
    if form.validate_on_submit():
        file=form.file.data
        filename = secure_filename(file.filename)
        #create sha1 of file
        url=sha1(file.read()).hexdigest()
        f=File.query.filter_by(url=url).first()
        if f is None:
            file.seek(0)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], url))
        else:
            if f.own==g.user:
                flash('File already exist in your storage(%s)'%f.name)
            else:
                flash("File already exist(%s in %s's storage)"%(f.name,f.own.nickname))
        newfile=File(url=url,timestamp=datetime.datetime.utcnow(),name=filename,own=g.user)
        db.session.add(newfile)
        db.session.commit()
        return redirect(url_for('index'))

    return render_template('upload.html',form=form)
Exemple #7
0
def uploadFiles():
    form = UploadForm()
    if form.validate_on_submit():
        #ingest form data
        grower_name = form.grower_name.data
        retail = form.retail_loc.data
        division = form.division_drop.data
        #process config file
        grower, crop_year = ingestCSV(form.upl_csv.data, division, retail,
                                      grower_name)
        #save files to static
        for f in request.files.getlist('upl_imgs'):
            filepath = os.path.join(app.config['UPLOADED_IMAGES_DEST'],
                                    f.filename)
            if os.path.exists(filepath):
                os.remove(filepath)
            images.save(f)
        flash("Files accepted and added to database.")
        return redirect(
            url_for('growerRecord',
                    division=grower.division,
                    grower_id=grower.id,
                    year=crop_year,
                    current_year=current_year))
    return render_template('upload.html', form=form, current_year=current_year)
Exemple #8
0
def upload():
    uploadForm = UploadForm()
    # Instantiate your form class
    if request.method == "GET":
        return render_template("upload.html", form=uploadForm)
    
    #checking if user is logged in
    if not session.get('logged_in'):
        abort(401)
        
    # Validate file upload on submit
    if request.method == 'POST' and uploadForm.validate_on_submit():
        # Get file data from the form
        photo =  uploadForm.photo.data
        
        #securing the filename before saving
        filename = secure_filename(photo.filename)
        
        #save the file to the upload folder
        photo.save(os.path.join(
            app.config['UPLOAD_FOLDER'], filename
        ))
        
        #flash success message
        flash('File Saved', 'success')
        return redirect(url_for('home'))

    return render_template('upload.html')
Exemple #9
0
def editCustomerCodes(customer_id=None):

    form = UploadForm()

    if form.validate_on_submit() and form.filename.data:
        file = form.filename.data
        filename = 'cust_' + str(customer_id) + '.csv'
        file.save(os.path.join(CUSTOMER_CODES_PATH, filename))
        try:
            parse_csv(os.path.join(CUSTOMER_CODES_PATH, filename))
            flash(gettext('CSV uploaded and processed sucessfully.'))
        except:
            flash(gettext('Upload unsuccessful! File could not be parsed!'))
        redirect('/settings/editcustomercodes')

    def_file_path = getCustomerCodesDefinitionFiles(customer_id)
    if def_file_path:
        try:
            def_file_data = parse_csv(def_file_path[0])
        except:
            def_file_data = []
    else:
        def_file_data = []
    customer = Customer.query.get(customer_id)

    return render_template('/settings/editcustomercodes.html',
                           title=gettext("Edit Customer Codes"),
                           customer=customer,
                           def_file_data=def_file_data,
                           form=form)
Exemple #10
0
def test_three():
    log('test3 loaded')
    form = UploadForm()
    log('form good')
    if request.method == 'POST':
        log('in post for test3')
        if form.validate_on_submit():
            log('form is valid')
            uploaded_file = request.files.get('file')
            log('uploaded file')
            filename = request.form.get('filename')
            log('got filename')
            content_type = uploaded_file.content_type
            log('got content type')
            if not uploaded_file:
                return 'FILE NOT UPLOADED'
            gcs_client = storage.Client()
            log('got storage client')
            storage_bucket = gcs_client.get_bucket('f_storage')
            log('got f_storage bucket')
            blob = storage_bucket.blob(uploaded_file.filename)
            log('got blob')
            blob.upload_from_string(uploaded_file.read(),
                                    content_type=content_type)
            log('uploaded from string')
            url = blob.public_url
            log('got url: ' + url)
            return 'OK'
        return 'OK - in POST'
    file = '/test3.html'
    title = 'Test3 - images'
    h1 = 'Test3 - images'
    return render_template(file, title=title, h1=h1, form=form)
Exemple #11
0
def upload():
    form = UploadForm()
    if request.method == 'POST' and form.validate_on_submit():
        target = os.path.join('./app/static', 'uploads/')
        print(target)

        if not os.path.isdir(target):
            os.mkdir(target)

        f = request.files['file']

        filename = secure_filename(f.filename)
        f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        description = request.form['description']
        result = {
            'Message': 'File Upload Successful',
            'Filename': filename,
            'Description': description
        }

        # flash('File Saved', 'success')
        return jsonify(result)

        errors = form_errors(form)
    return jsonify(errors=errors)
Exemple #12
0
def spellcheck():
    form = UploadForm()
    if form.validate_on_submit():
        f = form.upload.data
        filename = secure_filename(f.filename)
        errors = spellchecker(filename)
        encoded = base64.b64encode(f.read())
        encoded = FileStorage(BytesIO(encoded), filename)
        file_path = os.path.join(app.config['UPLOAD_FOLDER'],
                                 session['username'])
        errors_file_path = os.path.join(app.config['UPLOAD_FOLDER'],
                                        session['username'], 'errors')
        if os.path.exists(file_path):
            files = os.walk(file_path).__next__()[2]
            if len(files) >= 5:
                # this will DELETE the user's folder from storage
                shutil.rmtree(file_path)
                flash('Storage limit exceeded. Your storage has reset.')
        if not os.path.exists(file_path):
            os.makedirs(file_path)
        if not os.path.exists(errors_file_path):
            os.makedirs(errors_file_path)
        encoded.save(os.path.join(file_path, filename))  # save file
        with open(errors_file_path + '/' + filename, 'w') as errors_file:
            errors_file.write(json.dumps(errors))
        return redirect(url_for('uploads'))

    return render_template('spellcheck.html', form=form)
Exemple #13
0
def upload1():
    form = UploadForm()
    if form.validate_on_submit():
        if form.image.data:
            image_data = request.FILES[form.image.name].read()
            open(os.path.join(UPLOAD_FOLDER, form.image.data), 'w').write(image_data)
    return render_template('web/upload1.html', form=form)
Exemple #14
0
def upload():

    # load in UploadForm with existing data to variable form
    form = UploadForm()

    # check if information submitted is valid
    if form.validate_on_submit():

        # take data from form/file and set into variables
        name = form.name.data
        description = form.description.data
        game = form.game.data
        file = request.files['inputFile']
        image = request.files['imageFile']

        # create a new mod with the given data and add it to the database

        new_mod = Mods(user_id=current_user.id,
                       username=current_user.username,
                       game=game,
                       name=name,
                       description=description,
                       data='uploads/' + file.filename,
                       image='uploads/' + image.filename)

        db.session.add(new_mod)

        db.session.commit()

        file.save(os.path.join("static/uploads", file.filename))
        image.save(os.path.join("static/uploads", image.filename))

        return render_template('upload.html', form=form)

    return render_template('upload.html', form=form)
Exemple #15
0
def profile():
    form = UploadForm()

    if request.method == 'POST':
        # Get validated data from form
        if form.validate_on_submit():
            
            firstname = form.firstname.data  
            lastname = form.lastname.data
            gender = form.gender.data
            email = form.email.data
            location = form.location.data
            biography = form.biography.data
            dateCreated = str(datetime.date.today())
            
            profilepic = form.profilePic.data
            imagename = secure_filename(profilepic.filename)
            profilepic.save(os.path.join(app.config['UPLOAD_FOLDER'],imagename))
        
            user = UserProfile(firstname, lastname, gender, email, location, biography, imagename, dateCreated)
            db.session.add(user)
            db.session.commit()
            
           
            flash('User successfully added')
            return redirect(url_for('profile'))
    flash_errors(form)
    return render_template('profile.html', form=form)
Exemple #16
0
def upload():
    form = UploadForm()
    if form.validate_on_submit():
        try:
            name = form.name.data
            filename = images.save(form.image.data, folder=unicode(g.user.id))

            #Checks if Image is new or exists before commit changes
            image = Image.query.filter_by(name = form.name.data).first()
	    if image is None:
                image = Image(name = name, filename = filename, uid=g.user.id)
                message = "%r image uploaded." % name
            else:
                old_file = image.filename
                image.filename = filename
                message = "%r image changed." % name

            db.session.add(image)
            db.session.commit()

            flash(message)
            return redirect(url_for('index'))
        except UploadNotAllowed:
            flash("Not allowed to upload image")
    else:
        filename = None

    return render_template('upload.html',
        form = form,
        filename = filename)
Exemple #17
0
def upload():

    photofiles = UploadForm()

    if photofiles.validate_on_submit() and request.method == 'POST':

        description = photofiles.description.data
        photo = photofiles.photo.data

        filename = secure_filename(photo.filename)
        photo.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        photo = photo.filename
        upload = {
            "message": "File Upload Successful",
            "filename": photo,
            "description": description
        }
        flash('File Saved', 'success')
        return jsonify(upload)

    else:

        err = form_errors(photofiles)
        error = {"errors": err}
        return jsonify(error)
Exemple #18
0
def get_main_data():
    """
    First page after index page. Takes in restaurant, date, guest number and photo receipt data.
    After form submission, redirects to the "people_details" page that gets the names and phones for each guest
    """
    upload_form = UploadForm()

    if upload_form.validate_on_submit():
        restaurant = upload_form.restaurant.data
        date = upload_form.date.data
        num_friends = int(upload_form.num_friends.data)

        if upload_form.receipt_image.data:

            image = imgproc.loadImage(upload_form.receipt_image.data)

            Params.FOODS_DF = get_food_items_using_PyTorch(
                image, "./end2end/weights/craft_mlt_25k.pth",
                "./end2end/weights/craft_refiner_CTW1500.pth")

            # when form is validated and submitted, go to entering individual people's details
            return redirect(
                url_for('people_details',
                        restaurant=restaurant,
                        date=date,
                        count=num_friends))
    return render_template('get_main_data.html',
                           title="Upload Data",
                           upload_form=upload_form)
Exemple #19
0
def upload():

    if not session.get('logged_in'):
        abort(401)
    uploadform = UploadForm()
    # Instantiate your form class

    # Validate file upload on submit
    if request.method == 'POST':
        # Get file data and save to your uploads folder
        if uploadform.validate_on_submit():
            print uploadform.csrf_token

            photo = uploadform.photo.data
            description = uploadform.description.data

            filename = secure_filename(photo.filename)
            photo.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

            flash('File Saved', 'success')
            return redirect(
                url_for('home', filename=filename, description=description))
        else:
            print uploadform.errors.items()
            flash('File not Saved', 'error')
    return render_template('upload.html', form=uploadform)
Exemple #20
0
def upload():
    form = UploadForm()
    if form.validate_on_submit():
        group_id = str(form.group.data)
        name = str(form.name.data)
        date = str(form.date.data)
        print(group_id, name, date)
        make_today_dirs(date, int(group_id))

        f = form.screenshot_1.data
        # filename = random_filename(f.filename)
        ext = os.path.splitext(f.filename)[1]
        filename = os.path.join(group_id, date, name,
                                f'{date}-{name}-{1}' + ext)
        f.save(os.path.join(app.config['UPLOAD_PATH'], filename))

        f = form.screenshot_2.data
        # filename = random_filename(f.filename)
        ext = os.path.splitext(f.filename)[1]
        filename = os.path.join(group_id, date, name,
                                f'{date}-{name}-{2}' + ext)
        f.save(os.path.join(app.config['UPLOAD_PATH'], filename))

        f = form.screenshot_3.data
        # filename = random_filename(f.filename)
        ext = os.path.splitext(f.filename)[1]
        filename = os.path.join(group_id, date, name,
                                f'{date}-{name}-{3}' + ext)
        f.save(os.path.join(app.config['UPLOAD_PATH'], filename))

        flash('Upload success.')
        session['filenames'] = [filename]
        return redirect(url_for('success'))
    return render_template('upload.html', form=form)
Exemple #21
0
def index():
    form = UploadForm()

    if request.method == 'POST':
        if form.validate_on_submit():
            support = form.support.data
            confidence = form.confidence.data
            f = form.transactions_file.data

            filename = secure_filename(f.filename)
            data = f.readlines()

            output_filename, decode_errs = process_file(
                data, filename, support, confidence)

            file_exists = os.path.isfile(
                os.path.join(app.config['DOWNLOAD_FOLDER'], output_filename))

            if not file_exists:
                return render_template('/error.html',
                                       form=form,
                                       errmsg="nofile")

            return render_template('/results.html',
                                   form=form,
                                   result=output_filename,
                                   decode_errs=decode_errs)

    return render_template('/index.html', form=form)
Exemple #22
0
def index():

    form = UploadForm()
    if request.method == 'POST' and form.validate_on_submit():

        bucket_name = app.config['BUCKET_NAME']
        key = uuid.uuid4()
        filename = str(key) + '.ics'
        fullpath = '/' + bucket_name + '/' + filename

        upfile = request.files['csv_file']

        try:
            ics_file = converter.convert(upfile)

        except (ContentError, HeadersError, DatetimeFormatError) as error:
            flash(error, 'danger')
            return render_template('index.html', form=form, links=base_links,
                                   links_title=links_title)

        else:
            mtype = 'text/calendar'
            with gcs.open(fullpath, 'w', content_type=mtype) as w:
                w.write(ics_file)

            session['key'] = key
            return redirect(url_for('success'))

    for field, errors in form.errors.items():
        for error in errors:
            msg = "Whups! {}".format(error)
            flash(msg)
    return render_template('index.html', form=form, links=base_links,
                           links_title=links_title)
Exemple #23
0
def upload():
    form = UploadForm()
    if form.validate_on_submit():
        upload_result = cloudinary_upload(form.file.data)
        session['source_url'] = upload_result['secure_url']
        flash('Your poster has been successfully uploaded!')
        return redirect(url_for('new_poster'))
    return render_template('index.html', form=NewLinkForm(), upload_form=form)
Exemple #24
0
def upload():
    if not current_user.is_admin():
        return 'Not Authorized', 500
    form = UploadForm(request.form)
    if form.validate_on_submit():
        #save and process it
        pass
    return render_template('upload.html', form=form)
def add_image():
    form = UploadForm()
    if form.validate_on_submit():
        user_id = current_user.user_id
        result = Images.query.order_by(Images.image_id.desc()).first()
        result.description = form.description.data
        db.session.commit()
        return redirect(vs_url_for('gallery'))
    return render_template('add_image.html', form=form)
Exemple #26
0
def upload_image():
    form = UploadForm()
    if form.validate_on_submit():
        f = form.photo.data
        ext = os.path.splitext(f.filename)[1]
        filename = uuid.uuid4().hex + ext
        f.save(os.path.join(app.root_path, 'upload', filename))
        return redirect(url_for('show_image', filename=filename))
    return render_template("upload.html", form=form)
Exemple #27
0
def upload():
    form=UploadForm()
    if request.method == 'POST' and form.validate_on_submit():
        description = request.form['description'] 
        photo = request.files['photo'] 
        filename = secure_filename(photo.filename)
        photo.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
        return jsonify({'message': 'File upload successful', 'file': photo, 'description': description})
    else:
        return jsonify({'errors':form_errors(form)})
Exemple #28
0
def gallery():
    form = UploadForm()
    images = os.listdir('static/img')
    context = {'images': images, 'form': form}
    if form.validate_on_submit():
        img = Image.open(BytesIO(request.files.get('image').read()))
        filename = request.files.get('image').filename
        img.save(f'static/img/{filename}')
        return redirect('/gallery')
    return render_template('gallery.html', **context)
Exemple #29
0
def upload():
	form=UploadForm()
	if form.validate_on_submit():
		file=save_file(form.file.data,"static")
		song=Song(title=form.title.data,artist=form.artist.data,album=form.album.data,file=file,user=current_user)
		db.session.add(song)
		db.session.commit()
		flash("Song uploaded successfully","success")
		return redirect(url_for('my_uploads'))
	return render_template("upload.html",title="Upload Song",form=form)
def upload():
    """Render the website's about page."""
    form = UploadForm()
    if request.method == 'POST' and form.validate_on_submit():
        data_file = request.files['file']
        file_name = secure_filename(data_file.filename)
        data_file.save(os.path.join(UPLOAD_FOLDER, file_name))
        save_form_data(request.form, file_name)
        return redirect(url_for('thanks'))
    return render_template('upload.html', form=form)
Exemple #31
0
def upload():
    form = UploadForm()
    if form.validate_on_submit():
        f = form.photo.data
        filename = random_filename(f.filename)
        f.save(os.path.join(app.config['UPLOAD_PATH'], filename))
        flash('Upload success.')
        session['filenames'] = [filename]
        return redirect(url_for('show_images'))
    return render_template('upload.html', form=form)
Exemple #32
0
def upload():
    form = UploadForm()
    if form.validate_on_submit():
        f = form.photo.data
        filename = random_filename(f.filename)
        f.save(os.path.join(app.config['UPLOAD_PATH'], filename))
        flash('Upload success.')
        session['filenames'] = [filename]
        return redirect(url_for('show_images'))
    return render_template('upload.html', form=form)
Exemple #33
0
def upload():
    """Render the website's about page."""
    form = UploadForm()
    if request.method == 'POST' and form.validate_on_submit():
        data_file = request.files['file']
        file_name = secure_filename(data_file.filename)
        data_file.save(os.path.join(UPLOAD_FOLDER, file_name))
        save_form_data(request.form, file_name)
        return redirect(url_for('thanks'))
    return render_template('upload.html', form=form)
Exemple #34
0
def index():
    form = UploadForm()
    if form.validate_on_submit():
        var = form.image.data.stream.read()
        lat = form.latitude.data
        lon = form.longitude.data
        if lat == '' or lon == '':
            flash('Enable location access')
            return redirect('/')
        lang = 'en'
        if 12.41 <= float(lat) <= 19.07 and 77 <= float(lon) <= 84.40:
            lang = 'te'
        elif 8.5 <= float(lat) <= 13.35 and 76.15 <= float(lon) <= 80.20:
            lang = 'ta'
        elif 11.3 <= float(lat) <= 18.3 and 74 <= float(lon) <= 78.3:
            lang = 'ka'
        image = Image.open(io.BytesIO(var))
        img = np.array(image)
        reader = Reader(['en', 'hi'])
        bounds = reader.readtext(img)
        temp = []
        if lang != 'en':
            reader1 = Reader([lang])
            bounds1 = reader1.readtext(img)
            for i in range(len(bounds)):
                bounds[i] = list(bounds[i])
                bounds[i][1] = (bounds1[i][1]
                                if bounds[i][2] < bounds1[i][2]
                                else bounds[i][1])
                tem = False
                for x in bounds[i][1]:
                    if ord(x) > 255:
                        tem = True
                if tem:
                    temp.append(TextBlob(bounds[i][1]).detect_language()) if len(bounds[i][1]) >= 3 else temp.append('')
                else:
                    temp.append('en')
        image_with_bounds = draw_boxes(image, bounds)
        buffered = io.BytesIO()
        image_with_bounds.save(buffered, format="png")
        b64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
        text_trans = []
        app.logger.info(bounds)
        app.logger.info(temp)
        for i in range(len(temp)):
            if temp[i] in ['te', 'hi', 'ta', 'ka']:
                translator = Translator(from_lang=temp[i] + '-IN', to_lang='en')
                translation = translator.translate(bounds[i][1])
                text_trans.append(translation.upper())
            else:
                text_trans.append(bounds[i][1])
        text = "\n".join([i[1] for i in bounds])
        text_trans = '\n'.join(text_trans)
        return render_template('result.html', image="data:image/png;base64," + b64, text=text, text_trans=text_trans)
    return render_template('index.html', form=form)
Exemple #35
0
def upload():
    form=UploadForm()
    if request.method == 'POST' and form.validate_on_submit():
        description=form.description.data
        photo=form.photo.data
        filename = secure_filename(photo.filename)
        photo.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        photo=photo.filename
        return jsonify({"message":"File Upload Successful","file":photo,"description":description})
    else:
        return jsonify({"errors":form_errors(form)})
Exemple #36
0
def dashboard():
    form = UploadForm()

    if form.validate_on_submit():
        pass

    return render_template('upload_load.html',
                           title='Dashboard',
                           heading='CyAnalytics',
                           form=form,
                           logged_in=True)
Exemple #37
0
def dataImport():
    form = UploadForm()
    colnames = get_colnames(Product)
    form.colnames = colnames
    if form.validate_on_submit() and form.filename.data:
        filename = secure_filename(form.filename.data.filename)
        file = request.files[form.filename.name].read()
        open(os.path.join(CSV_PATH, filename), 'w').write(file)
        result = process_csv(os.path.join(CSV_PATH, filename), Product, colnames)
        flash(result)
        redirect('/settings/dataimport')
    return render_template('/settings/dataimport.html',
                           title=gettext("Data Import"),
                           form=form)
Exemple #38
0
def upload_file_form(game_slug, release_id):
    # release_id = request.args.get('release', None)
    # file_id = request.args.get('file', None)
    # if file_id: # edit/re-upload
        # file = db.session.query(File).filter(File.id==file_id).one()
        # form = UploadForm()
        # form.edit.data = "True"
    # else:
    form = UploadForm()
    form.edit.data = ""
    if form.validate_on_submit():
        uploaded_file = form.uploaded_file.data
        save_file(uploaded_file, release_id)
        flash('File uploaded!')
    return render_template('upload_files.html', form=form, upload_url=game_slug + '/filesupload/'+release_id, site_data=site_data(), navigation=return_navigation())
Exemple #39
0
def upload():	
	form = UploadForm()
	if form.validate_on_submit():
		flash('TXT registered')
		db = Db()
		filename = secure_filename(form.upload.data.filename)
		form.upload.data.save(os.path.join(app.config['UPLOADED_TEXT_DEST'], filename))
		SQL =  'INSERT INTO text (author_name, file_location, description, title, text_type, pub_date) VALUES (%s, %s, %s, %s, %s, %s);'
		data = (form.author.data, "uploads/" + form.upload.data.filename, form.description.data, form.title.data, form.textType.data, form.pub_date.data)
		db.execute(SQL, data)
		return redirect(url_for('pick'))

	else:
		filename = None
	return render_template('upload.html', form=form, filename=filename)
Exemple #40
0
def upload():
		user = g.user
		form = UploadForm()
		if form.validate_on_submit():
				video = Video(link = form.link.data, 
				comment = form.comment.data, 
				timestamp = datetime.datetime.utcnow(),
				author = user)
				db.session.add(video)
				db.session.commit()
				flash("Upload successful!")
				return redirect(url_for('index'))
		return render_template('upload.html',
		title = 'Upload',
		form = form,
		user = user)
Exemple #41
0
def upload_file_old(game_slug):
    release_id = request.args.get('release', None)
    file_id = request.args.get('file', None)

    if file_id:
        file = db.session.query(File).filter(File.id==file_id).one()
        form = UploadForm()
        form.edit.data = "True"
    else:
        form = UploadForm()
        form.edit.data = ""

    if form.validate_on_submit():
        uploaded_file = form.uploaded_file.data
        if uploaded_file: # and allowed_file(uploaded_file.filename):
            filename = secure_filename(uploaded_file.filename)
            if os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'], filename)):
                fileName, fileExtension = os.path.splitext(filename)
                filename = fileName + '-' + time.strftime("%Y%m%d-%H%M%S") + fileExtension
            uploaded_file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

        if form.edit.data:
            if uploaded_file:
                file.filename=filename

            file.description=form.description.data
        else:
            if uploaded_file:
#                release = Release.query.filter(Release.id==release_id).one()
                file = File(release_id=release_id, filename=filename, description=form.description.data)
                db.session.add(file)
        if uploaded_file or form.edit.data:
            file.approved = False;
            db.session.commit()
            if not form.edit.data:
                form.description.data=None
        if form.edit.data:
            flash('File changed!')
        else:
            if uploaded_file:
                flash('File uploaded!')
    else:
        if form.edit.data:
            form.description.data=file.description

    return render_template('add_file.html', form=form, site_data=site_data(), navigation=return_navigation())
Exemple #42
0
def ui_upload():
    form = UploadForm()
    message = ""
    error = ""
    if form.validate_on_submit():
        artist = None
        if form.artist.data != "":
            artist = form.artist.data
        album = None
        if form.album.data != "":
            album = form.album.data
        track = None
        if form.track.data != "":
            track = form.track.data
        current_user.radio.add_download("youtube-dl", form.url.data, artist, album, track)
        message = "Dodano link do kolejki pobierania"

    return render_template('upload.html', form=form, message=message, error=error)
Exemple #43
0
def uploads():
    
    form = UploadForm()
    
    
    if form.validate_on_submit():
        description = form.description.data
        photoData = form.photo.data
        filename = secure_filename(photodata.filename)
        
        
        try:
            
            potoData.save(os.path.join(app.config["UPLOAD_FOLDER"], filename))
            return jsonify(message="201", filename=filename, description=description)
            except Exception as e:
                print e:
                    
            return jsonify(errors=["internal Error"])
Exemple #44
0
def uploadXL():

    times =  ["08-09[am]","09-10[am]","10-11[am]","11-12[am]","12-01[pm]","01-02[pm]","02-03[pm]","03-04[pm]","04-05[pm]","05-06[pm]","06-07[pm]","07-08[pm]","08-09[pm]"]

    timesDict =  {
        "8:00AM":"08-09[am]",
        "9:00AM":"09-10[am]",
        "10:00AM":"10-11[am]",
        "11:00AM":"11-12[am]",
        "12:00PM":"12-01[pm]",
        "1:00PM":"01-02[pm]",
        "2:00PM":"02-03[pm]",
        "3:00PM":"03-04[pm]",
        "4:00PM":"04-05[pm]",
        "5:00PM":"05-06[pm]",
        "6:00PM":"06-07[pm]",
        "7:00PM":"07-08[pm]",
        "8:00PM":"08-09[pm]"
        }


    form = UploadForm()
    title="Upload File"
    filename = ""
    file=None
    if form.validate_on_submit():
        file = request.files['filexl']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            filename = str(uuid.uuid4()) + filename
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        else:
            flash('Only CSV Files Allowed', category='danger')
            return redirect(url_for('uploadXL'))

        #filepath = "/home/dundee/Computing2.csv"
        filepath = app.config['UPLOAD_FOLDER']+"/"+filename
        f = open(filepath,'rb')

        readerDict = csv.DictReader(f, delimiter='\t', dialect='excel')
        #This count variable is to just decide when to delete entries for the semester
        count=0
        for key in readerDict:
            entry_time=""
            entry_room=""
            entry_sem=""
            entry_type=""
            entry_initial=""
            entry_course=""
            entry_type=""

            entry_room = Room.query.filter_by(RoomNameSRU=key['ROOM_DESC']).first()
            if entry_room:
                entry_room = entry_room.RoomId
            else:
                entry_room="_MIA"

            entry_sem=key['SEM_OFFERED'][4]
            if entry_sem:
                entry_sem=entry_sem
                if count == 0:
                    delEntryClone(entry_sem)
            else:
                entry_sem="_MIA"

            entry_initial = User.query.filter_by(uwiId=key['STAFF_ID']).first()
            if entry_initial:
                entry_initial=entry_initial.userInitial
            else:
                entry_initial="_MIA"

            entry_type = CourseType.query.filter_by(CourseTypeDesc=key['SCHED_TYPE']).first()
            if entry_type:
                entry_type= entry_type.CourseType
            else:
                entry_type="_MIA"

            entry_day=key['DAY']
            if entry_day:
                entry_day=entry_day
            else:
                entry_day="MIA"

            entry_course=key['SUBJ_CODE']+key['CRSE_NUMB']
            if entry_course:
                entry_course=entry_course
            else:
                entry_course="_MIA"

            entry_time=key['START_TIME'].strip().replace(' ','')
            if entry_time:
                entry_time=timesDict[entry_time]
            else:
                entry_time="_MIA"


            timeDiff=timeDifference(key['START_TIME'].strip(),key['END_TIME'].strip())
            print timeDiff

            indx = times.index(entry_time)
            for i in range(timeDiff):
                entry = EntryClone(
                    EntryDay=entry_day,
                    EntryTime=times[indx+i],
                    RoomId=entry_room,
                    SemesterId=entry_sem,
                    CourseCode=entry_course,
                    CourseType=entry_type,
                    userInitial=entry_initial
            )
                db.session.add(entry)
                db.session.commit()


            count = count + 1

        flash('File Successfully Uploaded', category='success')
        return redirect(url_for('timetable',sem=entry_sem))

    return render_template('upload.html',title=title,form=form)
Exemple #45
0
def upload():
    if session.get('is_login') is None or not session.get('is_login'):
        flash(u'请先登录!', 'danger')
        return redirect(url_for('login'))
    upload_form = UploadForm()

    # print dir(upload_form.file_upload.data)
    # print dir(upload_form.file_upload.data.stream)
    # print upload_form.file_upload.data.stream.read()
    if upload_form.validate_on_submit():
        # check access key and secret key and image limit
        current_user_id = session.get('user_id')
        user_info = UsersInfo.query.filter_by(user_id=current_user_id).first()
        if user_info is None or not user_info:
            return redirect(url_for('e500'))
        if user_info.qiniu_access_key == '' or user_info.qiniu_secret_key == '' or \
           user_info.qiniu_bucket_name == '' or user_info.qiniu_domain == '' or \
           user_info.qiniu_access_key is None or user_info.qiniu_secret_key is None or \
           user_info.qiniu_bucket_name is None or user_info.qiniu_domain is None:
            # flash(u'您还未设置七牛密钥信息,请去个人中心中设置', 'danger')
            return redirect(url_for('main_view'))
        images = Images.query.filter_by(upload_user_id=current_user_id, use_default_config=0).all()
        max_upload_count = WebConfig.query.filter_by(config_name='default_upload_count').first()
        if len(images) >= int(max_upload_count.config_value):
            # flash(u'您已上传的图片数量到达系统限制,
            # 使用自己的七牛密钥后可以上传更多图片,请到个人中心设置。', 'danger')
            return redirect(url_for('main_view'))
        upload_filename = upload_form.file_upload.data.filename
        ext = os.path.splitext(upload_filename)[1]

        # save file in tmp directory
        local_filename = random_str(32) + ext
        with open('tmp/'+local_filename, 'wb') as ff:
            ff.write(upload_form.file_upload.data.stream.read())

        # init qiniu
        current_user_id = session.get('user_id')
        users_info = UsersInfo.query.filter_by(user_id=current_user_id).first()
        access_key = users_info.qiniu_access_key
        secret_key = users_info.qiniu_secret_key
        bucket_name = users_info.qiniu_bucket_name
        domain = users_info.qiniu_domain

        q = Auth(access_key, secret_key)
        remote_filename = local_filename
        upload_token = q.upload_token(bucket_name, remote_filename, 3600)
        local_file = 'tmp/' + local_filename
        ret, info = put_file(upload_token, remote_filename, local_file)

        url = 'http://' + domain + '/' + ret['key']
        # url2 = request.host_url + session.get('username') + '/' + local_filename
        # print '[*]', url
        # insert into image table
        title = upload_form.title.data
        description = upload_form.description.data
        qiniu_have_account = session.get('qiniu_have_account')
        if qiniu_have_account is None:
            flash(u'系统错误!请稍后再试!', 'danger')
            return redirect(url_for('main_view'))
        # use_default_config = 0: use system config
        # use_default_config = 1: use user's config
        images = Images(image_id='', title=title, description=description, filename=local_filename,
                        link=url, upload_time=str(int(time.time())), upload_user_id=current_user_id,
                        use_default_config=qiniu_have_account)
        db.session.add(images)
        db.session.commit()

        user_dir = 'tmp/' + session.get('username') + '/'
        if not os.path.exists(user_dir):
            os.mkdir(user_dir)
        thumbnail_file = user_dir + local_filename
        im = Image.open(local_file)
        im.thumbnail((128, 128))
        im.save(thumbnail_file)

        if os.path.exists(local_file):
            os.remove(local_file)

        flash(u'上传成功!链接为 '+url+',您可在个人中心中查看已上传的全部图片。', 'success')
        return redirect(url_for('main_view'))
    return redirect(url_for('main_view'))
class UploadFormProcessor(FormProcessor):
    def __init__(self, *args, **kwargs):
        super(UploadFormProcessor, self).__init__(*args, **kwargs)
        self.select_form()

    def select_form(self):
        if self.page.form:
            self.form = self.page.form
            self.form = self.process_form()
        else:
            self.get_form()
            if request.is_xhr:
                self.rendered_form = self.form
            else:
                self.form_template = self.get_form_template()
                self.rendered_form = self.render_form()

    def get_form(self):
        if 'key' in request.args:
            if request.endpoint == "photos":
                self.page.assets['new_photo'] = request.args['key']
                self.form = PostForm()
                self.form.photo.data = self.page.assets['new_photo']
                self.template = "post_form.html"
            else:
                self.page.assets['new_photo'] = request.args['key']
                self.form = EditForm()
                self.form.photo.data = self.page.assets['new_photo']
                self.form.about_me.data = g.user.about_me
                self.form.nickname.data = g.user.nickname
                self.template = "update_photo.html"
        else:
            if request.is_xhr:
                if request.endpoint == "photos":
                    self.form = UploadForm(prefix="").s3_upload_form()
            else:
                if request.endpoint == "photos":
                    key = "user-images/" + str(g.user.id) + "/" + str(uuid4()) + ".jpeg"
                    message = "Select New Photo"
                    redirect_url = request.base_url
                else:
                    key = "user-images/" + str(g.user.id) + "/profile_image/" + str(uuid4()) + ".jpeg"
                    message = "Change Profile Picture"
                    redirect_url = request.base_url
                self.form = UploadForm(key=key, message=message, redirect_url=redirect_url).s3_upload_form()

    def process_form(self):
        if self.form.validate_on_submit():
            photo_name = self.form.photo.data
            post = Post(body=self.form.body.data, timestamp=datetime.utcnow(), category=self.form.category.data,
                        author=g.user, photo=photo_name, writing_type="entry")

            db.session.add(post)
            db.session.commit()

            exif_stats = ExifStats()
            exif_stats.post_id = post.id
            exif_data = json.loads(json.dumps(request.json['exifTags']))
            for key, value in exif_data.iteritems():
                if key == "DateTime" or key == "DateTimeOriginal":
                    datetimeobject = datetime.strptime(value, '%Y:%m:%d %H:%M:%S')
                    setattr(exif_stats, key, datetimeobject)
                else:
                    setattr(exif_stats, key, value)

            db.session.add(exif_stats)
            db.session.commit()
            if request.is_xhr:
                response = post.json_view()
                response['savedsuccess'] = True
                self.rendered_form = response
            else:
                self.form = None
                self.rendered_form = None
        else:
            if request.is_xhr:
                self.form.errors['iserror'] = True
                return json.dumps(self.form.errors)
            else:
                self.template = "post_form.html"
                self.form_template = self.get_form_template()
                self.rendered_form = self.render_form()