Reputation: 35
So I have a working code that gets data from a website, connects to it if necessary, and save the cookies in a file so they persist each time I launch the code. Here's what the code looks like (obviously I've removed the imports and most of the code to make it more readable)
cookiejar_file = 'tmp/cookies.txt'
cj = http.cookiejar.LWPCookieJar(cookiejar_file)
try:
cj.load(ignore_discard=True)
except:
pass
s = requests.Session()
s.cookies = cj
# Do stuff, connect if necessary by doing a s.post() on the connect page
cj.save(cookiejar_file, ignore_discard=True)
But now that I'm trying to create a much cleaner class doing this job there is a problem: Each time I run the code it has to connect to the website again. So I must be doing something wrong and the cookies are not loaded successfully I guess ?
class Parent:
CookieFile = 'tmp/cookies.txt'
def __init__(self):
self.cj = http.cookiejar.LWPCookieJar(Parent.CookieFile)
self.cj.load()
self.session = requests.Session()
self.session.cookies = self.cj
def save_cookies(self):
self.cj.save(Parent.CookieFile, ignore_discard=True)
class Child(Parent):
def __init__(self):
Parent.__init__(self)
def main(self):
# Do stuff, connect if necessary
self.save_cookies()
a = Child
a.main()
Is there a problem with the way I'm doing this ? To me it looks like it should be doing the exact same thing. The cookie file has successfully been created the first time I executed the code and the cookies change each time I execute it.
Upvotes: 0
Views: 1175
Reputation: 35
Well the problem was simply that I had forgotten the "ignore_discard=True" when I load the Cookiejar.
This works perfectly with Python 3.5.1 and Requests 2.9.1:
import requests
import http.cookiejar
class Parent:
CookieFile = 'tmp/cookies.txt'
def __init__(self):
self.cj = http.cookiejar.LWPCookieJar(Parent.CookieFile)
self.cj.load(ignore_discard=True)
self.session = requests.Session()
self.session.cookies = self.cj
def save_cookies(self):
self.cj.save(Parent.CookieFile, ignore_discard=True)
class Child(Parent):
def __init__(self):
Parent.__init__(self)
def main(self):
# Do stuff, connect if necessary
self.save_cookies()
a = Child
a.main()
Upvotes: 1