当前位置: 首页>>代码示例>>Python>>正文


Python request.cookies方法代码示例

本文整理汇总了Python中flask.request.cookies方法的典型用法代码示例。如果您正苦于以下问题:Python request.cookies方法的具体用法?Python request.cookies怎么用?Python request.cookies使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在flask.request的用法示例。


在下文中一共展示了request.cookies方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: zmirror_enter

# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import cookies [as 别名]
def zmirror_enter(input_path='/'):
    """入口函数的壳, 只是包了一层异常处理, 实际是 main_function() """
    try:
        resp = main_function(input_path=input_path)

        # 加入额外的响应头
        for name, value in parse.extra_resp_headers.items():
            resp.headers.set(name, value)

        # 加入额外的cookies
        for name, cookie_string in parse.extra_cookies.items():
            resp.headers.add("Set-Cookie", cookie_string)

    except:  # coverage: exclude
        return generate_error_page(is_traceback=True)
    else:
        return resp


# noinspection PyUnusedLocal 
开发者ID:aploium,项目名称:zmirror,代码行数:22,代码来源:zmirror.py

示例2: _authenticate_session

# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import cookies [as 别名]
def _authenticate_session():
    user_manager = UserManager()
    user_session_token = None
    user = None

    if 'X-Session-Token' in request.headers:
        user_session_token = request.headers['X-Session-Token']
    elif 'session_token' in request.args:
        user_session_token = request.args.get('session_token')
    elif 'session_token' in request.cookies:
        user_session_token = request.cookies.get('session_token')

    if user_session_token:
        user, session = user_manager.authenticate_user_session(user_session_token)

    return user is not None 
开发者ID:BlackLight,项目名称:platypush,代码行数:18,代码来源:utils.py

示例3: _authenticate_csrf_token

# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import cookies [as 别名]
def _authenticate_csrf_token():
    user_manager = UserManager()
    user_session_token = None

    if 'X-Session-Token' in request.headers:
        user_session_token = request.headers['X-Session-Token']
    elif 'session_token' in request.args:
        user_session_token = request.args.get('session_token')
    elif 'session_token' in request.cookies:
        user_session_token = request.cookies.get('session_token')

    if user_session_token:
        user, session = user_manager.authenticate_user_session(user_session_token)
    else:
        return False

    if user is None:
        return False

    return session.csrf_token is None or request.form.get('csrf_token') == session.csrf_token 
开发者ID:BlackLight,项目名称:platypush,代码行数:22,代码来源:utils.py

示例4: send_cookie

# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import cookies [as 别名]
def send_cookie():
    if request.method == 'GET':
        # 쿠키를 주려면 Response 객체가 필요하다
        response = Response('hello hello')
        response.set_cookie('cookie', 'value!!!!!!!!!', secure=True, httponly=True, samesite='Lax')
        # [werkzeug.wrappers.BaseResponse]
        #     def set_cookie(
        #         self, key, value='', max_age=None, expires=None, path='/',
        #         domain=None, secure=False, httponly=False, samesite=None
        #     )

        return response
    elif request.method == 'POST':
        # 쿠키를 받으려면 BaseRequest의 프로퍼티인 'cookies'에 접근
        print(request.cookies['cookie'])

        # 쿠키 제거는 expires를 0으로 주면 된다
        response = Response('hello hello!')
        response.set_cookie('cookie', '', expires=0,secure=True, httponly=True, samesite='Lax')

        return response
    else:
        return '', 405 
开发者ID:JoMingyu,项目名称:--Awesome-Python--,代码行数:25,代码来源:main.py

示例5: get_value_from_request

# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import cookies [as 别名]
def get_value_from_request(_key):
    """
    get a value from GET, POST or CCOKIES

    Args:
        _key: the value name to find

    Returns:
        the value content if found otherwise None
    """
    global flask_request
    try:
        key = flask_request.args[_key]
    except Exception as _:
        try:
            key = flask_request.form[_key]
        except Exception as _:
            try:
                key = flask_request.cookies[_key]
            except Exception as _:
                key = None
    if key:
        # todo: fix it later
        key = key.replace("\\\"", "\"").replace("\\\'", "\'")
    return key 
开发者ID:zdresearch,项目名称:OWASP-Honeypot,代码行数:27,代码来源:server.py

示例6: login

# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import cookies [as 别名]
def login():
    if 'SESSION_ID' not in request.cookies:
        session_id = randomString(16, '0123456789abcdef')
    else:
        session_id = request.cookies['SESSION_ID']

    oidconsumer = consumer.Consumer({'id': session_id}, None)
    oidrequest = oidconsumer.begin(u'http://ru.wargaming.net/id/openid/')

    print(oidrequest.shouldSendRedirect())
    redirect_url = oidrequest.redirectURL(
        realm='http://127.0.0.1:5000/',
        return_to='http://127.0.0.1:5000/auth_cb',
    )
    print(oidrequest.shouldSendRedirect())
    response = redirect(redirect_url)
    response.set_cookie('SESSION_ID', session_id)
    return response 
开发者ID:svartalf,项目名称:python-wargaming,代码行数:20,代码来源:openid-demo.py

示例7: test_get_by_id

# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import cookies [as 别名]
def test_get_by_id(self):
        # Ensure id is correct for the current/logged in user
        with self.client:
            response = self.client.post('/login', data=dict(
                email='test@tester.com', password='password456'
            ), follow_redirects=True)
            print response
            logged_in_user_id = verifyLogin(
                app.config['SECRET_KEY'],
                app.config['COOKIE_TIMEOUT'],
                request.cookies
            )
            user = User()
            user.config = app.config
            user_id = user.getUID('test@tester.com', g.rdb_conn)
            self.assertTrue(logged_in_user_id == user_id) 
开发者ID:Runbook,项目名称:runbook,代码行数:18,代码来源:test_user.py

示例8: get_auth_cookies

# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import cookies [as 别名]
def get_auth_cookies(user: "User") -> List[Dict[Any, Any]]:
    # Login with the user specified to get the reports
    with current_app.test_request_context("/login"):
        login_user(user)
        # A mock response object to get the cookie information from
        response = Response()
        current_app.session_interface.save_session(current_app, session, response)

    cookies = []

    # Set the cookies in the driver
    for name, value in response.headers:
        if name.lower() == "set-cookie":
            cookie = parse_cookie(value)
            cookies.append(cookie["session"])
    return cookies 
开发者ID:apache,项目名称:incubator-superset,代码行数:18,代码来源:screenshots.py

示例9: auth_driver

# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import cookies [as 别名]
def auth_driver(driver: WebDriver, user: "User") -> WebDriver:
    """
        Default AuthDriverFuncType type that sets a session cookie flask-login style
    :return: WebDriver
    """
    if user:
        # Set the cookies in the driver
        for cookie in get_auth_cookies(user):
            info = dict(name="session", value=cookie)
            driver.add_cookie(info)
    elif request.cookies:
        cookies = request.cookies
        for k, v in cookies.items():
            cookie = dict(name=k, value=v)
            driver.add_cookie(cookie)
    return driver 
开发者ID:apache,项目名称:incubator-superset,代码行数:18,代码来源:screenshots.py

示例10: get_current_session_id_and_token

# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import cookies [as 别名]
def get_current_session_id_and_token():
    auth_header = request.environ.get('HTTP_AUTHORIZATION')
    auth_token = ""

    if auth_header:
        value = http.wsgi_to_bytes(auth_header)
        try:
            auth_type, auth_token = value.split(None, 1)
            auth_type = auth_type.lower()

            if auth_type != b'bearer':
                return None

        except ValueError:
            logging.warning("Invalid Auth header")
            return None
    elif "rbbtoken" in request.cookies:
        # Session token in cookie needs to be supported for embedded media links
        auth_token = urllib.parse.unquote(request.cookies['rbbtoken']).encode('latin1')
    else:
        return None

    return unpack_token(base64.b64decode(auth_token)) 
开发者ID:AMZ-Driverless,项目名称:rbb_core,代码行数:25,代码来源:auth.py

示例11: response_cookies_deep_copy

# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import cookies [as 别名]
def response_cookies_deep_copy():
    """
    It's a BAD hack to get RAW cookies headers, but so far, we don't have better way.
    We'd go DEEP inside the urllib's private method to get raw headers

    raw_headers example:
    [('Cache-Control', 'private'),
    ('Content-Length', '48234'),
    ('Content-Type', 'text/html; Charset=utf-8'),
    ('Server', 'Microsoft-IIS/8.5'),
    ('Set-Cookie','BoardList=BoardID=Show; expires=Mon, 02-May-2016 16:00:00 GMT; path=/'),
    ('Set-Cookie','aspsky=abcefgh; expires=Sun, 24-Apr-2016 16:00:00 GMT; path=/; HttpOnly'),
    ('Set-Cookie', 'ASPSESSIONIDSCSSDSSQ=OGKMLAHDHBFDJCDMGBOAGOMJ; path=/'),
    ('X-Powered-By', 'ASP.NET'),
    ('Date', 'Tue, 26 Apr 2016 12:32:40 GMT')]

    """
    raw_headers = parse.remote_response.raw._original_response.headers._headers
    header_cookies_string_list = []
    for name, value in raw_headers:
        if name.lower() == 'set-cookie':
            if my_host_scheme == 'http://':
                value = value.replace('Secure;', '')
                value = value.replace(';Secure', ';')
                value = value.replace('; Secure', ';')
            if 'httponly' in value.lower():
                if enable_aggressive_cookies_path_rewrite:
                    # 暴力cookie path重写, 把所有path都重写为 /
                    value = regex_cookie_path_rewriter.sub('path=/;', value)
                elif enable_aggressive_cookies_path_rewrite is not None:
                    # 重写HttpOnly Cookies的path到当前url下
                    # eg(/extdomains/a.foobar.com): path=/verify; -> path=/extdomains/a.foobar.com/verify

                    if parse.remote_domain not in domain_alias_to_target_set:  # do not rewrite main domains
                        value = regex_cookie_path_rewriter.sub(
                            '\g<prefix>=/extdomains/' + parse.remote_domain + '\g<path>', value)

            header_cookies_string_list.append(value)
    return header_cookies_string_list 
开发者ID:aploium,项目名称:zmirror,代码行数:41,代码来源:zmirror.py

示例12: response_text_rewrite

# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import cookies [as 别名]
def response_text_rewrite(resp_text):
    """
    rewrite urls in text-like content (html,css,js)
    :type resp_text: str
    :rtype: str
    """
    # v0.20.6+ plain replace domain alias, support json/urlencoded/json-urlencoded/plain
    if url_custom_redirect_enable:
        for before_replace, after_replace in (plain_replace_domain_alias + parse.temporary_domain_alias):
            resp_text = resp_text.replace(before_replace, after_replace)

    # v0.9.2+: advanced url rewrite engine
    resp_text = regex_adv_url_rewriter.sub(regex_url_reassemble, resp_text)

    if developer_string_trace is not None and developer_string_trace in resp_text:
        # debug用代码, 对正常运行无任何作用
        infoprint('StringTrace: appears after advanced rewrite, code line no. ', current_line_number())

    # v0.28.0 实验性功能, 在v0.28.3后默认启用
    resp_text = response_text_basic_mirrorlization(resp_text)

    if developer_string_trace is not None and developer_string_trace in resp_text:
        # debug用代码, 对正常运行无任何作用
        infoprint('StringTrace: appears after basic mirrorlization, code line no. ', current_line_number())

    # for cookies set string (in js) replace
    # eg: ".twitter.com" --> "foo.com"
    resp_text = resp_text.replace('\".' + target_domain_root + '\"', '\"' + my_host_name_no_port + '\"')
    resp_text = resp_text.replace("\'." + target_domain_root + "\'", "\'" + my_host_name_no_port + "\'")
    resp_text = resp_text.replace("domain=." + target_domain_root, "domain=" + my_host_name_no_port)
    resp_text = resp_text.replace('\"' + target_domain_root + '\"', '\"' + my_host_name_no_port + '\"')
    resp_text = resp_text.replace("\'" + target_domain_root + "\'", "\'" + my_host_name_no_port + "\'")

    if developer_string_trace is not None and developer_string_trace in resp_text:
        # debug用代码, 对正常运行无任何作用
        infoprint('StringTrace: appears after js cookies string rewrite, code line no. ', current_line_number())

    # resp_text = resp_text.replace('lang="zh-Hans"', '', 1)
    return resp_text 
开发者ID:aploium,项目名称:zmirror,代码行数:41,代码来源:zmirror.py

示例13: filter_client_request

# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import cookies [as 别名]
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 
开发者ID:aploium,项目名称:zmirror,代码行数:39,代码来源:zmirror.py

示例14: user_score

# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import cookies [as 别名]
def user_score(name):
    score = [randint(0, request.context.json.limit) for _ in range(5)]
    score.sort(reverse=request.context.query.order)
    assert request.context.cookies.pub == 'abcdefg'
    assert request.cookies['pub'] == 'abcdefg'
    return jsonify(name=request.context.json.name, score=score) 
开发者ID:0b01001001,项目名称:spectree,代码行数:8,代码来源:test_plugin_flask.py

示例15: request_validation

# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import cookies [as 别名]
def request_validation(self, request, query, json, headers, cookies):
        req_query = request.args or {}
        req_json = request.get_json() or {}
        req_headers = request.headers or {}
        req_cookies = request.cookies or {}
        request.context = Context(
            query.parse_obj(req_query) if query else None,
            json.parse_obj(req_json) if json else None,
            headers.parse_obj(req_headers) if headers else None,
            cookies.parse_obj(req_cookies) if cookies else None,
        ) 
开发者ID:0b01001001,项目名称:spectree,代码行数:13,代码来源:flask_plugin.py


注:本文中的flask.request.cookies方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。