Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert requests.cookiejar to qnetworkcookiejar?

Is there a simple way to convert a cookiejar from the Python 3 requests library to a qnetworkcookiejar?

I convert the cookiejar from the requests library into a dictionary and then in a qnetworkcookiejar. Some cookies are there in multiple versions with different values.

def updateCookieJar(self, cookiejar, requested_url):     
    qnetworkcookie_list = []
    cookie_dict = dict_from_cookiejar(cookiejar)
    for cookie in cookie_dict: 
        tmp_cookiejar = QNetworkCookie(cookie, cookie_dict[cookie])
        qnetworkcookie_list.append(tmp_cookiejar)
    qcookiejar = QNetworkCookieJar()
    qcookiejar.setCookiesFromUrl(qnetworkcookie_list, QUrl(requested_url))
    self.networkAccessManager().setCookieJar(qcookiejar)

This function is called inside a Webpage.

like image 453
Pumba Avatar asked Dec 15 '14 08:12

Pumba


People also ask

What is HTTP cookiejar?

The http. cookiejar module defines classes for automatic handling of HTTP cookies. It is useful for accessing web sites 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.

How do you pass cookies in Python request?

To send a request with a Cookie, you need to add the "Cookie: name=value" header to your request. To send multiple cookies in a single Cookie header, separate them with semicolons or add multiple "Cookie: name=value" request headers.

How do you use a cookie jar?

If, however, you are using an older model cookie jar, the answer is quite simple. Just put the cookies in a zip-style plastic bag, seal it up, and put the bag in the jar. Whenever you reach in for a cookie, it's an easy step to open the bag and close it back up to keep those cookies fresh.


1 Answers

Try using cookiejar directly instead of dictionary.

def updateCookieJar(self, cookiejar, requested_url):     
    qnetworkcookie_list = []

    for cookie in cookiejar:
        tmp_cookiejar = QNetworkCookie(cookie.name, cookie.value)
        qnetworkcookie_list.append(tmp_cookiejar)
    qcookiejar = QNetworkCookieJar()
    qcookiejar.setCookiesFromUrl(qnetworkcookie_list, QUrl(requested_url))
    self.networkAccessManager().setCookieJar(qcookiejar)
like image 163
Kashyap Prajapati Avatar answered Sep 22 '22 07:09

Kashyap Prajapati