當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。