Python http.cookiejar exception and classes

Python http.cookiejar exception and classes

HTTP.cookiejar defines the following exception:


This is the exception that is raises when the FileCookieJar fails to load cookies from a file.

Note: LoadError is a subclass of OSError and earlier it was subclass of IOError but it was changes in version 3.3

HTTP.cookiejar defines the following classes:

a.)     class http.cookiejar.CookieJar(policy=None)

The Cookiejar is used to store HTTP cookies. It simply extracts the cookies from HTTP requests and returns them in HTTP responses and instances of this class is automatically expires when they are not used anymore. Subclasses are also responsible for storing and retrieving cookies from a file or database.


import http.cookiejar, urllib.request

cj = http.cookiejar.CookieJar()

opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))

r ="")

print (r)


class http.cookiejar.FileCookieJar(filenamedelayload=Nonepolicy=None)

This class helps to load cookies and save them to a file on disk. Cookies cannot be loaded until load() or revert() method is called.

filename- Name of the file  that we want to load

policy - it is responsible whether cookie should be accepted or returned back to the server.


from http.cookiejar import MozillaCookieJar

import requests

s = requests.Session()

s.cookies = MozillaCookieJar('cookies.txt')

response = s.get('')


A file will be saved on your system


class http.cookiejar.DefaultCookiePolicy(blocked_domains=Noneallowed_domains=Nonenetscape=Truerfc2965=Falserfc2109_as_netscape=Nonehide_cookie2=Falsestrict_domain=Falsestrict_rfc2965_unverifiable=Truestrict_ns_unverifiable=Falsestrict_ns_domain=DefaultCookiePolicy.DomainLiberalstrict_ns_set_initial_dollar=Falsestrict_ns_set_path=Falsesecure_protocols=("https""wss"))

blocked_domains - These are the domains from where cookies are never accepted

allowed_domains- These are the domains or sequence of domains from where cookies are accepted.

secure_protocols- These are the sequence of protocols for which secure cookies can be added to . HTTPS and wss are considered to be secured protocols by default

DefaultCookiePolicy imnplements the standard accept and reject rules for Netscape and RFC 2965 cookies and by default RFC 2109 Cookies are treated according to RFC 2965 rules and if we turn off the the RFC 2965 handling RFC 2109 cookies are downgraded by the cookiejar to Netscape cookies by setting the version attribute of cookies instance to 0.

Next Article :