http.cookiejar — HTTP 클라이언트를 위한 쿠키 처리

소스 코드: Lib/http/cookiejar.py


The http.cookiejar module defines classes for automatic handling of HTTP cookies. It is useful for accessing websites that require small pieces of data – cookies – to be set on the client machine by an HTTP response from a web server, and then returned to the server in later HTTP requests.

Both the regular Netscape cookie protocol and the protocol defined by RFC 2965 are handled. RFC 2965 handling is switched off by default. RFC 2109 cookies are parsed as Netscape cookies and subsequently treated either as Netscape or RFC 2965 cookies according to the ‘policy’ in effect. Note that the great majority of cookies on the internet are Netscape cookies. http.cookiejar attempts to follow the de-facto Netscape cookie protocol (which differs substantially from that set out in the original Netscape specification), including taking note of the max-age and port cookie-attributes introduced with RFC 2965.

참고

The various named parameters found in Set-Cookie and Set-Cookie2 headers (for example, domain and expires) are conventionally referred to as attributes. To distinguish them from Python attributes, the documentation for this module uses the term cookie-attribute instead.

모듈은 다음 예외를 정의합니다:

exception http.cookiejar.LoadError

FileCookieJar 인스턴스는 파일에서 쿠키를 로드하지 못하면 이 예외를 발생시킵니다. LoadErrorOSError의 서브 클래스입니다.

버전 3.3에서 변경: 이전에는 LoadErrorIOError의 서브 형이었습니다. 이제는 OSError의 별칭입니다.

다음과 같은 클래스가 제공됩니다:

class http.cookiejar.CookieJar(policy=None)

policyCookiePolicy 인터페이스를 구현하는 객체입니다.

CookieJar 클래스는 HTTP 쿠키를 저장합니다. HTTP 요청에서 쿠키를 추출하고, HTTP 응답으로 반환합니다. 필요하면 CookieJar 인스턴스는 포함된 쿠키를 자동으로 만료합니다. 서브 클래스는 파일이나 데이터베이스에서 쿠키를 저장하고 검색하는 역할도 합니다.

class http.cookiejar.FileCookieJar(filename=None, delayload=None, policy=None)

policyCookiePolicy 인터페이스를 구현하는 객체입니다. 다른 인자에 대해서는, 해당 어트리뷰트의 설명서를 참조하십시오.

디스크의 파일에서 쿠키를 로드하고 아마도 파일에 쿠키를 저장할 수 있는 CookieJar. load()revert() 메서드가 호출될 때까지 이름이 지정된 파일에서 쿠키가 로드되지 않습니다. 이 클래스의 서브 클래스는 FileCookieJar 서브 클래스와 웹 브라우저와의 협력 섹션에 설명되어 있습니다.

This should not be initialized directly – use its subclasses below instead.

버전 3.8에서 변경: filename 매개 변수는 경로류 객체를 지원합니다.

class http.cookiejar.CookiePolicy

이 클래스는 각 쿠키가 서버에서 수락되고 서버로 반환되어야 하는지를 결정하는 역할을 맡습니다.

class http.cookiejar.DefaultCookiePolicy(blocked_domains=None, allowed_domains=None, netscape=True, rfc2965=False, rfc2109_as_netscape=None, hide_cookie2=False, strict_domain=False, strict_rfc2965_unverifiable=True, strict_ns_unverifiable=False, strict_ns_domain=DefaultCookiePolicy.DomainLiberal, strict_ns_set_initial_dollar=False, strict_ns_set_path=False, secure_protocols=('https', 'wss'))

Constructor arguments should be passed as keyword arguments only. blocked_domains is a sequence of domain names that we never accept cookies from, nor return cookies to. allowed_domains if not None, this is a sequence of the only domains for which we accept and return cookies. secure_protocols is a sequence of protocols for which secure cookies can be added to. By default https and wss (secure websocket) are considered secure protocols. For all other arguments, see the documentation for CookiePolicy and DefaultCookiePolicy objects.

DefaultCookiePolicy implements the standard accept / reject rules for Netscape and RFC 2965 cookies. By default, RFC 2109 cookies (that is, cookies received in a Set-Cookie header with a version cookie-attribute of 1) are treated according to the RFC 2965 rules. However, if RFC 2965 handling is turned off or rfc2109_as_netscape is True, RFC 2109 cookies are ‘downgraded’ by the CookieJar instance to Netscape cookies, by setting the version attribute of the Cookie instance to 0. DefaultCookiePolicy also provides some parameters to allow some fine-tuning of policy.

class http.cookiejar.Cookie

This class represents Netscape, RFC 2109 and RFC 2965 cookies. It is not expected that users of http.cookiejar construct their own Cookie instances. Instead, if necessary, call make_cookies() on a CookieJar instance.

더 보기

모듈 urllib.request

자동 쿠키 처리가 지원되는 URL 열기.

모듈 http.cookies

HTTP cookie classes, principally useful for server-side code. The http.cookiejar and http.cookies modules do not depend on each other.

https://curl.se/rfc/cookie_spec.html

The specification of the original Netscape cookie protocol. Though this is still the dominant protocol, the ‘Netscape cookie protocol’ implemented by all the major browsers (and http.cookiejar) only bears a passing resemblance to the one sketched out in cookie_spec.html.

RFC 2109 - HTTP 상태 관리 메커니즘

RFC 2965로 개정되었습니다. version=1 인 Set-Cookie를 사용합니다.

RFC 2965 - HTTP 상태 관리 메커니즘

버그가 수정된 Netscape 프로토콜. Set-Cookie 대신 Set-Cookie2를 사용합니다. 널리 사용되지 않습니다.

https://kristol.org/cookie/errata.html

완료되지 않은 RFC 2965의 정오표.

RFC 2964 - HTTP 상태 관리 사용

CookieJar and FileCookieJar objects

CookieJar 객체는 포함된 Cookie 객체를 이터레이트 하기 위한 이터레이터 프로토콜을 지원합니다.

CookieJar에는 다음과 같은 메서드가 있습니다:

request에 올바른 Cookie 헤더를 추가합니다.

If policy allows (that is, the rfc2965 and hide_cookie2 attributes of the CookieJar’s CookiePolicy instance are true and false respectively), the Cookie2 header is also added when appropriate.

The request object (usually a urllib.request.Request instance) must support the methods get_full_url(), has_header(), get_header(), header_items(), add_unredirected_header() and the attributes host, type, unverifiable and origin_req_host as documented by urllib.request.

버전 3.3에서 변경: request object needs origin_req_host attribute. Dependency on a deprecated method get_origin_req_host() has been removed.

CookieJar.extract_cookies(response, request)

HTTP response에서 쿠키를 추출하여 정책이 허용하면 CookieJar에 저장합니다.

CookieJarresponse 인자에서 수락할 수 있는 Set-CookieSet-Cookie2 헤더를 찾고, 쿠키를 적절하게 저장합니다 (CookiePolicy.set_ok() 메서드의 승인에 따라).

The response object (usually the result of a call to urllib.request.urlopen(), or similar) should support an info() method, which returns an email.message.Message instance.

The request object (usually a urllib.request.Request instance) must support the method get_full_url() and the attributes host, unverifiable and origin_req_host, as documented by urllib.request. The request is used to set default values for cookie-attributes as well as for checking that the cookie is allowed to be set.

버전 3.3에서 변경: request object needs origin_req_host attribute. Dependency on a deprecated method get_origin_req_host() has been removed.

CookieJar.set_policy(policy)

사용할 CookiePolicy 인스턴스를 설정합니다.

CookieJar.make_cookies(response, request)

response 객체에서 추출한 Cookie 객체의 시퀀스를 반환합니다.

responserequest 인자에 필요한 인터페이스는 extract_cookies() 설명서를 참조하십시오.

정책이 그래도 좋다고 한다면 Cookie를 설정합니다.

설정할 수 있는지 정책을 확인하지 않고, Cookie를 설정합니다.

CookieJar.clear([domain[, path[, name]]])

일부 쿠키를 지웁니다.

인자 없이 호출되면, 모든 쿠키를 지웁니다. 단일 인자가 제공되면, 해당 domain에 속하는 쿠키만 제거됩니다. 두 개의 인자가 제공되면, 지정된 domain과 URL path에 속하는 쿠키가 제거됩니다. 세 개의 인자가 제공되면, 지정된 domain, pathname을 갖는 쿠키가 제거됩니다.

일치하는 쿠키가 없으면 KeyError를 발생시킵니다.

CookieJar.clear_session_cookies()

모든 세션 쿠키를 폐기합니다.

Discards all contained cookies that have a true discard attribute (usually because they had either no max-age or expires cookie-attribute, or an explicit discard cookie-attribute). For interactive browsers, the end of a session usually corresponds to closing the browser window.

Note that the save() method won’t save session cookies anyway, unless you ask otherwise by passing a true ignore_discard argument.

FileCookieJar는 다음과 같은 추가 메서드를 구현합니다:

FileCookieJar.save(filename=None, ignore_discard=False, ignore_expires=False)

쿠키를 파일에 저장합니다.

이 베이스 클래스는 NotImplementedError를 발생시킵니다. 서브 클래스는 이 메서드를 구현하지 않은 채로 둘 수 있습니다.

filename is the name of file in which to save cookies. If filename is not specified, self.filename is used (whose default is the value passed to the constructor, if any); if self.filename is None, ValueError is raised.

ignore_discard: 폐기되는 것으로 설정된 쿠키도 저장합니다. ignore_expires: 만료된 쿠키도 저장합니다

파일이 이미 존재하면, 파일을 덮어써서, 파일에 포함된 모든 쿠키를 지웁니다. 저장된 쿠키는 나중에 load()revert() 메서드를 사용하여 복원할 수 있습니다.

FileCookieJar.load(filename=None, ignore_discard=False, ignore_expires=False)

파일에서 쿠키를 로드합니다.

새로 로드한 쿠키가 덮어쓰지 않는 한 오래된 쿠키는 유지됩니다.

인자는 save()와 같습니다.

명명된 파일은 클래스가 이해하는 형식이어야 하고, 그렇지 않으면 LoadError가 발생합니다. 또한, 예를 들어 파일이 존재하지 않으면, OSError가 발생할 수 있습니다.

버전 3.3에서 변경: IOError가 발생했었지만, 이제는 OSError의 별칭입니다.

FileCookieJar.revert(filename=None, ignore_discard=False, ignore_expires=False)

모든 쿠키를 지우고 저장된 파일에서 쿠키를 다시 로드합니다.

revert()load()와 같은 예외를 발생시킬 수 있습니다. 실패가 일어나면, 객체 상태는 변경되지 않습니다.

FileCookieJar 인스턴스에는 다음과 같은 공용 어트리뷰트가 있습니다:

FileCookieJar.filename

쿠키를 보관할 기본 파일의 파일명. 이 어트리뷰트는 대입할 수 있습니다.

FileCookieJar.delayload

참이면, 디스크에서 쿠키를 천천히(lazily) 로드합니다. 이 어트리뷰트는 대입하지 않아야 합니다. (디스크의 쿠키가 변경되지 않는 한) 성능에만 영향을 미칠 뿐 동작을 바꾸지는 않기 때문에, 이것은 힌트일 뿐입니다. CookieJar 객체는 이를 무시할 수 있습니다. 표준 라이브러리에 포함된 FileCookieJar 클래스는 아무것도 쿠키를 천천히 로드하지 않습니다.

FileCookieJar 서브 클래스와 웹 브라우저와의 협력

다음 CookieJar 서브 클래스는 읽기와 쓰기를 위해 제공됩니다.

class http.cookiejar.MozillaCookieJar(filename=None, delayload=None, policy=None)

Mozilla cookies.txt 파일 형식(curl, Lynx 및 Netscape 브라우저에서도 사용됩니다)으로 디스크에서 쿠키를 로드하고 저장할 수 있는 FileCookieJar.

참고

RFC 2965 쿠키에 대한 정보와, port 같은 최신이나 비표준 쿠키 어트리뷰트에 대한 정보가 손실됩니다.

경고

손실/손상이 불편한 쿠키가 있다면 저장하기 전에 쿠키를 백업하십시오 (로드/저장 왕복으로 인해 파일이 약간 변경될 수 있는 미묘한 부분이 있습니다).

또한 Mozilla가 실행되는 동안 저장된 쿠키는 Mozilla에 의해 방해를 받음에 유의하십시오.

class http.cookiejar.LWPCookieJar(filename=None, delayload=None, policy=None)

libwww-perl 라이브러리의 Set-Cookie3 파일 형식과 호환되는 형식으로 쿠키를 디스크에서 로드하고 저장할 수 있는 FileCookieJar. 사람이 읽을 수 있는 파일에 쿠키를 저장하려는 경우에 편리합니다.

버전 3.8에서 변경: filename 매개 변수는 경로류 객체를 지원합니다.

CookiePolicy objects

CookiePolicy 인터페이스를 구현하는 객체에는 다음과 같은 메서드가 있습니다:

CookiePolicy.set_ok(cookie, request)

서버에서 쿠키를 수락해야 하는지를 나타내는 불리언 값을 반환합니다.

cookieCookie 인스턴스입니다. requestCookieJar.extract_cookies() 설명서에서 정의한 인터페이스를 구현하는 객체입니다.

CookiePolicy.return_ok(cookie, request)

쿠키를 서버로 반환해야 하는지를 나타내는 불리언 값을 반환합니다.

cookieCookie 인스턴스입니다. requestCookieJar.add_cookie_header() 설명서에서 정의한 인터페이스를 구현하는 객체입니다.

CookiePolicy.domain_return_ok(domain, request)

주어진 쿠키 도메인(domain)에서, 쿠키를 반환하지 않아야 하면 False를 반환합니다.

이 메서드는 최적화입니다. 특정 도메인을 가진 모든 쿠키를 검사할 필요(많은 파일을 읽는 것을 수반합니다)를 제거합니다. domain_return_ok()path_return_ok()에서 참을 반환하면 모든 작업이 return_ok()로 넘어갑니다.

쿠키 도메인에 대해 domain_return_ok()가 참을 반환하면, 쿠키 경로에 대해 path_return_ok()가 호출됩니다. 그렇지 않으면, 해당 쿠키 도메인에 대해 path_return_ok()return_ok()가 호출되지 않습니다. path_return_ok()가 참을 반환하면, return_ok()Cookie 객체 자체로 호출되어 전체 검사를 수행합니다. 그렇지 않으면, 해당 쿠키 경로에 대해 return_ok()가 호출되지 않습니다.

domain_return_ok()request 도메인뿐만 아니라 모든 cookie 도메인에 대해 호출됨에 유의하십시오. 예를 들어, 요청 도메인이 "www.example.com"이면 함수는 ".example.com""www.example.com" 모두에 대해 호출될 수 있습니다. path_return_ok()도 마찬가지입니다.

request 인자는 return_ok()에 대해 설명된 대로입니다.

CookiePolicy.path_return_ok(path, request)

주어진 쿠키 경로에 대해, 쿠키를 반환하지 않아야 하면 False를 반환합니다.

domain_return_ok() 설명서를 참조하십시오.

위의 메서드를 구현하는 것 외에도, CookiePolicy 인터페이스의 구현은 어떤 프로토콜을 어떻게 사용해야 하는지를 나타내는 다음 어트리뷰트도 제공해야 합니다. 이러한 모든 어트리뷰트는 대입할 수 있습니다.

CookiePolicy.netscape

Netscape 프로토콜을 구현합니다.

CookiePolicy.rfc2965

RFC 2965 프로토콜을 구현합니다.

CookiePolicy.hide_cookie2

요청에 Cookie2 헤더를 추가하지 않습니다 (이 헤더가 있으면 서버에게 우리가 RFC 2965 쿠키를 이해하고 있음을 알립니다).

CookiePolicy 클래스를 정의하는 가장 유용한 방법은 DefaultCookiePolicy 에서 서브 클래싱하고 위의 메서드 중 일부나 전부를 재정의하는 것입니다. CookiePolicy 자체는 모든 쿠키를 설정하고 수신하도록 허용하는 ‘널 정책’으로 사용될 수 있습니다 (이 정책이 그리 유용하지는 않을 것입니다).

DefaultCookiePolicy objects

쿠키 수락과 반환에 대한 표준 규칙을 구현합니다.

RFC 2965와 Netscape 쿠키를 모두 다룹니다. RFC 2965 처리는 기본적으로 꺼져있습니다.

자체 정책을 제공하는 가장 쉬운 방법은 이 클래스를 재정의하고 자체 검사를 추가하기 전에 재정의된 구현에서 해당 메서드를 호출하는 것입니다:

import http.cookiejar
class MyCookiePolicy(http.cookiejar.DefaultCookiePolicy):
    def set_ok(self, cookie, request):
        if not http.cookiejar.DefaultCookiePolicy.set_ok(self, cookie, request):
            return False
        if i_dont_want_to_store_this_cookie(cookie):
            return False
        return True

CookiePolicy 인터페이스를 구현하는 데 필요한 기능 외에도, 이 클래스를 사용하면 도메인이 쿠키를 설정하고 수신하는 것을 차단하고 허락할 수 있도록 합니다. 또한 다소 느슨한 Netscape 프로토콜 규칙을 약간 강화할 수 있는 몇 가지 엄격성 스위치가 있습니다 (일부 양성 쿠키를 차단하는 대가를 치르면서).

A domain blocklist and allowlist is provided (both off by default). Only domains not in the blocklist and present in the allowlist (if the allowlist is active) participate in cookie setting and returning. Use the blocked_domains constructor argument, and blocked_domains() and set_blocked_domains() methods (and the corresponding argument and methods for allowed_domains). If you set an allowlist, you can turn it off again by setting it to None.

점으로 시작하지 않는 차단 또는 수락 목록에 있는 도메인은 일치할 쿠키 도메인과 같아야 합니다. 예를 들어, "example.com"은 차단 목록 항목 "example.com"과 일치하지만, "www.example.com"은 일치하지 않습니다. 점으로 시작하는 도메인은 더 구체적인 도메인과도 일치합니다. 예를 들어, "www.example.com""www.coyote.example.com"은 모두 ".example.com"과 일치합니다 (하지만 "example.com" 자체는 일치하지 않습니다). IP 주소는 예외이며, 정확히 일치해야 합니다. 예를 들어, blocked_domains에 "192.168.1.2"".168.1.2"가 포함되어 있으면, 192.168.1.2는 차단되지만, 193.168.1.2는 차단되지 않습니다.

DefaultCookiePolicy는 다음과 같은 추가 메서드를 구현합니다:

DefaultCookiePolicy.blocked_domains()

차단된 도메인 시퀀스를 반환합니다 (튜플로).

DefaultCookiePolicy.set_blocked_domains(blocked_domains)

차단된 도메인 시퀀스를 설정합니다.

DefaultCookiePolicy.is_blocked(domain)

domain이 쿠키 설정이나 수신에 대한 차단 목록에 있으면 True를 반환합니다.

DefaultCookiePolicy.allowed_domains()

Return None, or the sequence of allowed domains (as a tuple).

DefaultCookiePolicy.set_allowed_domains(allowed_domains)

Set the sequence of allowed domains, or None.

DefaultCookiePolicy.is_not_allowed(domain)

domain이 쿠키 설정이나 수신에 대한 수락 목록에 있으면 True를 반환합니다.

DefaultCookiePolicy 인스턴스에는 다음과 같은 어트리뷰트가 있습니다. 이 어트리뷰트들은 모두 같은 이름의 생성자 인자로 초기화되며, 모두 대입할 수 있습니다.

DefaultCookiePolicy.rfc2109_as_netscape

If true, request that the CookieJar instance downgrade RFC 2109 cookies (that is, cookies received in a Set-Cookie header with a version cookie-attribute of 1) to Netscape cookies by setting the version attribute of the Cookie instance to 0. The default value is None, in which case RFC 2109 cookies are downgraded if and only if RFC 2965 handling is turned off. Therefore, RFC 2109 cookies are downgraded by default.

일반 엄격성 스위치:

DefaultCookiePolicy.strict_domain

사이트가 .co.uk, .gov.uk, .co.nz 등의 국가 코드 최상위 도메인으로 2개의 구성 요소 도메인을 설정하는 것을 수락하지 않습니다. 이것은 완벽하지는 않으며 작동하지 않을 수도 있습니다!

RFC 2965 프로토콜 엄격성 스위치:

DefaultCookiePolicy.strict_rfc2965_unverifiable

확인할 수 없는 트랜잭션(unverifiable transactions)에 대한 RFC 2965 규칙을 따릅니다 (일반적으로 확인할 수 없는 트랜잭션은 다른 사이트에서 호스팅 되는 이미지에 대한 리디렉션이나 요청으로 인한 결과입니다). 이것이 거짓이면, 확인 가능성에 기초하여 쿠키가 차단되지 않습니다.

넷스케이프 프로토콜 엄격성 스위치:

DefaultCookiePolicy.strict_ns_unverifiable

Netscape 쿠키에도 확인할 수 없는 트랜잭션에 대한 RFC 2965 규칙을 적용합니다.

DefaultCookiePolicy.strict_ns_domain

Netscape 쿠키에 대한 도메인 일치 규칙이 얼마나 엄격한지를 나타내는 플래그. 허용 가능한 값은 아래를 참조하십시오.

DefaultCookiePolicy.strict_ns_set_initial_dollar

이름이 '$'로 시작하는 Set-Cookie: 헤더의 쿠키를 무시합니다.

DefaultCookiePolicy.strict_ns_set_path

경로가 요청 URI와 경로 일치하지 않는 쿠키 설정을 수락하지 않습니다.

strict_ns_domain is a collection of flags. Its value is constructed by or-ing together (for example, DomainStrictNoDots|DomainStrictNonDomain means both flags are set).

DefaultCookiePolicy.DomainStrictNoDots

When setting cookies, the ‘host prefix’ must not contain a dot (for example, www.foo.bar.com can’t set a cookie for .bar.com, because www.foo contains a dot).

DefaultCookiePolicy.DomainStrictNonDomain

Cookies that did not explicitly specify a domain cookie-attribute can only be returned to a domain equal to the domain that set the cookie (for example, spam.example.com won’t be returned cookies from example.com that had no domain cookie-attribute).

DefaultCookiePolicy.DomainRFC2965Match

쿠키를 설정할 때, 전체 RFC 2965 도메인 일치가 필요합니다.

편의를 위해 다음 어트리뷰트가 제공되며, 위 플래그의 가장 유용한 조합입니다:

DefaultCookiePolicy.DomainLiberal

Equivalent to 0 (that is, all of the above Netscape domain strictness flags switched off).

DefaultCookiePolicy.DomainStrict

DomainStrictNoDots|DomainStrictNonDomain 과 동등합니다.

The first example shows the most common usage of http.cookiejar:

import http.cookiejar, urllib.request
cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")

이 예는 Netscape, Mozilla 또는 Lynx 쿠키를 사용하여 URL을 여는 방법을 보여줍니다 (쿠키 파일의 위치에 대해서는 유닉스/Netscape 규칙을 가정합니다):

import os, http.cookiejar, urllib.request
cj = http.cookiejar.MozillaCookieJar()
cj.load(os.path.join(os.path.expanduser("~"), ".netscape", "cookies.txt"))
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")

다음 예는 DefaultCookiePolicy 의 사용법을 보여줍니다. RFC 2965 쿠키를 켜고, Netscape 쿠키를 설정하고 반환할 때 도메인에 대해 더욱 엄격하며, 일부 도메인이 쿠키를 설정하거나 쿠키를 반환하지 못하도록 차단합니다:

import urllib.request
from http.cookiejar import CookieJar, DefaultCookiePolicy
policy = DefaultCookiePolicy(
    rfc2965=True, strict_ns_domain=Policy.DomainStrict,
    blocked_domains=["ads.net", ".ads.net"])
cj = CookieJar(policy)
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")