Python flask.redirect() Examples

The following are 30 code examples of flask.redirect(). 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: 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 #2
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 #3
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 #4
Source Project: zmirror   Author: aploium   File: custom_func.sample.py    License: MIT License 6 votes vote down vote up
def custom_prior_redirect_func(request, parse):
    """
    用于在 prior_request_redirect 阶段的自定义重定向

    若返回一个 flask.Response 对象, 则执行重定向, 直接返回这个 Response
    若返回None, 则不进行重定向

    不应该修改parse变量 (添加头和cookie除外)

    详见 `config_default.py` 中 `Custom Redirection` 部分

    :param request: flask request object
    :type request: Request
    :param parse: the zmirror parse variable
    :type parse: ZmirrorThreadLocal
    :rtype: Union[Response, None]
    """
    print(request.url, parse.remote_url)

    from flask import redirect

    # 如果你想重定向, 请使用这句
    # return redirect("/location/you/want/redirect/to")

    return None  # 不进行自定义重定向 
Example #5
Source Project: unicorn-binance-websocket-api   Author: oliver-zehentleitner   File: unicorn_binance_websocket_api_manager.py    License: MIT License 6 votes vote down vote up
def _start_monitoring_api_thread(self, host, port, warn_on_update):
        """
        Threaded method that servces the monitoring api

        :param host: IP or hostname to use
        :type host: str
        :param port: Port to use
        :type port: int
        :param warn_on_update: Should the monitoring system report available updates?
        :type warn_on_update: bool
        """
        logging.info("Starting monitoring API service ...")
        app = Flask(__name__)
        @app.route('/')
        @app.route('/status/')
        def redirect_to_wiki():
            logging.debug("Visit https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/wiki/UNICORN-"
                          "Monitoring-API-Service for further information!")
            return redirect("https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/wiki/"
                            "UNICORN-Monitoring-API-Service", code=302)

        api = Api(app)
        api.add_resource(BinanceWebSocketApiRestServer,
                         "/status/<string:statusformat>/",
                         "/status/<string:statusformat>/<string:checkcommandversion>",
                         resource_class_kwargs={'handler_binance_websocket_api_manager': self,
                                                'warn_on_update': warn_on_update})
        try:
            dispatcher = wsgi.PathInfoDispatcher({'/': app})
            self.monitoring_api_server = wsgi.WSGIServer((host, port), dispatcher)
            self.monitoring_api_server.start()
        except RuntimeError as error_msg:
            logging.critical("Monitoring API service is going down! - Info: " + str(error_msg))
        except OSError as error_msg:
            logging.critical("Monitoring API service is going down! - Info: " + str(error_msg)) 
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: 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 #11
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 #12
Source Project: everyclass-server   Author: everyclass   File: views.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def register_by_email():
    """注册:第三步:使用邮箱验证注册"""
    if not session.get(SESSION_USER_REGISTERING, None):  # 步骤异常,跳回第一步
        return redirect(url_for('user.register'))

    identifier = session[SESSION_USER_REGISTERING].identifier

    try:
        request_id = user_service.register_by_email(identifier)
    except Exception as e:
        return handle_exception_with_error_page(e)
    else:
        return render_template('user/emailSent.html', request_id=request_id) 
Example #13
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 #14
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 #15
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 #16
Source Project: everyclass-server   Author: everyclass   File: views.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def reset_calendar_token():
    """重置日历订阅令牌"""
    calendar_service.reset_calendar_tokens(session[SESSION_CURRENT_USER].identifier)
    flash("日历订阅令牌重置成功")
    return redirect(url_for("user.main")) 
Example #17
Source Project: zmirror   Author: aploium   File: zmirror.py    License: MIT License 5 votes vote down vote up
def filter_client_request():
    """过滤用户请求, 视情况拒绝用户的访问
    :rtype: Union[Response, None]
    """
    dbgprint('Client Request Url: ', request.url)

    # crossdomain.xml
    if os.path.basename(request.path) == 'crossdomain.xml':
        dbgprint('crossdomain.xml hit from', request.url)
        return crossdomain_xml()

    # Global whitelist ua
    if check_global_ua_pass(str(request.user_agent)):
        return None

    if is_deny_spiders_by_403 and is_denied_because_of_spider(str(request.user_agent)):
        return generate_simple_resp_page(b'Spiders Are Not Allowed To This Site', 403)

    if human_ip_verification_enabled and (
                ((human_ip_verification_whitelist_from_cookies or enable_custom_access_cookie_generate_and_verify)
                 and must_verify_cookies)
            or is_ip_not_in_allow_range(request.remote_addr)
    ):
        dbgprint('ip', request.remote_addr, 'is verifying cookies')
        if 'zmirror_verify' in request.cookies and \
                ((human_ip_verification_whitelist_from_cookies and verify_ip_hash_cookie(request.cookies.get('zmirror_verify')))
                 or (enable_custom_access_cookie_generate_and_verify and custom_verify_access_cookie(
                        request.cookies.get('zmirror_verify'), request))):
            ip_whitelist_add(request.remote_addr, info_record_dict=request.cookies.get('zmirror_verify'))
            dbgprint('add to ip_whitelist because cookies:', request.remote_addr)
        else:
            return redirect(
                "/ip_ban_verify_page?origin=" + base64.urlsafe_b64encode(str(request.url).encode(encoding='utf-8')).decode(
                    encoding='utf-8'),
                code=302)

    return None 
Example #18
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 #19
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 #20
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 #21
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 #22
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 #23
Source Project: comport   Author: codeforamerica   File: decorators.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def admin_or_department_required():
    '''
    Reads department from current_user and checks whether the user
    has access to that department or is an admin
    '''
    def check_department(view_function):
        @wraps(view_function)
        def decorated_function(*args, **kwargs):
            if current_user.has_department(kwargs["department_id"]) or current_user.is_admin():
                return view_function(*args, **kwargs)
            flash('You do not have sufficient permissions to do that', 'alert alert-danger')
            return redirect(request.args.get('next') or '/')
        return decorated_function
    return check_department 
Example #24
Source Project: comport   Author: codeforamerica   File: views.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def delete_denominator_row(department_id, value_id):
    department = Department.get_by_id(department_id)
    value = DenominatorValue.get_by_id(value_id)

    if not department or not value:
        abort(404)

    value.delete()

    return redirect(url_for(
        'department.edit_denominators', department_id=department_id
    )) 
Example #25
Source Project: password_pwncheck   Author: CboeSecurity   File: password-pwncheck.py    License: MIT License 5 votes vote down vote up
def catch_all(path):
    return redirect('https://www.youtube.com/watch?v=dQw4w9WgXcQ' ,code=301)

###########################################################
##################### MAIN ################################
########################################################### 
Example #26
Source Project: ptnotes   Author: averagesecurityguy   File: webserver.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def import_scan(pid):
    """
    Import scan data into the database associated with the pid.
    """
    project = get_project_db(pid)
    db = database.ScanDatabase(project['dbfile'])

    if flask.request.method == 'GET':
        files = db.importdb.get_imported_files()

        return flask.render_template('import.html', pid=pid, files=files,
                    name=project['name'])

    else:
        i = importscan.Import(project['dbfile'])
        scans = flask.request.files.getlist("scans[]")

        for scan in scans:
            res = i.import_scan(scan.read())
            if res is True:
                db.importdb.add_import_file(scan.filename)

        a = attacks.Attack(project['dbfile'])
        a.find_attacks()

        return flask.redirect(flask.url_for('get_project', pid=pid)) 
Example #27
Source Project: ptnotes   Author: averagesecurityguy   File: webserver.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def project_notes(pid):
    """
    Display all project notes.
    """
    pdb = database.ProjectDatabase()
    project = get_project_db(pid)

    if flask.request.method == 'POST':
        note = flask.request.form['note']
        pdb.update_project_note(pid, note)

        return flask.redirect(flask.url_for('get_project', pid=pid))
    else:
        return flask.render_template('project_notes.html', pid=pid,
                    name=project['name'], note=project['note']) 
Example #28
Source Project: ptnotes   Author: averagesecurityguy   File: webserver.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def delete_project(pid):
    """
    Delete the specified project.
    """
    pdb = database.ProjectDatabase()
    project = pdb.delete_project(pid)

    return flask.redirect(flask.url_for('projects')) 
Example #29
Source Project: oabot   Author: dissemin   File: app.py    License: MIT License 5 votes vote down vote up
def index():
    context = {
        'username' : flask.session.get('username', None),
        'success' : flask.request.args.get('success'),
    }
    if context['username']:
        return flask.redirect(flask.url_for('get_random_edit'))
    return flask.render_template("index.html", **context) 
Example #30
Source Project: oabot   Author: dissemin   File: app.py    License: MIT License 5 votes vote down vote up
def get_proposed_edits(page_name, force, follow_redirects=True, only_doi=False):
    # Get the page
    text = main.get_page_over_api(page_name)

    # See if it's a redirect
    redir = redirect_re.match(text)
    if redir:
        return get_proposed_edits(redir.group(1), force, False, only_doi)

    # See if we already have it cached
    cache_fname = "cache/"+to_cache_name(page_name)
    if not force and os.path.isfile(cache_fname):
        with open(cache_fname, 'r') as f:
            return json.load(f)

    # Otherwise, process it
    all_templates = main.add_oa_links_in_references(text, page_name, only_doi)
    filtered = list(filter(lambda e: e.proposed_change, all_templates))
    context = {
    'proposed_edits': [change.json() for change in filtered],
    'page_name' : page_name,
        'utcnow': unicode(datetime.datetime.utcnow()),
    }

    if filtered:
        # Cache the result
        with open(cache_fname, 'w') as f:
            json.dump(context, f)
    elif os.path.isfile(cache_fname):
        os.remove(cache_fname)

    return context