Skip to content

Instantly share code, notes, and snippets.

@slingamn
Created May 3, 2012 08:00
Show Gist options
  • Select an option

  • Save slingamn/2584138 to your computer and use it in GitHub Desktop.

Select an option

Save slingamn/2584138 to your computer and use it in GitHub Desktop.

Revisions

  1. slingamn revised this gist May 3, 2012. 1 changed file with 15 additions and 4 deletions.
    19 changes: 15 additions & 4 deletions gistfile1.py
    Original file line number Diff line number Diff line change
    @@ -4,8 +4,15 @@
    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):
    @@ -28,9 +35,13 @@ def get_cookie_form_cj(self, name):


    if __name__ == '__main__':
    URL = 'http://requests.sinaapp.com'
    EXPECTED_VALUE = '\u4E2A\u4EBA'

    uc = UClient()
    uc.req('http://requests.sinaapp.com')
    print "urllib2 and cookielib test:", uc.get_cookie_form_cj('xx') == '\u4E2A\u4EBA'
    uc.req(URL)
    print "urllib2 and cookielib test:", get_cookie_from(uc.cj, 'xx') == EXPECTED_VALUE

    s = session()
    s.get('http://request.sinaapp.com')
    print 'requests test:', s.cookies.get('xx', '') == '\u4E2A\u4EBA'
    s.get(URL)
    print 'requests.session test:', get_cookie_from(s.cookies, 'xx') == EXPECTED_VALUE
  2. ben created this gist Apr 22, 2012.
    36 changes: 36 additions & 0 deletions gistfile1.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    #!/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:', s.cookies.get('xx', '') == '\u4E2A\u4EBA'