Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert cookies as dict to cookies as string for HTTP request

Tags:

python

I have the following cookie, stored as a dict:

cookies = session.cookies.get_dict()
{'nflx-rgn': '"ue1|1433799654706|uw2:2"', 'SecureNetflixId': 'v%3D2%26mac%3DAQEAEQABABTh6lNR0cbOgGRD7DT7CChBIhA83qsfV_k.%26dt%3D1433799654968', 'memclid': '9a55d2c6-4d85-44bb-8338-0b1a180a7c44', 'NetflixId': 'v%3D2%26ct%3DBQAOAAEBEFP07qwktIitvHYO-Xn6gU2BYKymzutSFtIyfD_zEWVo4yMjbjJ4LgPmtZhjgE5lRWg5OTP8C1N2zNbTc8VsdzUS3OaLnsGsV4AkXZzkewt0X0WcMwSYVl3-pX8Rs0jH2PCXixD8K2oARmtQIrWCvv35EUOpGCb3v-tExqpZaN_6FBfTrF68FXcR4kDGAjXYooBWKnCv1aS1VVscso_GRg6HH7--qOsjW7WoPkxyRAAqt0GmeD8tY5aQHMbD779s7oiAr7YArEmUC_3Hdej0huyGo0Iq-_IlY_jGZhyupIO0ZIpznvGB2teF8YeaiSh2LlQ4RIlUOo3hO5n9lmlmBnRXAYGYbJ_64HiwTfsw3jRWkgAJWnnxSHo9sGLJibspLCQ3RzdA-JwxSPYoBh-HkhnAxxPveWmPbH_1JtXR9rvhfnenIhDgzu_nCUH7i-sxg4bnKhGjpVzH1Y8x9wSNE2-xWdax912FBEzQWyT5I2HxnQQ.%26bt%3Dusr%26ch%3DAQEAEAABABRxRbrqqSNQFSxPcuqeaLCNvVMfYe40K6A.%26mac%3DAQEAEAABABTQs51fmHZefZn26dZQFm9ZDMjlNgmXis8.', 'tlr': 'US|1433799655947'}

How would I then add that to my requests header so it would be valid. For example:

headers = {
        "Accept-Language" : "en-US,en;q=0.8,pt;q=0.6",
        "Connection" : "keep-alive",
        "Cookies": ???
}
requests.get(url, headers=headers)

I would prefer to do this over adding in the cookies argument to requests.

like image 541
David542 Avatar asked Jun 08 '15 21:06

David542


1 Answers

Use this:

cookie_string = "; ".join([str(x)+"="+str(y) for x,y in cookies.items()])
headers = {
        "Accept-Language" : "en-US,en;q=0.8,pt;q=0.6",
        "Connection" : "keep-alive",
        "Cookies": cookie_string
}
requests.get(url, headers=headers)
like image 162
Tuan Anh Hoang-Vu Avatar answered Sep 18 '22 04:09

Tuan Anh Hoang-Vu