Python flask.url_for() Examples

The following are 30 code examples of flask.url_for(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask , or try the search function .
Example #1
Source Project: video2commons   Author: toolforge   File: redisession.py    License: GNU General Public License v3.0 8 votes vote down vote up
def save_session(self, app, session, response):
        """Save session to Redis."""
        domain = self.get_cookie_domain(app)
        path = url_for('main', _external=False)

        if not session:
            self.redis.delete(self.prefix + session.sid)
            if session.modified:
                response.delete_cookie(app.session_cookie_name,
                                       domain=domain, path=path)
        else:
            redis_exp = self.get_redis_expiration_time(app, session)
            cookie_exp = self.get_expiration_time(app, session)
            if session.modified:
                val = self.serializer.dumps(dict(session))
                self.redis.setex(self.prefix + session.sid,
                                 int(redis_exp.total_seconds()), val)
            else:
                self.redis.expire(self.prefix + session.sid,
                                  int(redis_exp.total_seconds()))
            response.set_cookie(app.session_cookie_name, session.sid,
                                expires=cookie_exp, httponly=True,
                                domain=domain, path=path, secure=True) 
Example #2
Source Project: oabot   Author: dissemin   File: app.py    License: MIT License 7 votes vote down vote up
def get_random_edit():
    # Check first that we are logged in
    access_token =flask.session.get('access_token', None)
    if not access_token:
        return flask.redirect(flask.url_for('login', next_url=flask.url_for('get_random_edit')))

    # Then, redirect to a random cached edit
    for page_name in list_cache_contents():
        # Randomly skip or pick the current one, about 1 % chance.
        if random() > 0.01:
            continue

        cache_fname = "cache/"+to_cache_name(page_name)
        with open(cache_fname, 'r') as f:
            page_json = json.load(f)

        proposed_edits = page_json.get('proposed_edits', [])
        proposed_edits = [template_edit for template_edit in proposed_edits if (template_edit['classification'] != 'rejected')]
        if proposed_edits:
            edit_idx = randint(0, len(proposed_edits)-1)
            orig_hash = proposed_edits[edit_idx]['orig_hash']
            return flask.redirect(
                flask.url_for('review_one_edit', name=page_name, edit=orig_hash))

    return flask.redirect(flask.url_for('index')) 
Example #3
Source Project: thewarden   Author: pxsocs   File: routes.py    License: MIT License 7 votes vote down vote up
def portfolio_main():
    transactions = Trades.query.filter_by(user_id=current_user.username)
    if transactions.count() == 0:
        return redirect(url_for("main.get_started"))
    # For now pass only static positions, will update prices and other
    # data through javascript after loaded. This improves load time
    # and refresh speed.
    # Get positions and prepare df for delivery
    df = positions()
    df.set_index('trade_asset_ticker', inplace=True)
    df = df[df['is_currency'] == 0].sort_index(ascending=True)
    df = df.to_dict(orient='index')
    if df is None:
        return redirect(url_for("main.get_started"))
    return render_template("portfolio.html",
                           title="Portfolio Dashboard",
                           portfolio_data=df) 
Example #4
Source Project: thewarden   Author: pxsocs   File: routes.py    License: MIT License 7 votes vote down vote up
def reset_token(token):
    if current_user.is_authenticated:
        return redirect(url_for("main.home"))
    user = User.verify_reset_token(token)
    if user is None:
        flash("That is an invalid or expired token", "warning")
        return redirect(url_for("users.reset_request"))
    form = ResetPasswordForm()
    if form.validate_on_submit():
        hash = generate_password_hash(form.password.data)
        user.password = hash
        db.session.commit()
        flash("Your password has been updated! You are now able to log in",
              "success")
        return redirect(url_for("users.login"))
    return render_template("reset_token.html",
                           title="Reset Password",
                           form=form) 
Example #5
Source Project: comport   Author: codeforamerica   File: test_public_pages.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_non_public_depts_display_for_users_with_access(self, testapp):
        ''' Users can see links to datasets they're allowed to access on the front page
        '''
        impd = Department.create(name="I Police Department", short_name="IMPD", is_public=True)
        UseOfForceIncidentIMPD.create(department_id=impd.id, opaque_id="12345abcde")
        bpd = Department.create(name="B Police Department", short_name="BPD", is_public=False)
        UseOfForceIncidentBPD.create(department_id=bpd.id, opaque_id="12345abcde")
        lmpd = Department.create(name="LM Police Department", short_name="LMPD", is_public=False)
        UseOfForceIncidentLMPD.create(department_id=lmpd.id, opaque_id="12345abcde")

        # A non logged-in user can only see the public department
        response = testapp.get("/", status=200)
        soup = BeautifulSoup(response.text, "html.parser")
        assert soup.find("a", href="/department/IMPD/useofforce") is not None
        assert soup.find("a", href="/department/BPD/useofforce") is None
        assert soup.find("a", href="/department/LMPD/useofforce") is None

        # A user associated with a particular department can see that department's
        # available datasets when logged in
        create_and_log_in_user(testapp=testapp, department=bpd, username="user1")
        response = testapp.get("/", status=200)
        soup = BeautifulSoup(response.text, "html.parser")
        assert soup.find("a", href="/department/IMPD/useofforce") is not None
        assert soup.find("a", href="/department/BPD/useofforce") is not None
        assert soup.find("a", href="/department/LMPD/useofforce") is None

        # A user with admin access can see all departments' available datasets
        create_and_log_in_user(testapp=testapp, department=impd, rolename='admin', username="user2")
        response = testapp.get("/", status=200)
        soup = BeautifulSoup(response.text, "html.parser")
        assert soup.find("a", href="/department/IMPD/useofforce") is not None
        assert soup.find("a", href="/department/BPD/useofforce") is not None
        assert soup.find("a", href="/department/LMPD/useofforce") is not None

        # Log out and only the public department should be visible
        testapp.get(url_for('public.logout')).follow()
        response = testapp.get("/", status=200)
        soup = BeautifulSoup(response.text, "html.parser")
        assert soup.find("a", href="/department/IMPD/useofforce") is not None
        assert soup.find("a", href="/department/BPD/useofforce") is None
        assert soup.find("a", href="/department/LMPD/useofforce") is None 
Example #6
Source Project: oabot   Author: dissemin   File: app.py    License: MIT License 6 votes vote down vote up
def login():
    """Initiate an OAuth login.

    Call the MediaWiki server to get request secrets and then redirect
the
    user to the MediaWiki server to sign the request.
    """
    consumer_token = mwoauth.ConsumerToken(
        app.config['CONSUMER_KEY'], app.config['CONSUMER_SECRET'])
    try:
        redirect, request_token = mwoauth.initiate(
            app.config['OAUTH_MWURI'], consumer_token)
    except Exception:
        app.logger.exception('mwoauth.initiate failed')
        return flask.redirect(flask.url_for('index'))
    else:
        flask.session['request_token'] = dict(zip(
            request_token._fields, request_token))
        return flask.redirect(redirect) 
Example #7
Source Project: thewarden   Author: pxsocs   File: routes.py    License: MIT License 6 votes vote down vote up
def login():
    if current_user.is_authenticated:
        return redirect(url_for("main.home"))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user and check_password_hash(user.password, form.password.data):
            login_user(user, remember=form.remember.data)
            # The get method below is actually very helpful
            # it returns None if empty. Better than using [] for a dictionary.
            next_page = request.args.get("next")  # get the original page
            if next_page:
                return redirect(next_page)
            else:
                return redirect(url_for("main.home"))
        else:
            flash("Login failed. Please check e-mail and password", "danger")

    return render_template("login.html", title="Login", form=form) 
Example #8
Source Project: thewarden   Author: pxsocs   File: routes.py    License: MIT License 6 votes vote down vote up
def reset_request():
    if current_user.is_authenticated:
        return redirect(url_for("main.home"))
    form = RequestResetForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        send_reset_email(user)
        flash(
            "An email has been sent with instructions to reset your" +
            " password.",
            "info",
        )
        return redirect(url_for("users.login"))
    return render_template("reset_request.html",
                           title="Reset Password",
                           form=form) 
Example #9
Source Project: thewarden   Author: pxsocs   File: routes.py    License: MIT License 6 votes vote down vote up
def delete_baccount(id):
    # type = account or address
    account = None
    type = request.args.get("type")
    if type == "account":
        account = AccountInfo.query.filter_by(
            user_id=current_user.username).filter_by(account_id=id)
    if type == "address":
        account = BitcoinAddresses.query.filter_by(
            user_id=current_user.username).filter_by(address_id=id)

    if (account is None) or (account.count() == 0):
        flash(f"{type.capitalize()} id: {id} not found. Nothing done.",
              "warning")
        return redirect(url_for("node.bitcoin_monitor"))
    if account.first().user_id != current_user.username:
        abort(403)

    account.delete()
    db.session.commit()
    flash(f"{type.capitalize()} deleted", "danger")
    return redirect(url_for("node.bitcoin_monitor")) 
Example #10
Source Project: circleci-demo-python-flask   Author: CircleCI-Public   File: users.py    License: MIT License 6 votes vote down vote up
def get_user_posts(id):
    user = User.query.get_or_404(id)
    page = request.args.get('page', 1, type=int)
    pagination = user.posts.order_by(Post.timestamp.desc()).paginate(
        page, per_page=current_app.config['CIRCULATE_POSTS_PER_PAGE'],
        error_out=False)
    posts = pagination.items
    prev = None
    if pagination.has_prev:
        prev = url_for('api.get_user_posts', page=page-1, _external=True)
    next = None
    if pagination.has_next:
        next = url_for('api.get_user_posts', page=page+1, _external=True)
    return jsonify({
        'posts': [post.to_json() for post in posts],
        'prev': prev,
        'next': next,
        'count': pagination.total
    }) 
Example #11
Source Project: circleci-demo-python-flask   Author: CircleCI-Public   File: users.py    License: MIT License 6 votes vote down vote up
def get_user_followed_posts(id):
    user = User.query.get_or_404(id)
    page = request.args.get('page', 1, type=int)
    pagination = user.followed_posts.order_by(Post.timestamp.desc()).paginate(
        page, per_page=current_app.config['CIRCULATE_POSTS_PER_PAGE'],
        error_out=False)
    posts = pagination.items
    prev = None
    if pagination.has_prev:
        prev = url_for('api.get_user_followed_posts', page=page-1,
                       _external=True)
    next = None
    if pagination.has_next:
        next = url_for('api.get_user_followed_posts', page=page+1,
                       _external=True)
    return jsonify({
        'posts': [post.to_json() for post in posts],
        'prev': prev,
        'next': next,
        'count': pagination.total
    }) 
Example #12
Source Project: circleci-demo-python-flask   Author: CircleCI-Public   File: comments.py    License: MIT License 6 votes vote down vote up
def get_comments():
    page = request.args.get('page', 1, type=int)
    pagination = Comment.query.order_by(Comment.timestamp.desc()).paginate(
        page, per_page=current_app.config['CIRCULATE_COMMENTS_PER_PAGE'],
        error_out=False)
    comments = pagination.items
    prev = None
    if pagination.has_prev:
        prev = url_for('api.get_comments', page=page-1, _external=True)
    next = None
    if pagination.has_next:
        next = url_for('api.get_comments', page=page+1, _external=True)
    return jsonify({
        'comments': [comment.to_json() for comment in comments],
        'prev': prev,
        'next': next,
        'count': pagination.total
    }) 
Example #13
Source Project: circleci-demo-python-flask   Author: CircleCI-Public   File: comments.py    License: MIT License 6 votes vote down vote up
def get_post_comments(id):
    post = Post.query.get_or_404(id)
    page = request.args.get('page', 1, type=int)
    pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(
        page, per_page=current_app.config['CIRCULATE_COMMENTS_PER_PAGE'],
        error_out=False)
    comments = pagination.items
    prev = None
    if pagination.has_prev:
        prev = url_for('api.get_post_comments', page=page-1, _external=True)
    next = None
    if pagination.has_next:
        next = url_for('api.get_post_comments', page=page+1, _external=True)
    return jsonify({
        'comments': [comment.to_json() for comment in comments],
        'prev': prev,
        'next': next,
        'count': pagination.total
    }) 
Example #14
Source Project: circleci-demo-python-flask   Author: CircleCI-Public   File: views.py    License: MIT License 6 votes vote down vote up
def password_reset_request():
    if not current_user.is_anonymous:
        return redirect(url_for('main.index'))
    form = PasswordResetRequestForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user:
            token = user.generate_reset_token()
            send_email(user.email, 'Reset Your Password',
                       'auth/email/reset_password',
                       user=user, token=token,
                       next=request.args.get('next'))
        flash('An email with instructions to reset your password has been '
              'sent to you.')
        return redirect(url_for('auth.login'))
    return render_template('auth/reset_password.html', form=form) 
Example #15
Source Project: circleci-demo-python-flask   Author: CircleCI-Public   File: test_api.py    License: MIT License 6 votes vote down vote up
def test_users(self):
        # add two users
        r = Role.query.filter_by(name='User').first()
        self.assertIsNotNone(r)
        u1 = User(email='john@example.com', username='john',
                  password='cat', confirmed=True, role=r)
        u2 = User(email='susan@example.com', username='susan',
                  password='dog', confirmed=True, role=r)
        db.session.add_all([u1, u2])
        db.session.commit()

        # get users
        response = self.client.get(
            url_for('api.get_user', id=u1.id),
            headers=self.get_api_headers('susan@example.com', 'dog'))
        self.assertTrue(response.status_code == 200)
        json_response = json.loads(response.data.decode('utf-8'))
        self.assertTrue(json_response['username'] == 'john')
        response = self.client.get(
            url_for('api.get_user', id=u2.id),
            headers=self.get_api_headers('susan@example.com', 'dog'))
        self.assertTrue(response.status_code == 200)
        json_response = json.loads(response.data.decode('utf-8'))
        self.assertTrue(json_response['username'] == 'susan') 
Example #16
Source Project: Mastering-Python-Networking-Second-Edition   Author: PacktPublishing   File: chapter9_6.py    License: MIT License 5 votes vote down vote up
def get_url(self):
        return url_for('get_device', id=self.id, _external=True) 
Example #17
Source Project: Mastering-Python-Networking-Second-Edition   Author: PacktPublishing   File: chapter9_7.py    License: MIT License 5 votes vote down vote up
def get_url(self):
        return url_for('get_device', id=self.id, _external=True) 
Example #18
Source Project: everyclass-server   Author: everyclass   File: views_api.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def get_calendar_token(id_sec: str, semester: str):
    """

    :param id_sec: 加密后的学号或教工号
    :param semester: 学期,如 2018-2019-1

    错误码:
    4000 请求无效
    4003 无权访问
    """
    try:
        res_type, res_id = encryption.decrypt(id_sec)
    except ValueError:
        return generate_error_response(None, api_helpers.STATUS_CODE_INVALID_REQUEST, '用户ID无效')

    if res_type == encryption.RTYPE_STUDENT:
        if not user_service.has_access(res_id, g.username)[0]:
            return generate_error_response(None, api_helpers.STATUS_CODE_PERMISSION_DENIED, '无权访问该用户课表')
        student = entity_service.get_student_timetable(res_id, semester)
        if not student:
            return generate_error_response(None, api_helpers.STATUS_CODE_INVALID_REQUEST, '学生不存在')
        token = calendar_service.get_calendar_token(resource_type=res_type,
                                                    identifier=student.student_id,
                                                    semester=semester)
    else:
        teacher = entity_service.get_teacher_timetable(res_id, semester)
        if not teacher:
            return generate_error_response(None, api_helpers.STATUS_CODE_INVALID_REQUEST, '教师不存在')
        token = calendar_service.get_calendar_token(resource_type=res_type,
                                                    identifier=teacher.teacher_id,
                                                    semester=semester)

    ics_url = url_for('calendar.ics_download', calendar_token=token, _external=True)
    ics_webcal = ics_url.replace('https', 'webcal').replace('http', 'webcal')
    return generate_success_response({'token': token,
                                      'ics_url': ics_url,
                                      'ics_url_webcal': ics_webcal}) 
Example #19
Source Project: everyclass-server   Author: everyclass   File: views.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def register_choice():
    """注册:第二步:选择注册方式"""
    if not session.get(SESSION_USER_REGISTERING, None):  # 步骤异常,跳回第一步
        return redirect(url_for('user.register'))
    return render_template('user/registerChoice.html') 
Example #20
Source Project: everyclass-server   Author: everyclass   File: views.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def register_by_password_status():
    """AJAX 刷新教务验证状态"""
    if not request.args.get("request", None) or not isinstance(request.args["request"], str):
        return "Invalid request"

    try:
        success, message, identifier = user_service.register_by_password_status_refresh(request.args.get("request"))

        if success:
            # write login state to session
            flash(MSG_REGISTER_SUCCESS)
            if SESSION_PWD_VER_REQ_ID in session:
                del session[SESSION_PWD_VER_REQ_ID]

            _set_current_user(identifier)  # potential uncaught error
            return jsonify({"message": "SUCCESS"})
        elif message in ("PASSWORD_WRONG", "INTERNAL_ERROR", "INVALID_REQUEST_ID"):
            return jsonify({"message": message})
        else:
            return jsonify({"message": "NEXT_TIME"})

    except everyclass.server.user.exceptions.IdentityVerifyRequestNotFoundError:
        return "Invalid request"
    except user_service.IdentityVerifyMethodNotExpectedError:
        return "Invalid request"
    except everyclass.server.user.exceptions.AlreadyRegisteredError:
        # 已经注册成功,但不知为何(可能是网络原因)进入了中间状态,没有执行下面的删除 session 的代码,并且用户刷新页面
        if SESSION_PWD_VER_REQ_ID in session:
            del session[SESSION_PWD_VER_REQ_ID]
        flash(MSG_ALREADY_REGISTERED)
        return redirect(url_for('user.login')) 
Example #21
Source Project: everyclass-server   Author: everyclass   File: views.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def register_by_password_success():
    """验证成功后跳转到用户首页"""
    return redirect(url_for("user.main")) 
Example #22
Source Project: everyclass-server   Author: everyclass   File: views.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def logout():
    """用户退出登录"""
    del session[SESSION_CURRENT_USER]
    flash("退出登录成功。")
    return redirect(url_for('main.main')) 
Example #23
Source Project: MPContribs   Author: materialsproject   File: views.py    License: MIT License 5 votes vote down vote up
def applications(token, action):
    ts = current_app.config["USTS"]
    max_age = current_app.config["USTS_MAX_AGE"]
    try:
        owner, project = ts.loads(token, max_age=max_age)
    except SignatureExpired:
        return f"signature for {owner} of {project} expired."

    try:
        obj = Projects.objects.get(project=project, owner=owner, is_approved=False)
    except DoesNotExist:
        return f"{project} for {owner} already approved or denied."

    actions = ["approve", "deny"]
    if action not in actions:
        response = f"<h3>{project}</h3><ul>"
        scheme = "http" if current_app.config["DEBUG"] else "https"
        for a in actions:
            u = url_for(
                "projects.applications",
                token=token,
                action=a,
                _scheme=scheme,
                _external=True,
            )
            response += f'<li><a href="{u}">{a}</a></li>'
        return response + "</ul>"

    if action == "approve":
        obj.is_approved = True
        obj.save()  # post_save (created=False) sends notification when `is_approved` set
    else:
        obj.delete()  # post_delete signal sends notification

    return f'{project} {action.replace("y", "ie")}d and {owner} notified.' 
Example #24
Source Project: flask-session-tutorial   Author: hackersandslackers   File: auth.py    License: MIT License 5 votes vote down vote up
def signup():
    """
    Sign-up form to create new user accounts.
    GET: Serve sign-up page.
    POST: Validate form, create account, redirect user to dashboard.
    """
    form = SignupForm()
    if form.validate_on_submit():
        existing_user = User.query.filter_by(email=form.email.data).first()
        if existing_user is None:
            user = User(
                name=form.name.data,
                email=form.email.data,
                website=form.website.data
            )
            user.set_password(form.password.data)
            db.session.add(user)
            db.session.commit()  # Create new user
            login_user(user)  # Log in as newly created user
            print(user)
            return redirect(url_for('main_bp.dashboard'))
        flash('A user already exists with that email address.')
    return render_template(
        'signup.jinja2',
        title='Create an Account.',
        form=form,
        template='signup-page',
        body="Sign up for a user account."
    ) 
Example #25
Source Project: flask-session-tutorial   Author: hackersandslackers   File: auth.py    License: MIT License 5 votes vote down vote up
def login():
    """
    Log-in page for registered users.
    GET: Serve Log-in page.
    POST: Validate form and redirect user to dashboard.
    """
    if current_user.is_authenticated:
        return redirect(url_for('main_bp.dashboard'))  # Bypass if user is logged in

    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()  # Validate Login Attempt
        if user and user.check_password(password=form.password.data):
            login_user(user)
            next_page = request.args.get('next')
            return redirect(next_page or url_for('main_bp.dashboard'))
        flash('Invalid username/password combination')
        return redirect(url_for('auth_bp.login'))
    return render_template(
        'login.jinja2',
        form=form,
        title='Log in.',
        template='login-page',
        body="Log in with your User account."
    ) 
Example #26
Source Project: flask-session-tutorial   Author: hackersandslackers   File: auth.py    License: MIT License 5 votes vote down vote up
def unauthorized():
    """Redirect unauthorized users to Login page."""
    flash('You must be logged in to view that page.')
    return redirect(url_for('auth_bp.login')) 
Example #27
Source Project: flask-session-tutorial   Author: hackersandslackers   File: routes.py    License: MIT License 5 votes vote down vote up
def logout():
    """User log-out logic."""
    logout_user()
    return redirect(url_for('auth_bp.login')) 
Example #28
Source Project: comport   Author: codeforamerica   File: views.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def start_password_reset(user_id):
    user = User.get_by_id(user_id)
    if not user:
        abort(404)

    if request.method == 'POST':
        user.password_reset_uuid = str(uuid.uuid4())
        user.save()
        flash('User password reset engaged.', 'info')
        return redirect(url_for('admin.edit_user', user_id=user_id))

    return redirect(url_for('admin.edit_user', user_id=user_id)) 
Example #29
Source Project: comport   Author: codeforamerica   File: views.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def delete_demographic_row(department_id, value_id):
    department = Department.get_by_id(department_id)
    value = DemographicValue.get_by_id(value_id)

    if not department or not value:
        abort(404)

    value.delete()

    return redirect(url_for(
        'department.edit_demographics', department_id=department_id
    )) 
Example #30
Source Project: comport   Author: codeforamerica   File: test_functional.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_sees_alert_on_log_out(self, user, testapp):
        res = testapp.get("/login/")
        # Fills out login form in navbar
        form = res.forms['loginForm']
        form['username'] = user.username
        form['password'] = 'myprecious'
        # Submits
        res = form.submit().follow()
        res = testapp.get(url_for('public.logout')).follow()
        # sees alert
        assert 'You are logged out.' in res