Пример #1
0
def edit_tag(id):
    form = TagForm()
    tag = Tag.query.get_or_404(id)
    form.name.data = tag.name
    if form.validate_on_submit():
        pass
    return render_template('tag_edit.html', form=form)
Пример #2
0
def taggremaker():
    """
    Page to generate taggregator iframe. Starts with example iframe for tumblr user airdeari.
    Uses TagForm to make a new taggregation for the tumblr user and styling of choice.
    :return: the page I just described
    """
    u = "airdeari"
    c = "fffafb"
    h = 200
    w = 300
    iframe_code = '<iframe src="http://iraedria.ksadwin.com' +\
                  url_for('taggregator', username=u, color=c, height=h, width=w) +\
                  '" frameBorder="0" scrolling="no"></iframe>'
    f = TagForm()
    if f.validate_on_submit():
        u = f.username.data
        c = f.color.data
        h = f.height.data
        w = f.width.data
        iframe_code = '<iframe src="http://iraedria.ksadwin.com' +\
                      url_for('taggregator', username=u, color=c, height=h, width=w) +\
                      '" frameBorder="0" scrolling="no"></iframe>'
        return render_template("tagremaker.html", form=f, u=u, c=c, w=w, h=h, iframe_code=iframe_code)
        # I should have just made this form myself with JS probably
    return render_template("tagremaker.html", form=f, u=u, c=c, w=w, h=h, iframe_code=iframe_code)
Пример #3
0
def tag():
    if request.method == 'POST':
        form = TagForm()
        if form.new_row.data:
            form.img_tag.append_entry()
        elif form.submit.data:
            if form.validate_on_submit():
                key_array = []
                for key in request.files.keys():
                    key_array.append(key)
                for idx in range(0, len(request.files)):
                    tags = form.img_tag.data[idx]['tag'].split(",")
                    images = request.files.getlist(key_array[idx])
                    for img in images:
                        filename = save_file(img)
                        add_and_tag_file(filename, form.project.data, tags)
                        os.remove(
                            os.path.join(app.config['UPLOAD_FOLDER'],
                                         filename))
                iteration_info = train_project(form.project.data)
                flash('Files uploaded')
                return render_template('train_result.html',
                                       info=iteration_info)
            flash('No files were uploaded')
        return render_template('tag.html', form=form)
    form = TagForm()
    return render_template('tag.html', form=form)
def detail_view(rec_number):
    # создадим формы
    commentform = CommentForm()
    tagform = TagForm()
    # сохраним начала ключей данного оюъявления в редис
    tag_key = f'{rec_number}:tags'
    comment_key = f'{rec_number}:comments:'
    # выгребаем из кэша простые словари, без вложенностей
    bul = fish_out_of_cache_simple(r, rec_number)
    # если есть тэги, запрашиваем и их, но т.к. они хранятся в виде сета, то для них используется другая команда
    if r.scard(tag_key) > 0:
        bul['tags'] = [x.decode("utf-8") for x in r.smembers(tag_key)]

    # Выбираем из кэша комменты. Перебираем все по очереди, используя начало ключа и счетчик
    # когда оба запроса на предполагаемый контент вернут ничего, останавливаемся
    bul['comments'] = []
    comment_count = 0
    while True:
        author = r.get(f'{comment_key}{comment_count}:author')
        content = r.get(f'{comment_key}{comment_count}:content')
        if not (author and content):
            break
        comment_count += 1
        bul['comments'].append({
            'author': author.decode("utf-8"),
            'content': content.decode("utf-8")
        })

    # если с формы пришли тэги, превращаем их в массив и закидываем в редис
    # если после этого окажется, что сэт увеличился, переписываем в сэт в бд
    if tagform.validate_on_submit():
        new_tags = make_tags(tagform.tags.data)
        r.sadd(tag_key, *new_tags)
        if r.scard(tag_key) > len(bul['tags']):
            col.update_one({"_id": ObjectId(rec_number)}, {
                "$set": {
                    "tags": [x.decode("utf-8") for x in r.smembers(tag_key)]
                }
            })
        return redirect(url_for('detail_view', rec_number=rec_number))

    # берем новый коммент с формы и записываем и в бд и в кэш
    if commentform.validate_on_submit():
        new_comment = {
            "author": commentform.author.data,
            "content": commentform.content.data,
        }
        col.update_one({"_id": ObjectId(rec_number)},
                       {"$push": {
                           "comments": new_comment
                       }})
        r.set(f'{comment_key}{comment_count}:author', new_comment['author'])
        r.set(f'{comment_key}{comment_count}:content', new_comment['content'])
        return redirect(url_for('detail_view', rec_number=rec_number))
    return render_template('bul_detail.html',
                           title='Bulletin',
                           bul=bul,
                           cmform=commentform,
                           tgform=tagform)
Пример #5
0
def tags():
    tag_form = TagForm()
    if tag_form.validate_on_submit():
        tag_name = tag_form.tag_name.data
        tag = Tag(TagName=tag_name)
        db.session.add(tag)
        db.session.commit()
        flash(f"Created Tag: {tag_form.tag}")
    return render_template('tags.html', TagForm=tag_form)
def post_tag():
    form = TagForm()
    user = current_user
    print(user.id)
    form['csrf_token'].data = request.cookies['csrf_token']
    if form.validate_on_submit():
        tag = Tag(tagName=form.data['tagName'], userId=user.id)
        db.session.add(tag)
        db.session.commit()
        return tag.to_dict()
Пример #7
0
def task():
	rpp = get_random_pair_of_posts(DB)
	tag_form = TagForm(newsgroupA=rpp[0]['label'], newsgroupB=rpp[1]['label'])
	if tag_form.validate_on_submit():
		tag_form_results = [tag_form.newsgroupA.data, tag_form.tagA.data, 
							tag_form.newsgroupB.data, tag_form.tagB.data]
		save_results(tag_form_results, DB)
		flash("Thank you for entering these tags: {}:'{}', {}:'{}'".format(*tag_form_results))
		return redirect(url_for('task'))
	return render_template('task.html', rpp=rpp, form=tag_form)
Пример #8
0
def tag():
    form = TagForm()
    tags = Tag.query.all()
    if form.validate_on_submit():
        name = form.name.data
        tag = Tag(name=name)
        db.session.add(tag)
        db.session.commit()
        flash('create success!', 'success')
        return redirect(url_for('tag'))
    return render_template('tag_list.html', form=form, tags=tags)
Пример #9
0
def get_tagquestions():
    form = TagForm()
    if form.validate_on_submit():
        tag = form.tag.data
        tag = tag.lower()
        print(tag)
        if (tag == 'dynamic programming'):
            tag = "dp"
        if (tag == 'dfs'):
            tag = "dfs and similar"
        if (tag == "mst" or tag == "minimum shortest path"
                or tag == "minimum shortest paths"):
            tag = "shortest paths"
        if (tag == "tree"):
            tag = "trees"
        if (tag == "graph"):
            tag = "graphs"
        if (tag == "maths"):
            tag = "math"
        if (tag == "matrix"):
            tag = "matrices"
        all_data = QuestionTags.query.filter(QuestionTags.Tag == tag).all()
        #dividing codechef and codeforces
        cc_data = []
        cf_data = []
        for d in all_data:
            qid = d.Ques_id
            question = Questions.query.filter(Questions.Qid == qid).first()
            qname = question.Qname
            ques_link = question.Ques_link
            sol_link = question.Sol_link
            if question.Platform == 'codechef':
                ques_link = Config.codechef_question_link + ques_link
                if sol_link:
                    sol_link = Config.codechef_solution_link + sol_link
                else:
                    sol_link = None
                q_data = Questiondata(qname, ques_link, sol_link)
                cc_data.append(q_data)
            elif question.Platform == 'codeforces':
                ques_link = Config.codeforces_question_link + ques_link
                sol_link = Config.codeforces_solution_link + sol_link
                q_data = Questiondata(qname, ques_link, sol_link)
                cf_data.append(q_data)
        return render_template('print_tagquestions.html',
                               tag=tag,
                               cc_data=cc_data,
                               cf_data=cf_data)
    return render_template('get_tagquestions.html', form=form)
Пример #10
0
def manage():

    header = {
        "title": "Admin page",
        "subtitle": "Manage your blog!",
        "image_path": "manage_bg.jpg",
        "needed": True,
        "dashboard_flash": True
    }

    posts = Blogpost.query.order_by(Blogpost.date_posted.desc()).all()
    tags = Tags.query.all()

    form = TagForm()

    #if post request to edit form and is validated
    if form.validate_on_submit():

        app.logger.info('tag to be added')

        tag = Tags(name=form.name.data)
        db.session.add(tag)
        db.session.commit()

        #flash message, article has been updated
        flash('tag uploaded', 'success')

        #redirect
        return redirect(url_for('manage'))

    #load template with articles
    return render_template('manage.html',
                           posts=posts,
                           header=header,
                           tags=tags,
                           form=form)