Skip to content

Instantly share code, notes, and snippets.

@slingamn
Created May 3, 2012 07:31
Show Gist options
  • Save slingamn/2584020 to your computer and use it in GitHub Desktop.
Save slingamn/2584020 to your computer and use it in GitHub Desktop.
requests cookie test
#!/usr/bin/env python
# coding:utf-8
import urllib
import urllib2
import cookielib
from requests import session
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__':
uc = UClient()
uc.req('http://requests.sinaapp.com')
print "urllib2 and cookielib test:", uc.get_cookie_form_cj('xx') == '\u4E2A\u4EBA'
s = session()
s.get('http://request.sinaapp.com')
print 'requests test:', uc.get_cookie_form_cj('xx') == '\u4E2A\u4EBA'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment