HTTP.cookiejar defines the following exception:
http.cookiejar.LoadError
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.
CODE:-
import http.cookiejar, urllib.request
cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
r = opener.open("http://google.com/")
print (r)
OUTPUT:
class http.cookiejar.FileCookieJar
(filename, delayload=None, policy=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.
CODE:-
from http.cookiejar import MozillaCookieJar
import requests
s = requests.Session()
s.cookies = MozillaCookieJar('cookies.txt')
response = s.get('https://www.google.com')
s.cookies.save()
OUTPUT:-
A file will be saved on your system
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"))
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.
Comments