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 File: redisession.py    From video2commons with 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 File: routes.py    From thewarden with MIT License 8 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 #3
Source File: routes.py    From thewarden with 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 File: routes.py    From thewarden with MIT License 7 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 #5
Source File: app.py    From oabot with 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 #6
Source File: users.py    From circleci-demo-python-flask with 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 #7
Source File: comments.py    From circleci-demo-python-flask with 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 #8
Source File: comments.py    From circleci-demo-python-flask with 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 #9
Source File: users.py    From circleci-demo-python-flask with 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 #10
Source File: routes.py    From thewarden with 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 #11
Source File: views.py    From circleci-demo-python-flask with 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 #12
Source File: test_public_pages.py    From comport with 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 #13
Source File: app.py    From oabot with 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 #14
Source File: routes.py    From thewarden with 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 #15
Source File: test_api.py    From circleci-demo-python-flask with 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 File: views.py    From llvm-zorg with Apache License 2.0 5 votes vote down vote up
def login():
    # If this isn't a post request, return the login template.
    if request.method != 'POST':
        return render_template("login.html", error=None)

    # Authenticate the user.
    username = request.form['username']
    if not current_app.authenticate_login(username, request.form['password']):
        return render_template("login.html",
                               error="Invalid login")

    # Log the user in.
    session['logged_in'] = True
    session['active_user'] = username
    flask.flash('You were logged in as "%s"!' % username)
    return redirect(url_for("index")) 
Example #17
Source File: utils.py    From thewarden with MIT License 5 votes vote down vote up
def send_reset_email(user):
    token = user.get_reset_token()
    msg = Message('Password Reset Request',
                  sender='cryptoblotterrp@gmail.com',
                  recipients=[user.email])
    msg.body = f'''To reset your password, visit the following link:
                {url_for('users.reset_token', token=token, _external=True)}


                If you did not make this request then simply ignore this email
                 and no changes will be made.
                '''
    mail.send(msg) 
Example #18
Source File: views.py    From llvm-zorg with Apache License 2.0 5 votes vote down vote up
def favicon_ico():
    return redirect(url_for('.static', filename='favicon.ico')) 
Example #19
Source File: test_api.py    From circleci-demo-python-flask with MIT License 5 votes vote down vote up
def test_anonymous(self):
        response = self.client.get(
            url_for('api.get_posts'),
            headers=self.get_api_headers('', ''))
        self.assertTrue(response.status_code == 200) 
Example #20
Source File: test_api.py    From circleci-demo-python-flask with MIT License 5 votes vote down vote up
def test_token_auth(self):
        # add a user
        r = Role.query.filter_by(name='User').first()
        self.assertIsNotNone(r)
        u = User(email='john@example.com', password='cat', confirmed=True,
                 role=r)
        db.session.add(u)
        db.session.commit()

        # issue a request with a bad token
        response = self.client.get(
            url_for('api.get_posts'),
            headers=self.get_api_headers('bad-token', ''))
        self.assertTrue(response.status_code == 401)

        # get a token
        response = self.client.get(
            url_for('api.get_token'),
            headers=self.get_api_headers('john@example.com', 'cat'))
        self.assertTrue(response.status_code == 200)
        json_response = json.loads(response.data.decode('utf-8'))
        self.assertIsNotNone(json_response.get('token'))
        token = json_response['token']

        # issue a request with the token
        response = self.client.get(
            url_for('api.get_posts'),
            headers=self.get_api_headers(token, ''))
        self.assertTrue(response.status_code == 200) 
Example #21
Source File: test_api.py    From circleci-demo-python-flask with MIT License 5 votes vote down vote up
def test_no_auth(self):
        response = self.client.get(url_for('api.get_posts'),
                                   content_type='application/json')
        self.assertTrue(response.status_code == 200) 
Example #22
Source File: views.py    From circleci-demo-python-flask with MIT License 5 votes vote down vote up
def change_email(token):
    if current_user.change_email(token):
        flash('Your email address has been updated.')
    else:
        flash('Invalid request.')
    return redirect(url_for('main.index')) 
Example #23
Source File: test_api.py    From circleci-demo-python-flask with MIT License 5 votes vote down vote up
def test_unconfirmed_account(self):
        # add an unconfirmed user
        r = Role.query.filter_by(name='User').first()
        self.assertIsNotNone(r)
        u = User(email='john@example.com', password='cat', confirmed=False,
                 role=r)
        db.session.add(u)
        db.session.commit()

        # get list of posts with the unconfirmed account
        response = self.client.get(
            url_for('api.get_posts'),
            headers=self.get_api_headers('john@example.com', 'cat'))
        self.assertTrue(response.status_code == 403) 
Example #24
Source File: models.py    From circleci-demo-python-flask with MIT License 5 votes vote down vote up
def to_json(self):
        json_user = {
            'url': url_for('api.get_user', id=self.id, _external=True),
            'username': self.username,
            'member_since': self.member_since,
            'last_seen': self.last_seen,
            'posts': url_for('api.get_user_posts', id=self.id, _external=True),
            'followed_posts': url_for('api.get_user_followed_posts',
                                      id=self.id, _external=True),
            'post_count': self.posts.count()
        }
        return json_user 
Example #25
Source File: posts.py    From circleci-demo-python-flask with MIT License 5 votes vote down vote up
def new_post():
    post = Post.from_json(request.json)
    post.author = g.current_user
    db.session.add(post)
    db.session.commit()
    return jsonify(post.to_json()), 201, \
        {'Location': url_for('api.get_post', id=post.id, _external=True)} 
Example #26
Source File: comments.py    From circleci-demo-python-flask with MIT License 5 votes vote down vote up
def new_post_comment(id):
    post = Post.query.get_or_404(id)
    comment = Comment.from_json(request.json)
    comment.author = g.current_user
    comment.post = post
    db.session.add(comment)
    db.session.commit()
    return jsonify(comment.to_json()), 201, \
        {'Location': url_for('api.get_comment', id=comment.id,
                             _external=True)} 
Example #27
Source File: routes.py    From thewarden with MIT License 5 votes vote down vote up
def register():
    if current_user.is_authenticated:
        return redirect(url_for("main.home"))
    form = RegistrationForm()
    if form.validate_on_submit():
        hash = generate_password_hash(form.password.data)
        user = User(username=form.username.data,
                    email=form.email.data,
                    password=hash)
        db.session.add(user)
        db.session.commit()
        flash(f"Account created for {form.username.data}.", "success")
        return redirect(url_for("users.login"))
    return render_template("register.html", title="Register", form=form) 
Example #28
Source File: routes.py    From thewarden with MIT License 5 votes vote down vote up
def logout():
    logout_user()
    return redirect(url_for("main.home")) 
Example #29
Source File: routes.py    From thewarden with MIT License 5 votes vote down vote up
def delacc():
    if request.method == "GET":
        id = request.args.get("id")
        trade = Trades.query.filter_by(id=id)
        if trade[0].user_id != current_user.username:
            abort(403)

        AccountInfo.query.filter_by(account_id=id).delete()
        db.session.commit()
        flash("Account deleted", "danger")
        return redirect(url_for("transactions.tradeaccounts"))

    else:
        return redirect(url_for("transactions.tradeaccounts")) 
Example #30
Source File: models.py    From circleci-demo-python-flask with MIT License 5 votes vote down vote up
def to_json(self):
        json_comment = {
            'url': url_for('api.get_comment', id=self.id, _external=True),
            'post': url_for('api.get_post', id=self.post_id, _external=True),
            'body': self.body,
            'body_html': self.body_html,
            'timestamp': self.timestamp,
            'author': url_for('api.get_user', id=self.author_id,
                              _external=True),
        }
        return json_comment