Exemplo n.º 1
0
def edit_blog_post(post_id):

    form = BlogPostForm()
    form.category.choices = ([(cat.category, cat.category)
                              for cat in BlogCategory.query.all()])

    post = BlogPost.query.filter_by(id=int(post_id)).first_or_404()

    # update post data
    if form.validate_on_submit() and form.submit.data:

        post.title = form.post_title.data
        post.body = form.post_body.data
        post.last_edit = datetime.utcnow()
        post.category = form.category.data

        if 'photo' in request.files:

            file = request.files['photo']
            filename = secure_filename(file.filename)
            images.save(request.files['photo'], folder="blog_photos/")
            post.photo_filename = filename

        db.session.commit()

        flash('Changes saved.')
        return redirect(url_for('manage_blog'))

    elif request.method == 'GET':
        form.post_title.data = post.title
        form.post_body.data = post.body
        form.category.data = post.category

    return render_template('edit_blog_post.html', form=form, post=post)
Exemplo n.º 2
0
def upload():
    form =UploadForm()
    if form.validate_on_submit():
        images.save(form.upload_file.data)
        print(form.upload_file.data)
        # print(images.path(form.upload_file))
    return render_template('upload.html', form=form)
Exemplo n.º 3
0
    def context(self):
        cata = request.args.get('c', '')
        result = {'notify': ''}
        if cata == 'view':
            if 'edit' in request.args:
                id = request.args.get('edit')
                if request.method == 'POST' and request.form['edit'] == 'Save':
                    if request.files.get('image').filename != '':
                        remove(app.config['UPLOADED_IMAGES_DEST'] + mongo.db.news.find_one({'_id': ObjectId(id)})['image'])
                        filename = images.save(request.files.get('image'), 'news')
                    else:
                        filename = mongo.db.news.find_one({'_id': ObjectId(id)})['image']

                    result['notify'] = update_news(id, request.form, filename, session['manager'] + ' - ' + str(datetime.now()))
                result['show'] = EditForm(mongo.db.news.find_one( { '_id': ObjectId(id) } ), 
                                          [(u'Tiêu đề', 'name', 'text'), 
                                           (u'Ảnh minh họa', 'image', 'image'), 
                                           (u'Tóm tắt', 'summary', 'textarea'),
                                           (u'Nội dung', 'content', 'news'), 
                                           (u'Trạng thái', 'status', [u'Đã duyệt', u'Chưa duyệt']), 
                                           (u'Ngày đăng', 'create_date', 'readonly'), 
                                           (u'Người đăng', 'creator', 'readonly')])
                return result
            elif request.method == 'POST' and 'delete' in request.form:
                remove(app.config['UPLOADED_IMAGES_DEST'] + mongo.db.news.find_one({'_id': ObjectId(request.form['delete'])})['image'])
                result['notify'] = remove_news(request.form['delete'])
            collection = mongo.db.news.find().sort("_id", -1)
            result['show'] = ViewForm(collection, 
                                      [(u'Tiêu đề', 'name'), 
                                       (u'Ảnh minh họa', 'image'), 
                                       (u'Tóm tắt', 'summary'), 
                                       (u'Ngày đăng', 'create_date'), 
                                       (u'Trạng thái', 'status')], 
                                      request.url,
                                      '_id')
            return result
        elif cata == 'create':
            if request.method == 'POST' and 'image' in request.files:
                filename = images.save(request.files.get('image'), 'news')
                result['notify'] = insert_news(request.form, filename, session['manager'])
            return result
        elif cata == 'upload':
            if request.method == 'POST' and 'image' in request.files:
                filename = images.save(request.files.get('image'), 'images')
                mongo.db.images.insert({'filename': filename, 'created_date': datetime.now()})
                result['notify'] = 'Uploaded Image ' + filename
            elif 'delete' in request.args:
                mongo.db.images.remove({'filename': request.args.get('delete', '')})
                remove(app.config['UPLOADED_IMAGES_DEST'] + request.args.get('delete', ''))
                result['notify'] = 'Removed Image ' + request.args.get('delete', '')

            result['files'] = mongo.db.images.find().sort("_id", -1).limit(20)
            return result
        else:
            return result
Exemplo n.º 4
0
def newclub():
    form = NewClubForm()
    if form.validate_on_submit():
        division = form.club_division.data
        filename = images.save(request.files['club_badge'])
        url = images.url(filename)
        club = Club(clb_name=form.clubname.data,
                    clb_town=form.club_town.data,
                    clb_postcode=form.club_postcode.data,
                    division_id=division.id,
                    clb_contract=form.club_contract.data,
                    clb_collab=form.club_collab.data,
                    clb_fundingapp=form.club_fundingapp.data,
                    clb_badge=url)
        db.session.add(club)
        db.session.commit()
        flash('You have successfully added ' + club.clb_name)
        return redirect(url_for('main.clubs'))
    # page = request.args.get('page', 1, type=int)
    # clubs = Club.query.order_by(Club.clb_name.asc()).paginate(
    #     page, current_app.config['POSTS_PER_PAGE'], False)
    # next_url = url_for(
    #     'main.clubs', page=clubs.next_num) if clubs.has_next else None
    # prev_url = url_for(
    #     'main.clubs', page=clubs.prev_num) if clubs.has_prev else None
    return render_template('form.html', title='Add Club', form=form)
Exemplo n.º 5
0
def handle_request():
    if request.method == 'POST':
        if request.files:
            username = '******'

            filename = images.save(request.files['image'])
            url = images.url(filename)

            #---------------------

            result = predict(filename)

            #---------------------

            user = User.query.filter_by(username=username).first()
            if user is None: user = User(username=username)

            report = Report(user=user, data=json.dumps(result))

            image = Image(report=report)

            image.image_filename = filename
            image.image_url = url

            db.session.add(user)
            db.session.add(report)
            db.session.add(image)

            db.session.commit()

            return 'Report Generated'
        return 'No Files Recieved'
    return 'Method not POST'
Exemplo n.º 6
0
def edit_portfolio():

    form = ProjectForm()

    if form.validate_on_submit() and form.submit.data:

        if 'cover_img' not in request.files:
            flash('Project requires a cover photo.')
            return redirect(url_for('edit_portfolio'))

        file = request.files['cover_img']
        filename = secure_filename(file.filename)
        saved = images.save(file, folder="portfolio/")

        new_project = (PortfProject(
            name=form.name.data,
            description=form.description.data,
            url=form.url.data,
            cover_img_filename=filename,
            cover_img_alt_txt=form.cover_img_alt_txt.data,
            link_text=form.link_text.data))

        db.session.add(new_project)
        db.session.commit()

        if saved:
            flash('New project now live!')
        return redirect(url_for('portfolio'))

    projects = PortfProject.query.order_by(PortfProject.id.desc())

    return render_template('edit_portfolio.html',
                           title='Edit Portfolio',
                           form=form,
                           projects=projects)
Exemplo n.º 7
0
 def import_data(self, request):
     """Import the data for this recipe by either saving the image associated
     with this recipe or saving the metadata associated with the recipe. If
     the metadata is being processed, the title and description of the recipe
     must always be specified."""
     try:
         if 'recipe_image' in request.files:
             filename = images.save(request.files['recipe_image'])
             self.image_filename = filename
             self.image_url = images.url(filename)
         else:
             json_data = request.get_json()
             self.recipe_title = json_data['title']
             self.recipe_description = json_data['description']
             if 'recipe_type' in json_data:
                 self.recipe_type = json_data['recipe_type']
             if 'rating' in json_data:
                 self.rating = json_data['rating']
             if 'ingredients' in json_data:
                 self.ingredients = json_data['ingredients']
             if 'recipe_steps' in json_data:
                 self.recipe_steps = json_data['recipe_steps']
             if 'inspiration' in json_data:
                 self.inspiration = json_data['inspiration']
     except KeyError as e:
         raise ValidationError('Invalid recipe: missing ' + e.args[0])
     return self
Exemplo n.º 8
0
def novo_servidor():
	form = FormServidor()	
	if request.method == 'POST':
		if form.validate_on_submit:
			filename = images.save(request.files['photo'])
			url = images.url(filename)	
			# Verifica se o cpf já existe
			cpf = form.cpf.data	
			retorno = Servidor.query.filter_by(cpf=cpf).first()	
			if retorno is not None:
				flash( 'O CPF já está cadastrado.')
				return render_template('pages/novo_servidor.html', title="Cadastro de Servidor", form=form)
			else:	# caso contrário insere no banco de dados			
				servidor = Servidor()
				servidor.nome = form.nome.data
				servidor.cpf  = cpf
				servidor.banco = form.banco.data
				servidor.agencia = form.agencia.data
				servidor.conta = form.conta.data
				servidor.tipoconta = form.tipoconta.data
				servidor.photo = filename
				servidor.photo_url = url
				db.session.add(servidor)
				db.session.commit()
				flash('Novo registro, {}, cadastrado!'.format(servidor.nome), 'sucess')
				return redirect(url_for('pages.servidores'))
		else:
			flash('ERROR! O registro não foi adicionado', 'error')
		
	return render_template('pages/novo_servidor.html', title="Cadastro de Servidor", form=form)
Exemplo n.º 9
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)
Exemplo n.º 10
0
def register():
    """
    Handle requests to the /register route
    Add a user to the database through the registration form
    """
    form = RegistrationForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            filename = images.save(request.files['user_photo'])
            url = images.url(filename)
            user = User(email=form.email.data,
                        username=form.username.data,
                        first_name=form.first_name.data,
                        last_name=form.last_name.data,
                        sex=form.sex.data,
                        number1=form.number1.data,
                        number2=form.number2.data,
                        country=form.country.data,
                        image_filename=filename,
                        image_url=url,
                        password=form.password.data)
            # add user to the database
            db.session.add(user)
            db.session.commit()
            flash('You have successfully registered! You may now login.')

            # redirect to the login page
            return redirect(url_for('auth.login'))

    # load registration template
    return render_template('auth/register.html', form=form, title='Register')
Exemplo n.º 11
0
def editPerson(clinic_id, region_name, person_id):
    person = Person.query.filter_by(id=person_id).one()
    form = EditPerson(person.name, person.email, obj=person)
    if form.validate_on_submit():
        if form.picture_url.data == person.picture_url:
            url = form.picture_url.data
            filename = person.picture_filename
        else:
            filename = images.save(request.files['picture_url'])
            url = images.url(filename)
        person.name = form.name.data
        person.comments = form.comments.data
        person.picture_filename = filename
        person.picture_url = url
        person.phone = form.phone.data
        person.email = form.email.data
        person.department = form.department.data
        person.date_of_request = form.date_of_request.data
        person.date_of_request2 = form.date_of_request2.data
        db.session.commit()
        flash('Изменения сохранены')
        return redirect(
            url_for('clients.showPersons',
                    region_name=region_name,
                    clinic_id=clinic_id))
    return render_template('/clients/edit_person.html',
                           title='Edit Client',
                           form=form,
                           person_id=person_id,
                           clinic_id=clinic_id,
                           region_name=region_name)
Exemplo n.º 12
0
def manage_plant(id):
    plant = Plant.query.get(id)
    form = PlantManagementForm()
    if form.validate_on_submit():
        if form.action.data:
            print("Update the plant")
            # if location is not null, update the plant's location
            if form.location.data:
                plant.location = form.location.data
                flash('Congratulations, plant location updated')

            # if there is a photo, delete the old on and set the new one
            if request.files['photo']:
                os.remove(app.config['UPLOADS_DEFAULT_DEST'] +
                          plant.image_filename)

                filename = images.save(request.files['photo'])
                url = images.url(filename)
                plant.image_filename = filename
                plant.image_url = url
                flash('Congratulations, plant photo updated')

        if form.delete.data:
            print("delete the plant")
            db.session.delete(plant)
            flash('Congratulations, plant deleted')

        db.session.commit()

        return redirect(url_for('index'))
    return render_template('manage_plant.html', form=form)
Exemplo n.º 13
0
 def set_avatar(self, image):
     filename = images.save(image, name=str(uuid.uuid4().hex)+'.')
     if self.avatar:
         os.remove(images.path(self.avatar))
     self.avatar = filename
     #self.squarePortrait();
     self.save()
Exemplo n.º 14
0
def report():
    form = CaseForm()
    form.level.choices = [
        (building.buildingDesc, building.buildingDesc)
        for building in Building.query.filter_by(buildingID='B02').all()
    ]
    user = current_user.get_id()
    if request.method == 'POST':
        filename = secure_filename(images.save(request.files['photo']))
        url = images.url(filename)
        case = Case(photoFilename=filename,
                    photoURL=url,
                    building=form.building.data,
                    location=request.form['location'],
                    level=request.form['level'],
                    roomNum=form.unit.data,
                    typeOfFacility=request.form['facility'],
                    severity=form.severity.data,
                    comments=form.description.data,
                    userID=user)
        db.session.add(case)
        db.session.commit()
        # db.session.refresh(case)
        createGroupedBar()
        createBar()
        backlogPie()
        buildingPie()
        case_id = str(case.caseID)
        return redirect(url_for('success', caseid=case_id))
    return render_template('report.html', title='Case Reporting', form=form)
Exemplo n.º 15
0
def logbook(id):
    form = LogbookForm()
    book = Logbook.query.filter_by(user_id=current_user.id).all()
    if form.validate_on_submit():
        filename = images.save(form.photo.data)
        book = Logbook()
        book.saida = form.saida.data.upper()
        book.chegada = form.chegada.data.upper()
        book.aeronave = form.aeronave.data.upper()
        book.voo = form.voo.data.upper()
        book.tempo = form.tempo.data
        book.user_id = current_user.id
        book.status = 'Em analise'
        current_user.cont_tempo = get_all_time2(
            Logbook.query.filter_by(user_id=id).all())
        current_user.cont_tempo_str = get_all_time(
            Logbook.query.filter_by(user_id=id).all())
        current_user.cont_voo = len(Logbook.query.filter_by(user_id=id).all())
        db.session.add(book)
        db.session.add(current_user)
        db.session.commit()
        flash('LogBook Registrado com Sucesso!!', 'success')

        return redirect(url_for('logbook', id=current_user.id))

    return render_template('logbook.html', form=form)
Exemplo n.º 16
0
def create_article():
    """Написание статьи"""
    form = ArticleForm()
    if request.method == 'POST' and form.validate():
        try:
            filename = images.save(request.files['poster'], 'posters')
            category = Category.query.filter_by(
                id=form.category_id.data).first()

            article = Article(
                category=category,
                author=current_user,
                title=form.title.data,
                poster=filename,
                short_desc=form.short_desc.data,
                text=form.text.data,
                draft=form.draft.data,
            )

            for tag_name in form.tags.data:
                tag = Tag.query.filter_by(name=tag_name).first()
                article.tags.append(tag)

            db.session.add(article)
            db.session.commit()
        except:
            print('Error saving form')

        return redirect(url_for('account_app.my_articles'))

    return render_template('account_app/article_create.html', form=form)
Exemplo n.º 17
0
def profile():
    """Заполнение профиля пользователя"""
    profile = UserProfile.query.filter_by(user=current_user).first()
    form = UserProfileForm(formdata=request.form, obj=profile)

    if request.method == 'POST' and form.validate():
        if not profile:
            try:
                filename = images.save(request.files['avatar'], 'avatars')
            except:
                filename = 'avatars/default_avatar.jpg'

            try:
                user_profile = UserProfile(
                    user=current_user,
                    first_name=form.first_name.data,
                    last_name=form.last_name.data,
                    gender=form.gender.data,
                    about=form.about.data,
                    date_of_birth=form.date_of_birth.data,
                    avatar=filename,
                )
                db.session.add(user_profile)
                db.session.commit()

            except Exception as e:
                print('Error saving profile', e)

            return redirect(url_for('auth_app.profile'))

        profile.user = current_user
        profile.first_name = form.first_name.data
        profile.last_name = form.last_name.data
        profile.gender = form.gender.data
        profile.about = form.about.data
        profile.date_of_birth = form.date_of_birth.data

        if request.files['avatar']:
            filename = images.save(request.files['avatar'], 'avatars')
            profile.avatar = filename

        db.session.commit()

        return redirect(url_for('auth_app.profile'))

    return render_template('auth_app/profile.html', form=form, profile=profile)
Exemplo n.º 18
0
def manage_blog():

    form = BlogPostForm()
    form.category.choices = ([(cat.category, cat.category)
                              for cat in BlogCategory.query.all()])

    # Publish new blog post
    if form.validate_on_submit() and form.submit.data:

        if 'photo' not in request.files:
            flash('Post requires a photo.')
            return redirect(url_for('manage_blog'))

        file = request.files['photo']
        filename = secure_filename(file.filename)
        saved = images.save(request.files['photo'], folder="blog_photos/")

        post = BlogPost(title=form.post_title.data,
                        body=form.post_body.data,
                        category=form.category.data,
                        photo_filename=filename,
                        photo_alt_text=form.photo_alt_text.data)

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

        if saved:
            flash('Post is now live!')
        return redirect(url_for('blog'))

    post_count = BlogPost.query.count()
    comments_count = BlogComment.query.count()
    most_pop = BlogPost.query.order_by(
        BlogPost.post_score.desc()).first_or_404()
    latest = BlogComment.query.order_by(
        BlogComment.timestamp.desc()).first_or_404()
    latest_comment_post = (BlogPost.query.filter_by(
        id=latest.post_id).first_or_404())

    page = request.args.get('page', 1, type=int)
    posts = BlogPost.query.order_by(BlogPost.timestamp.desc()).paginate(
        page, app.config['TITLES_PER_PAGE'], False)
    next_url = url_for('manage_blog', page=posts.next_num) \
        if posts.has_next else None
    prev_url = url_for('manage_blog', page=posts.prev_num) \
        if posts.has_prev else None

    return render_template('manage_blog.html',
                           title='Manage Blog',
                           form=form,
                           posts=posts.items,
                           next_url=next_url,
                           prev_url=prev_url,
                           post_count=post_count,
                           comments_count=comments_count,
                           most_pop=most_pop,
                           latest=latest,
                           latest_comment_post=latest_comment_post.title)
Exemplo n.º 19
0
def index():
    form = PostForm()
    if current_user.can(Permission.WRITE_ARTICLES) and \
            form.validate_on_submit():

        filename = images.save(request.files['image'])
        url = images.url(filename)
        post = Post(title=form.title.data,
                    sub_title=form.sub_title.data,
                    body=form.body.data,
                    author=current_user._get_current_object(),
                    image_url=url,
                    image_filename=filename)

        topics = form.topics.data
        clean_topics = "".join(topics.split())
        topics_list = clean_topics.split(',')
        capitalized = [topic.capitalize() for topic in topics_list]

        for topic in capitalized:
            exists = Topic.query.filter_by(topic=topic).all()
            if exists:
                post.topics.append(exists[0])

            else:
                new_topic = Topic(topic=topic)
                post.topics.append(new_topic)

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

        return redirect(url_for('.index'))

    page = request.args.get('page', 1, type=int)
    show_followed = False
    if current_user.is_authenticated:
        show_followed = bool(request.cookies.get('show_followed', ''))
    if show_followed:
        query = current_user.followed_posts
    else:
        query = Post.query
    pagination = query.order_by(Post.timestamp.desc()).paginate(
        page,
        per_page=current_app.config['FLASKY_POSTS_PER_PAGE'],
        error_out=False)
    posts = pagination.items
    popular_posts = get_popular_posts()
    popular_topics = get_popular_topics()

    return render_template('index.html',
                           popular_posts=popular_posts,
                           popular_topics=popular_topics,
                           form=form,
                           posts=posts,
                           show_followed=show_followed,
                           pagination=pagination)
Exemplo n.º 20
0
def experiment(experiment_id):
    experiment = Experiment.query.filter_by(id=experiment_id).first_or_404()
    form = AddRunForm()

    if form.validate_on_submit():
        columns = ''
        if experiment.column_extract_code is not None:
            # extract columns from output
            # TODO This part should be done once when code is submitted.
            source_code = experiment.column_extract_code
            try:
                byte_code = compile(source_code,
                                    filename='<inline code>',
                                    mode='exec')
                loc = {}
                exec(byte_code, globals(), loc)
                columns = loc['parse'](form.run_result.data)
                if columns is None:
                    columns = ''
                if validat_csv(columns) is False:
                    form.run_result.errors.append(
                        'exctracted columns wrongs format: ' + columns)
                    return render_experiment(experiment, form)
            except Exception as e:
                form.run_result.errors.append('Error while parsing:' + str(e))
                return render_experiment(experiment, form)
            columns = clean_columns(columns)
        if validat_csv(form.columns.data) is False:
            form.columns.errors.append('columns wrongs format')
            return render_experiment(experiment, form)

        # if columns == '':
        #     columns = clean_columns(form.columns.data)
        # else:
        #     columns = columns + ', ' + clean_columns(form.columns.data)

        run = Run(description=form.description.data,
                  run_result=form.run_result.data,
                  owner=current_user,
                  result_inffered_columns=columns,
                  columns=clean_columns(form.columns.data),
                  experiment_id=int(experiment_id))
        db.session.add(run)
        db.session.commit()
        if form.upload_file.data is not None:
            f = form.upload_file.data
            fn = images.save(f, str(run.id))
            new_file = FileContent(run_id=run.id, file_name=fn)
            db.session.add(new_file)
            db.session.commit()

        return redirect(url_for('main.experiment',
                                experiment_id=experiment_id))
    return render_experiment(experiment, form)
Exemplo n.º 21
0
    def sending_updated_data(self, post_id):
        topic_n = self.topic.data
        heading_n = self.heading.data
        post_preview_n = self.post_preview.data
        post_text_n = self.post_text.data
        post_image_n = images.save(self.image.data)

        post = models.Post.query.filter_by(post_id=post_id).first()
        post.update_post(topic_n=topic_n, heading_n=heading_n, post_preview_n=post_preview_n, post_text_n=post_text_n, post_image_n=post_image_n)

        return post
Exemplo n.º 22
0
def upload(id):
    event = Event.query.filter_by(id=int(id)).first_or_404()
    form = PhotoUploadForm()
    if form.validate_on_submit():
        name_path = 'event/eventphoto_{}.'.format(event.id)

        f = form.event_photo.data
        filename = images.save(request.files['event_photo'], name=name_path)
        event.image_url = images.url(filename)
        db.session.commit()
        return redirect(url_for('event', id=id))
    return render_template('upload.html', form=form)
Exemplo n.º 23
0
    def create_post_object(self):
        # Retrieve data from form
        topic = self.topic.data
        heading = self.heading.data
        post_preview = self.post_preview.data
        post_text = self.post_text.data
        image = images.save(self.image.data)

        # Creating a post
        post = models.Post.create_post(topic=topic, heading=heading, post_preview=post_preview, post_text=post_text,
                                       post_image=image)

        return post
Exemplo n.º 24
0
def edit_profile():
    form = EditProfileForm(user=current_user)
    if form.validate_on_submit():
        if not os.path.exists(current_app.config['UPLOADS_DEFAULT_DEST']):
            os.makedirs(current_app.config['UPLOADS_DEFAULT_DEST'])
            os.chmod(current_app.config['UPLOADS_DEFAULT_DEST'],
                     stat.S_IRWXU + stat.S_IRGRP + stat.S_IWGRP + stat.S_IROTH)
        elif not os.path.exists(current_app.config['IMG_THUMB_DEST']):
            os.makedirs(current_app.config['IMG_THUMB_DEST'])
            os.chmod(current_app.config['IMG_THUMB_DEST'],
                     stat.S_IRWXU + stat.S_IRGRP + stat.S_IWGRP + stat.S_IROTH)

        if form.avatar.data:
            avatar_filename = images.save(form.avatar.data)
            size = 50, 50
            im = Image.open(
                os.path.join(current_app.config['UPLOADS_DEFAULT_DEST'],
                             'images/', avatar_filename))
            im.thumbnail(size)
            file_split_name = os.path.splitext(avatar_filename)
            img_thumb = file_split_name[0] + '_thumbnail' + file_split_name[-1]
            im.save(
                os.path.join(current_app.config['IMG_THUMB_DEST'], img_thumb))
            current_user.thumb_head_img = url_for(
                'static', filename='uploads/thumbnails/' + img_thumb)
            current_user.head_img = images.url(avatar_filename)

        if form.location.data:
            current_user.location = form.location.data
        if form.phone.data:
            current_user.phone = form.phone.data
        if form.intro.data:
            current_user.info = form.intro.data
        current_user.username = form.username.data

        db.session.add(current_user)
        try:
            db.session.commit()
            flash('个人资料已经更新!')
        except:
            flash('未知错误!请重试或联系管理员')
            db.session.rollback()

        return redirect(url_for('.user', username=current_user.username))
    form.username.data = current_user.username
    form.phone.data = current_user.phone
    form.intro.data = current_user.info
    form.location.data = current_user.location
    return render_template('home/edit_profile.html',
                           form=form,
                           user=current_user)
Exemplo n.º 25
0
def upload():
    image = request.files.get('upload')

    if not image:
        abort(400)

    # Rename file to random filename:
    file = image.filename.split('.')
    extension = file.pop()
    new_filename = str(uuid4())
    image.filename = '.'.join([new_filename, extension])

    try:
        images.save(image)
    except UploadNotAllowed:
        abort(403)
    else:
        return jsonify({
            "url":
            current_app.config['UPLOADS_DEFAULT_URL'] + 'images/' +
            image.filename
        }), 201
    abort(400)
Exemplo n.º 26
0
def upload():
    if request.method == 'POST':
        filename    = images.save(request.files['photo'])
        url_photo   = images.url(filename)
        user = User.query.get(current_user.id)
        user.url_photo = url_photo
        try:
            db.session.commit()
            flash('Photo uploaded', 'alert-success')
        except:
            flash('Photo did not load', 'alert-danger')        
        return redirect(url_for('main.profile'))
    elif request.method == 'GET':
        form = UploadForm()
        return render_template('main/upload.html', form=form)
Exemplo n.º 27
0
def add():
    form = AddUserForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            filename = images.save(request.files['user_image'])
            url = images.url(filename)
            new_user = User(form.name.data, form.email.data, form.sex.data, form.password.data, filename, url)
            db.session.add(new_user)
            db.session.commit()
            return redirect("/")
        else:
            flash("入力内容が間違っているため、ユーザー登録できませんでした。")


    return render_template("users/add.html", form=form)
Exemplo n.º 28
0
def upload_avatar():
    nickname = request.form['user_nickname']
    user = User.query.filter_by(nickname=nickname).first()

    if g.user.nickname != nickname:
        return abort(404)
    else:
        filename = images.save(request.files['avatar'])
        url = images.url(filename)

        user.set_avatar_url(url)
        db.session.add(user)
        db.session.commit()
        return redirect(url_for('user_profile', nickname=nickname, _external=True))
    return redirect(url_for('user_profile', nickname=nickname, _external=True))
Exemplo n.º 29
0
def add_cuisine():
    form = AddCuisineForm()
    if request.method == 'POST':
        print "Hello"
        if form.validate_on_submit():
            print form.errors
            filename = images.save(request.files['cuisine_img'])
            url = images.url(filename)
            addCuisine(form.title.data, form.description.data,
                       int(form.global_.data), int(form.preparation.data),
                       int(form.meal_type.data), int(form.main_ingr.data),
                       filename, url)

            return redirect(url_for('index'))

    return render_template('addcuisine.html', form=form)
Exemplo n.º 30
0
def input_charity_info():
    '''
    Redirect to this page after Stripe Connect
    Create the product and the plan which is connected to the charity
    '''
    print('AAAA')
    form = CharityInputForm()
    if form.validate_on_submit():  #This line should be fixed later.
        '''
        Save the charity's info into Charity data table
        '''
        print('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA')
        filename = images.save(request.files['charity_logo'])
        image_url = images.url(filename)

        charity = Charity.query.filter_by(user_id=current_user.id).first()

        charity.charity_name = form.charity_name.data
        charity.charity_logo = image_url
        charity.description = form.description.data
        charity.link = form.link.data
        charity.is_form_done = True

        db.session.commit()

        stripe.api_key = stripe_keys['secret_key']

        try:
            product = stripe.Product.create(name='donation', type='service')

            #Plan should be created only once
            plan = stripe.Plan.create(
                nickname=current_user.id,  #Cannot be changed
                product=product.id,
                id=current_user.id,
                interval='month',
                currency='usd',
                amount=0)
        except:
            print('Error caused.')

        flash('Your Charity is registered successfully!')
        return redirect(url_for('index'))
    return render_template('input_charity_info.html',
                           title='Input Charity Info',
                           form=form)
Exemplo n.º 31
0
def save_image_get_filename(image_file):
    """
    If the user attached an image, save it
    and return its url. Otherwise return an empty str
    meaning the item has no image.

    :param image_file: An image file of the item
    :return: the image url to save in the Item table
    """
    if image_file:
        filename = images.save(
            image_file,
            name=image_file.filename
        )

        return filename

    return ''
Exemplo n.º 32
0
def update_photo(id):
	row = Servidor.query.filter_by(id=id).first()
	if row:
		form = FormPhoto(request.form, obj=row)
		if request.method == 'POST' and form.validate_on_submit:
			filename = images.save(request.files['photo'])
			url = images.url(filename)
			updeted = Servidor.query.filter_by(id=id).update({
				Servidor.photo : filename,
				Servidor.photo_url: url
			})	
			db.session.commit()	
			flash('Foto atualizada com sucesso!', 'sucess')	
			return redirect(url_for('pages.servidores'))
		return render_template('pages/update_photo.html', form=form, row=row)
	else:
		flash('O Registro com ID: #{}, não existe na base de dados.'.format(id), 'error')
		return redirect(url_for('pages.servidores'))
Exemplo n.º 33
0
def add_recipe():
    form = AddRecipeForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            filename = images.save(request.files['recipe_image'])
            url = images.url(filename)
            new_recipe = Recipe(form.recipe_title.data,
                                form.recipe_description.data, current_user.id,
                                True, filename, url)
            db.session.add(new_recipe)
            db.session.commit()
            flash('New Recipe, {0}, added!'.format(new_recipe.recipe_title),
                  'success')
            return redirect(url_for('recipes.user_recipes'))
        else:
            flash_errors(form)
            flash('ERROR! Recipe was not added!', 'error')

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