Created
May 3, 2012 08:00
-
-
Save slingamn/2584138 to your computer and use it in GitHub Desktop.
requests cookie test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# coding:utf-8 | |
import urllib | |
import urllib2 | |
import cookielib | |
import requests | |
from requests import session | |
def get_cookie_from(cj, name): | |
for cookie in cj: | |
if cookie.name == name: | |
return cookie.value | |
return None | |
class UClient(object): | |
def __init__(self): | |
self.cj = cookielib.CookieJar() | |
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj)) | |
def req(self, url, params=None): | |
if params is None: | |
req = urllib2.Request(url) | |
if isinstance(params, (tuple, dict)): | |
req = urllib2.Request(url, urllib.urlencode(params)) | |
else: | |
req = urllib2.Request(url, params) | |
return self.opener.open(req) | |
def get_cookie_form_cj(self, name): | |
for cookie in self.cj: | |
if cookie.name == name: | |
return cookie.value | |
if __name__ == '__main__': | |
URL = 'http://requests.sinaapp.com' | |
EXPECTED_VALUE = '\u4E2A\u4EBA' | |
uc = UClient() | |
uc.req(URL) | |
print "urllib2 and cookielib test:", get_cookie_from(uc.cj, 'xx') == EXPECTED_VALUE | |
s = session() | |
s.get(URL) | |
print 'requests.session test:', get_cookie_from(s.cookies, 'xx') == EXPECTED_VALUE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment