Beispiel #1
0
def wtf():
    name = None
    form = FlaskForm()
    if form.validate_on_submit():  # 如果输入的数据验证通过,validate_on_submit()方法返回True
        name = form.name.data  # 赋值给局部变量
        form.name.data = ' '  # 将表单字段清空
    return render_template('wtf.html', form=form, name=name)  # 渲染模板,带有变量name的值
    def user_delete(username):
        title = "Delete User"

        if not ldap_user_exists(username=username):
            abort(404)

        form = FlaskForm(request.form)

        if form.validate_on_submit():
            try:
                user = ldap_get_user(username=username)
                ldap_delete_entry(user['distinguishedName'])
                flash(u"User deleted successfully.", "success")
                return redirect(url_for('core_index'))
            except ldap.LDAPError as e:
                e = dict(e.args[0])
                flash(e['info'], "error")
        elif form.errors:
            flash(u"Data validation failed.", "error")

        return render_template("pages/user_delete_es.html",
                               title=title,
                               action="Delete User",
                               form=form,
                               username=username,
                               parent=url_for('user_overview',
                                              username=username))
Beispiel #3
0
Datei: view.py Projekt: zabano/dx
def show_reports():

    form = FlaskForm()
    if form.validate_on_submit():

        vcf_id = request.form['vcfs'].split(',')[0]
        url = urlparse.urlparse(request.form['url'])
        args = MultiDict(urlparse.parse_qsl(url.query))
        response = jsonapi.get_related(db, args, 'vcfs', vcf_id, 'calls')
        title = request.form.get('title')
        if response.status == requests.codes.ok:
            report = Report(title)
            report.vcfs = [VCF.query.get(vcf_id)]
            report.creator = current_user
            report.project = Project.query.get(request.form.get('project'))
            report.panels = Panel.query.filter(Panel.id.in_(request.form.get('panels').split(','))).all()
            report.fisher = request.form.get('fisher')
            report.artifact = request.form.get('artifact')
            report.frequency = request.form.get('frequency')
            report.depth = request.form.get('depth')
            report.content = cPickle.dumps(response.document)
            db.add(report)
            try:
                db.commit()
            except SQLAlchemyError:
                flash("Error saving report: '{0}'. Please try again later.".format(title), category='danger')
            else:
                flash("Report: '{0}' saved successfully.".format(title), category='success')

    admin = current_user.is_authenticated and PERMISSION.MANAGE_REPORT_REQUEST in current_user.permissions
    return render_template('reports/index.html', admin=admin)
Beispiel #4
0
def index():
    user = {'username': '******'}
    posts = [
        {
            'author': {'username': '******'},
            'body': 'Beautiful day in Portland!'
        },
        {
            'author': {'username': '******'},
            'body': 'The Avengers movie was so cool!'
        }
    ]
    form = FlaskForm()
    if form.validate_on_submit():
        # print(form)
        baseurl = request.values.get('baseurl')
        # baseurl = "https://movie.douban.com/people/JiaU_Dong/collect"
        flash('Douban Movie Profile URL {}'.format(
            baseurl))
        mvlst = crawler.main(baseurl)

        # return render_template('base.html', title='Home', user=user,
        #                    posts=posts, form=form, mvlst=mvlst)
        # return jsonify(mvlst)
        global mvjs
        mvjs = json.dumps(mvlst, ensure_ascii=False)
        return
    else:
        return render_template('base.html', title='Home', user=user,
                               posts=posts, form=form)
Beispiel #5
0
def wtf1():
    form = FlaskForm()
    if form.validate_on_submit():  # 如果表单中有数据则传到session['name']里保存
        session['name'] = form.name.data
        # print(session['name'])
        return redirect(url_for('wtf1'))  # 保存到session['name']后重定向
    return render_template('wtf.html', form=form, name=session.get('name'))
Beispiel #6
0
def confirmar_atividade(codigo):
    permissoes = current_user.getPermissoes()
    if "MINISTRANTE" in permissoes or "CONTEUDO" in permissoes or current_user.is_admin(
    ):
        form_login = LoginForm(request.form)
        permitido, atividade, emails = valida_url_codigo(current_user, codigo)
        ministrante = current_user.ministrante
        r_atividade_ministrante = (
            db.session.query(RelacaoAtividadeMinistrante).filter_by(
                id_ministrante=ministrante.id,
                id_atividade=atividade.id).first())
        if permitido == True and r_atividade_ministrante.confirmado is not False:
            form = FlaskForm(request.form)
            if form.validate_on_submit():
                confirmar = request.form.getlist("confirmar")[0]
                r_atividade_ministrante.confirmado = bool(confirmar == "1")
                db.session.add(r_atividade_ministrante)
                db.session.commit()
                return redirect(url_for("conteudo.cadastro_sucesso"))
            return render_template(
                "conteudo/confirmar_atividade.html",
                codigo=codigo,
                titulo_atividade=atividade.titulo,
                form=form,
                form_login=form_login,
            )
    abort(404)
    def group_delete(groupname):
        title = "Delete group"

        if not ldap_group_exists(groupname):
            abort(404)

        form = FlaskForm(request.form)

        if form.validate_on_submit():
            try:
                group = ldap_get_group(groupname=groupname)
                ldap_delete_entry(group['distinguishedName'])
                flash(u"Group removed successfully.", "success")
                return redirect(url_for('core_index'))
            except ldap.LDAPError as e:
                error = e.message['info'].split(":", 2)[-1].strip()
                error = str(error[0].upper() + error[1:])
                flash(error, "error")
        elif form.errors:
            flash(u"Data validation failed.", "error")

        return render_template("pages/group_delete_es.html",
                               title=title,
                               action="Delete group",
                               form=form,
                               groupname=groupname,
                               parent=url_for('group_overview',
                                              groupname=groupname))
def delete_user_profile():
    """
    On get returns "delete profile" page to confirm if user really wants to delete their profile.
    On post deletes user profile. Note all user's ads will be automatically deleted as well because this
    is how database is setup (there is an automatic delete cascade for user->ad objects).
    :return:
    """
    user = flask_login.current_user
    delete_user_profile_form = FlaskForm()
    if request.method == 'POST' and delete_user_profile_form.validate_on_submit(
    ):
        if not user_is_authorized_to_update_item(user.id):
            flash("You are not authorized to update this page")
            return redirect(url_for("index"))

        user_email = user.email
        user_id = user.id
        database.set_user_authenticated_status(user, False)
        flask_login.logout_user()
        database.delete_user(database.get_user_by_unicode_id(user_id))

        flash("User account for " + user_email +
              "and all ads for this account were deleted.")
        return redirect(url_for("index"))

    return render_template("delete_user_profile.html",
                           user=user,
                           delete_user_profile_form=delete_user_profile_form,
                           page_info=get_page_info())
def new_ad():
    """
    Creates new ad from user inputs
    :return: on get add page; on post add  and redirects to my ads page ; on get  returns partly filled in template
    """

    # using FlaskForm for csrf protection, rest is custom - built
    new_ad_form = FlaskForm()
    if request.method == "POST" and new_ad_form.validate_on_submit():
        ad_new = create_database.Ad(user_id=flask_login.current_user.id)
        update_ad_from_form_info(ad_new, request.form)
        database.update_ad(ad_new)
        flash("New ad was successfully added")
        return redirect(url_for("my_ads"))

    user = database.get_user_by_unicode_id(flask_login.current_user.id)
    new_ad_template = database.get_ad_template(
        user, initialize_city=True, initialize_category_and_subcategory=True)
    categories_with_sub_categories = database.get_categories_with_subcategories(
    )
    cities = database.get_cities()
    categories_json = json.dumps(categories_with_sub_categories)

    selected_sub_categories = categories_with_sub_categories[
        new_ad_template["category"]]["value"]

    return render_template("new_ad.html",
                           ad=new_ad_template,
                           categories_json=categories_json,
                           categories=categories_with_sub_categories,
                           new_ad_form=new_ad_form,
                           selected_sub_categories=selected_sub_categories,
                           cities=cities,
                           page_info=get_page_info())
Beispiel #10
0
def login_func():
    """
    接收登录信息函数
    :return:
    """
    mes = {"message": "success"}
    form = FlaskForm()
    if form.validate_on_submit():
        args = get_args(request)
        args.pop('csrf_token', None)
        try:
            mes = UserInfo.login(**args)
        except Exception as e:
            n = datetime.datetime.now()
            t = "官网登录失败.{}".format(n)
            c = "args:{}, auth:{}, error:{}".format(args, AUTH, e)
            send_mail(title=t, content=c)
            ms = "{} {}".format(t, c)
            logger.exception(msg=ms)
        finally:
            if mes['message'] == "success":
                """登录成功"""
                session['_id'] = mes.pop('_id')  # 保存会话
            else:
                pass
    else:
        mes['message'] = "提交错误,请刷新页面后重试"

    return json.dumps(mes)
Beispiel #11
0
def delete_listens():
    """ Delete all the listens for the currently logged-in user from ListenBrainz.

    If POST request, this view checks for the correct authorization token and
    deletes the listens. If deletion is successful, redirects to user's profile page,
    else flashes an error and redirects to user's info page.

    If GET request, this view renders a page asking the user to confirm that they
    wish to delete their listens.
    """
    form = FlaskForm()
    if form.validate_on_submit():
        try:
            delete_listens_history(current_user.musicbrainz_id)
            flash.info('Successfully deleted listens for %s.' %
                       current_user.musicbrainz_id)
            return redirect(
                url_for('user.profile', user_name=current_user.musicbrainz_id))
        except Exception as e:
            current_app.logger.error('Error while deleting listens for %s: %s',
                                     current_user.musicbrainz_id, str(e))
            flash.error(
                'Error while deleting listens for %s, please try again later.'
                % current_user.musicbrainz_id)
            return redirect(url_for('profile.info'))

    if form.csrf_token.errors:
        flash.error(
            'Cannot delete listens due to error during authentication, please try again later.'
        )
        return redirect(url_for('profile.info'))

    return render_template('profile/delete_listens.html',
                           user=current_user,
                           form=form)
Beispiel #12
0
def switch_delete(switch_id):
    switch = Switch.q.filter_by(host_id=switch_id).one()

    if not switch:
        flash(u"Switch mit ID {} nicht gefunden!".format(switch_id), "error")
        return redirect(url_for('.switches'))

    form = Form()

    if form.validate_on_submit():
        delete_switch(switch, current_user)

        session.session.commit()

        flash("Die Switch wurde erfolgreich gelöscht.", "success")

        return redirect(url_for('.switches'))

    form_args = {
        'form': form,
        'cancel_to': url_for('.switches'),
        'submit_text': 'Löschen',
        'actions_offset': 0
    }

    return render_template('generic_form.html',
                           page_title="Switch löschen",
                           form_args=form_args)
Beispiel #13
0
 def validate_on_submit(self):
     valid = True
     if not FlaskForm.validate_on_submit(self):
         valid = False
         current_app.logger.error(
             'Validity check failed on FlaskForm fields')
     return valid
Beispiel #14
0
def delete():
    """ Delete currently logged-in user from ListenBrainz.

    If POST request, this view checks for the correct authorization token and
    deletes the user. If deletion is successful, redirects to home page, else
    flashes an error and redirects to user's info page.

    If GET request, this view renders a page asking the user to confirm
    that they wish to delete their ListenBrainz account.
    """
    form = FlaskForm()
    if form.validate_on_submit():
        try:
            delete_user(current_user.musicbrainz_id)
            flash.success("Successfully deleted account for %s." %
                          current_user.musicbrainz_id)
            return redirect(url_for('index.index'))
        except Exception:
            current_app.logger.error('Error while deleting user: %s',
                                     current_user.musicbrainz_id,
                                     exc_info=True)
            flash.error(
                'Error while deleting user %s, please try again later.' %
                current_user.musicbrainz_id)
            return redirect(url_for('profile.info'))

    if form.csrf_token.errors:
        flash.error(
            'Cannot delete user due to error during authentication, please try again later.'
        )
        return redirect(url_for('profile.info'))

    return render_template('profile/delete.html', user=current_user, form=form)
Beispiel #15
0
def reset_latest_import_timestamp():
    form = FlaskForm()
    if form.validate_on_submit():
        try:
            listens_importer.update_latest_listened_at(
                current_user.id, ExternalServiceType.LASTFM, 0)
            flash.info(
                "Latest import time reset, we'll now import all your data instead of stopping at your last imported listen."
            )
        except DatabaseException:
            flash.error(
                "Something went wrong! Unable to reset latest import timestamp right now."
            )
        return redirect(url_for("profile.info"))

    if form.csrf_token.errors:
        flash.error(
            'Cannot reset import time due to error during authentication, please try again later.'
        )
        return redirect(url_for('profile.info'))

    return render_template(
        "profile/resetlatestimportts.html",
        form=form,
    )
def edit_ad(ad_id):
    """
    Updates specific ad with user edited information.
    :param ad_id: id of the ad
    :return: either current ad info (on GET) or updated ad (on POST)
    """
    selected_ad = database.get_ad_by_id(int(ad_id))
    if not user_is_authorized_to_update_item(selected_ad.user_id):
        flash("You are not authorized to update this page")
        return redirect(url_for("index"))

    edit_ad_form = FlaskForm()
    if request.method == "POST" and edit_ad_form.validate_on_submit():
        # using FlaskForm only for csrf protection in this case, rest is custom-built
        update_ad_from_form_info(selected_ad, request.form)
        flash("Ad was updated")

    categories_with_sub_categories = database.get_categories_with_subcategories(
    )

    cities = database.get_cities()
    categories_json = json.dumps(categories_with_sub_categories)
    ad_dict = database.ad_to_dict(selected_ad)
    selected_sub_categories = categories_with_sub_categories[
        ad_dict["category"]]["value"]
    return render_template("edit_my_ad.html",
                           ad=ad_dict,
                           categories_json=categories_json,
                           categories=categories_with_sub_categories,
                           selected_sub_categories=selected_sub_categories,
                           cities=cities,
                           edit_ad_form=edit_ad_form,
                           page_info=get_page_info())
def delete_ad(ad_id):
    """
    :param ad_id: ad to be deleted
    :return: on get add page; on post deletes ad and redirects to my ads page
    """
    selected_ad = database.get_ad_by_id(int(ad_id))

    if not user_is_authorized_to_update_item(selected_ad.user_id):
        flash("You are not authorized to update this page")
        return redirect(url_for("login"))

    # Use FlaskForm for csrf protection
    delete_ad_form = FlaskForm()
    if request.method == "POST" and delete_ad_form.validate_on_submit():
        ad_deleted_msg = "Your ad #" + str(selected_ad.id) + " was deleted"
        database.delete_ad(selected_ad)
        flash(ad_deleted_msg)
        return redirect(url_for("my_ads"))

    ad_dict = database.ad_to_dict(selected_ad)

    return render_template("delete_ad.html",
                           ad=ad_dict,
                           page_info=get_page_info(),
                           delete_ad_form=delete_ad_form)
 def validate_on_submit(self):
     current_app.logger.debug('Validating data: {}'.format(self.data))
     valid = True
     if not FlaskForm.validate_on_submit(self):
         valid = False
         current_app.logger.error(
             'Validity check failed on FlaskForm fields')
     return valid
Beispiel #19
0
def logout():
    # Basic form to validate CSRF
    form = FlaskForm()
    if form.validate_on_submit():
        response = redirect(url_for('auth.register'))
        response.set_cookie('remember_me', '', expires=0)
        session.pop('user', None)
        return response
Beispiel #20
0
def movie_delete(movie_id):
    movie = models.Movie.query.get(movie_id)
    form = FlaskForm()
    if not form.validate_on_submit():
        context = {'form': form, 'title': movie.title}
        return render_template('movie_delete.html', **context)
    with models.session() as session:
        session.delete(movie)
    return redirect(url_for('main.movies'))
Beispiel #21
0
    def update_datacite(self):
        """."""
        form = UpdateDataciteForm()
        cancel_or_new_task_form = FlaskForm()

        is_task_running = False
        time = 0
        task_details = current_cache.get('update_datacite:task_details')

        if task_details:
            is_task_running = True
            if cancel_or_new_task_form.validate_on_submit():
                current_cache.set('update_datacite:task_details', None)
                return redirect(url_for('updatedataciteview.update_datacite'))
        else:
            if form.validate_on_submit():
                from_date = request.form['from_date']
                until_date = request.form['until_date']

                action = request.form['action']
                if action == 'SubmitDates':
                    if from_date > until_date:
                        flash("Error: the 'From' date should precede the 'Until' date.")
                    else:
                        pids_count = find_registered_doi_pids(from_date,
                                                                until_date,
                                                                current_app.config['ZENODO_LOCAL_DOI_PREFIXES']).count()
                        task_details = dict(
                            total_pids=pids_count
                        )
                        time = pids_count/current_app.config['DATACITE_UPDATING_RATE_PER_HOUR']

                elif action == 'Confirm':
                    pids_count = find_registered_doi_pids(from_date,
                                                          until_date,
                                                          current_app.config['ZENODO_LOCAL_DOI_PREFIXES']).count()
                    task_details = dict(
                        start_date=datetime.utcnow(),
                        job_id=str(uuid.uuid4()),
                        from_date=from_date,
                        until_date=until_date,
                        total_pids=pids_count,
                        left_pids=pids_count,
                        last_update=datetime.utcnow()
                    )
                    current_cache.set('update_datacite:task_details',
                                      task_details, timeout=-1)
                    return redirect(url_for('updatedataciteview.update_datacite'))

                elif action == 'Cancel':
                    return redirect(url_for('updatedataciteview.update_datacite'))

        return self.render('zenodo_records/update_datacite.html',
                           form=form,
                           cancel_or_new_task_form=cancel_or_new_task_form,
                           details=task_details,
                           is_task_running=is_task_running, time=time)
    def index():
        f = FlaskForm()

        if f.validate_on_submit():
            return 'good'

        if f.errors:
            return f.csrf_token.errors[0]

        return f.csrf_token.current_token
Beispiel #23
0
def clear_skipped_votes() -> Response:
    """Remove any skipped votes to restart the review queue."""
    # There's no form data here, so use a bare FlaskForm just to handle
    # CSRF protection.
    form = FlaskForm()
    if form.validate_on_submit():
        Vote.clear_skipped(user=g.user, commit=True)
        flash(
            "All skipped talks cleared. Choose a category to continue voting.")
    return redirect(url_for("views.vote_home"))
Beispiel #24
0
def delete(title):
    page = WikiPage.query.filter(WikiPage.title == title).first_or_404()
    form = FlaskForm()

    if form.validate_on_submit():
        db.session.delete(page)
        db.session.commit()

        return redirect(url_for('wiki.index'))
    return render_template('delete.html', page=page, form=form)
Beispiel #25
0
def book_delete(book_id):
    book = models.Book.query.get(book_id)
    form = FlaskForm()
    if not form.validate_on_submit():
        context = {'form': form, 'title': book.title}
        return render_template('book_delete.html', **context)
    models.db.session.delete(book)
    models.db.session.commit()
    flash(f'You have deleted {book.title}!')
    return redirect(url_for('main.books'))
Beispiel #26
0
def delete(id):
    item = Transcript.query.get_or_404(id)
    form = FlaskForm()

    if form.validate_on_submit():
        db.session.delete(item)
        db.session.commit()
        return redirect_for('transcript.index')

    return render_template('transcript/delete.html', item=item, form=form)
Beispiel #27
0
def test_flash():
    form = FlaskForm()
    if form.validate_on_submit():
        old_name = session.get('name')
        if old_name is not None and old_name != form.name.data:
            flash('Look like you have change your name!')
        else:
            flash('Welcome %s' % session['name'])
        session['name'] = form.name.data
        return redirect(url_for('test_flash'))
    return render_template('wtf.html', form=form, name=session.get('name'))
Beispiel #28
0
def delete(id):
    item = Salad.query.get_or_404(id)
    form = FlaskForm()

    if form.validate_on_submit():
        item.delete()
        db.session.commit()

        return redirect_for('salad.index')

    return render_template('salad/delete.html', item=item, form=form)
Beispiel #29
0
def delete(dataset_id):
    ds = get_dataset(dataset_id)
    if ds["author"] != current_user.id:
        raise Forbidden("You can't delete this dataset.")

    form = FlaskForm()
    if form.validate_on_submit():
        db.dataset.delete(ds["id"])
        flash.success("Dataset has been deleted.")
        return redirect(url_for("user.profile", musicbrainz_id=current_user.musicbrainz_id))
    else:  # GET
        return render_template("datasets/delete.html", dataset=ds, form=form)
Beispiel #30
0
def email_verification_request():
    """GET|POST /email-verification-request: handle email verification requests
    """
    u = g.user

    form = FlaskForm()
    if form.validate_on_submit():
        send_verification_email(u)
        fn = '/auth/email-verification-request-followup.html'
        return render_template(fn, email=u.email)

    return render_template('/auth/email-verification-request.html', form=form)
Beispiel #31
0
 def validate_on_submit(self, user):
     if FlaskForm.validate_on_submit(self):
         if user.check_password(self.current.data):
             if self.new.data == self.repeat.data:
                 return True
             else:
                 flash("Введённые пароли не совпадают", "error")
         else:
             flash("Введённый пароль не верен", "error")
     else:
         flash("Пароль должен иметь длину от 8 до 30 символов", "error")
     return False
Beispiel #32
0
def email_verification_request():
    """GET|POST /email-verification-request: handle email verification requests
    """
    u = g.user

    form = FlaskForm()
    if form.validate_on_submit():
        send_verification_email(u)
        fn = '/auth/email-verification-request-followup.html'
        return render_template(fn, email=u.email)

    return render_template('/auth/email-verification-request.html', form=form)
Beispiel #33
0
def certgen():
    if request.method == 'GET':
        return redirect(url_for('account_list'))

    form = FlaskForm(request.form)
    if form.validate_on_submit():
        generate_cert()
        trust_cert()

        return shutdown_response()

    return redirect(url_for('account_list'))