當前位置: 首頁>>代碼示例>>Python>>正文


Python request.access_route方法代碼示例

本文整理匯總了Python中flask.request.access_route方法的典型用法代碼示例。如果您正苦於以下問題:Python request.access_route方法的具體用法?Python request.access_route怎麽用?Python request.access_route使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在flask.request的用法示例。


在下文中一共展示了request.access_route方法的7個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: authenticate_rapidapi

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import access_route [as 別名]
def authenticate_rapidapi(func):
    """Decorator to authenticate request with Rapid API."""

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        # Rapid authentication
        if rapid_enabled:
            rapid_secret = request.headers.get('X-RapidAPI-Proxy-Secret')
            if rapid_secret is not None:
                client_ip = request.access_route[-1]
                # test the rapid api with corresponding request header
                if rapid_secret == app.config['RAPID_SECRET']:
                    return func(*args, **kwargs)
            # No authentication
            return "Invalid/expired token", 401
        else:
            return func(*args, **kwargs)

    return wrapper 
開發者ID:IUNetSci,項目名稱:hoaxy-backend,代碼行數:21,代碼來源:api.py

示例2: login

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import access_route [as 別名]
def login():
    """Flask AUCR user login route."""
    if current_user.is_authenticated:
        # if user is logged in we get out of here
        return redirect(url_for('main.index'))
    if request.method == "POST":
        form = LoginForm()
        if form.validate_on_submit():
            user_name = User.query.filter_by(username=form.username.data).first()
            if user_name is not None and user_name.otp_secret is not None:
                otp_auth_check = user_name.verify_totp(form.token.data)
                if otp_auth_check is False or not user_name.check_password(form.password.data):
                    flash('Invalid username, password or token.')
                    return redirect(url_for('auth.login'))
            if user_name is None or not user_name.check_password(form.password.data):
                flash('Invalid username, password or token.')
                return redirect(url_for('auth.login'))
            # log user in
            if form.remember_me.data:
                login_user(user_name, remember=form.remember_me.data)
            else:
                login_user(user_name)
            session["navbar"] = get_group_permission_navbar()
            session["groups"] = get_groups()
            flash('You are now logged in!')
            user_name.set_last_used_ip(request.access_route[0])
            db.session.add(user_name)
            db.session.commit()
            page = request.args.get('page', 1, type=int)
            return redirect(url_for('main.index', page=page))
        else:
            for error in form.errors:
                flash(str(form.errors[error][0]), 'error')
        flash('Invalid username, password or token.')
        return redirect(url_for('auth.login'))
    page = request.args.get('page', 1, type=int)
    form = LoginForm()
    return render_template('login.html', title=_('Sign In'), form=form, page=page) 
開發者ID:AUCR,項目名稱:AUCR,代碼行數:40,代碼來源:routes.py

示例3: get

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import access_route [as 別名]
def get(self):

        # feeds get large need to force some cleanup
        gc.collect()

        if get_remote_address() != request.access_route[-1]:
            return jsonify_unauth()

        if not HTTPD_TOKEN:
            return jsonify_success()

        remote = ROUTER_ADDR
        if current_app.config.get('CIF_ROUTER_ADDR'):
            remote = current_app.config['CIF_ROUTER_ADDR']

        try:
            r = Client(remote, HTTPD_TOKEN).ping()
            r = Client(remote, HTTPD_TOKEN).indicators_search({'indicator': 'example.com', 'nolog': '1'})
            r = True

        except TimeoutError:
            return jsonify_unknown(msg='timeout', code=408)

        except AuthError:
            return jsonify_unauth()

        if not r:
            return jsonify_unknown(503)

        return jsonify_success() 
開發者ID:csirtgadgets,項目名稱:bearded-avenger,代碼行數:32,代碼來源:health.py

示例4: proxy_get_remote_address

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import access_route [as 別名]
def proxy_get_remote_address():
    if HTTPD_PROXY in ['1', 1]:
        return request.access_route[-1]

    return get_remote_address() 
開發者ID:csirtgadgets,項目名稱:bearded-avenger,代碼行數:7,代碼來源:__init__.py

示例5: get_ipaddr

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import access_route [as 別名]
def get_ipaddr():  # pragma: no cover
    """
    :return: the ip address for the current request
     (or 127.0.0.1 if none found) based on the X-Forwarded-For headers.

    .. deprecated:: 0.9.2
     """
    if request.access_route:
        return request.access_route[0]
    else:
        return request.remote_addr or '127.0.0.1' 
開發者ID:alisaifee,項目名稱:flask-limiter,代碼行數:13,代碼來源:util.py

示例6: api_get_scanner_stats

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import access_route [as 別名]
def api_get_scanner_stats():
    pretty = True if request.args.get('pretty', '').lower() == 'true' else False
    verbose = True if request.args.get('verbose', '').lower() == 'true' else False

    # Disallow verbose stat requests from the public if this setting is set
    if verbose and not API_ALLOW_VERBOSE_STATS_FROM_PUBLIC:
        verbose = True if request.access_route[0] == '127.0.0.1' else False

    # Get the scanner statistics from the backend database, defaulting to the quick stats only
    stats = database.select_scan_scanner_statistics(verbose)

    # If a grade isn't in the database, return it with quantity 0
    grade_distribution = {grade: stats['grade_distribution'].get(grade, 0) for grade in GRADES}
    grade_distribution_all_scans = {grade: stats['grade_distribution_all_scans'].get(grade, 0) for grade in GRADES}

    # Get the number of grade improvements
    grade_improvements_all = stats['scan_score_difference_distribution_summation']

    # Make sure we only list the ones that are improvements, with a maximum of 5 letter grades
    grade_improvements = {k: 0 for k in range(0, 6)}
    for k, v in grade_improvements_all.items():
        grade_improvements[min(5, max(0, int(k / 20)))] += v

    # Convert all the datetimes to HTTP strings
    stats['most_recent_scan_datetime'] = http_date(stats['most_recent_scan_datetime'].utctimetuple())
    stats['recent_scans'] = {http_date(i.utctimetuple()): v for i, v in stats['recent_scans']}

    resp = make_response(json.dumps({
        'gradeDistribution': {
            'latest': grade_distribution,
            'all': grade_distribution_all_scans,
        },
        'gradeImprovements': grade_improvements,
        'misc': {
            'mostRecentScanDate': stats['most_recent_scan_datetime'],
            'numHoursWithoutScansInLast24Hours': 24 - len(stats['recent_scans']) if verbose else -1,
            'numImprovedSites': sum([v for k, v in grade_improvements_all.items() if k > 0]),
            'numScans': stats['scan_count'],
            'numScansLast24Hours': sum(stats['recent_scans'].values()) if verbose else -1,
            'numSuccessfulScans': sum(grade_distribution_all_scans.values()),
            'numUniqueSites': sum(grade_improvements_all.values())
        },
        'recent': {
            'scans': {
                'best': database.select_scan_recent_finished_scans(13, 90, 1000),   # 13, as there are 13 grades
                'recent': database.select_scan_recent_finished_scans(13, 0, 1000),  # 13, as there are 13 grades
                'worst': database.select_scan_recent_finished_scans(13, 0, 20),     # 13, as there are 13 grades
                'numPerHourLast24Hours': stats['recent_scans'],
            },
        },
        'states': {state: stats['states'].get(state, 0) for state in STATES},
    }, indent=4 if pretty else None, sort_keys=pretty, default=str))

    resp.mimetype = 'application/json'

    return resp 
開發者ID:mozilla,項目名稱:http-observatory,代碼行數:58,代碼來源:api.py

示例7: test_decorated_dynamic_limits

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import access_route [as 別名]
def test_decorated_dynamic_limits(extension_factory):
    app, limiter = extension_factory(
        {"X": "2 per second"}, default_limits=["1/second"]
    )

    def request_context_limit():
        limits = {
            "127.0.0.1": "10 per minute",
            "127.0.0.2": "1 per minute"
        }
        remote_addr = (request.access_route and request.access_route[0]
                       ) or request.remote_addr or '127.0.0.1'
        limit = limits.setdefault(remote_addr, '1 per minute')
        return limit

    @app.route("/t1")
    @limiter.limit("20/day")
    @limiter.limit(lambda: current_app.config.get("X"))
    @limiter.limit(request_context_limit)
    def t1():
        return "42"

    @app.route("/t2")
    @limiter.limit(lambda: current_app.config.get("X"))
    def t2():
        return "42"

    R1 = {"X_FORWARDED_FOR": "127.0.0.1, 127.0.0.0"}
    R2 = {"X_FORWARDED_FOR": "127.0.0.2"}

    with app.test_client() as cli:
        with hiro.Timeline().freeze() as timeline:
            for i in range(0, 10):
                assert cli.get("/t1", headers=R1).status_code == 200
                timeline.forward(1)
            assert cli.get("/t1", headers=R1).status_code == 429
            assert cli.get("/t1", headers=R2).status_code == 200
            assert cli.get("/t1", headers=R2).status_code == 429
            timeline.forward(60)
            assert cli.get("/t1", headers=R2).status_code == 200
            assert cli.get("/t2").status_code == 200
            assert cli.get("/t2").status_code == 200
            assert cli.get("/t2").status_code == 429
            timeline.forward(1)
            assert cli.get("/t2").status_code == 200 
開發者ID:alisaifee,項目名稱:flask-limiter,代碼行數:47,代碼來源:test_decorators.py


注:本文中的flask.request.access_route方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。