|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +import cookielib |
| 4 | +import urllib2 |
| 5 | + |
| 6 | + |
| 7 | +def creat_cookie(name, value, **kwargs): |
| 8 | + result = { |
| 9 | + 'version': 0, |
| 10 | + 'name': name, |
| 11 | + 'value': value, |
| 12 | + 'port': None, |
| 13 | + 'domain': '', |
| 14 | + 'path': '/', |
| 15 | + 'secure': False, |
| 16 | + 'expires': None, |
| 17 | + 'discard': True, |
| 18 | + 'comment': None, |
| 19 | + 'comment_url': None, |
| 20 | + 'rest': {'HttpOnly': None}, |
| 21 | + 'rfc2109': False, |
| 22 | + } |
| 23 | + result.update(kwargs) |
| 24 | + result['port_specified'] = bool(result['port']) |
| 25 | + result['domain_specified'] = bool(result['domain']) |
| 26 | + result['domain_initial_dot'] = result['domain'].startswith('.') |
| 27 | + result['path_specified'] = bool(result['path']) |
| 28 | + |
| 29 | + return cookielib.Cookie(**result) |
| 30 | + |
| 31 | + |
| 32 | +def header(): |
| 33 | + cookie_jar = cookielib.CookieJar() |
| 34 | + cookie_handler = urllib2.HTTPCookieProcessor(cookie_jar) |
| 35 | + opener = urllib2.build_opener(cookie_handler) |
| 36 | + |
| 37 | + request = urllib2.Request("http://httpbin.org/cookies") |
| 38 | + request.add_header("Cookie", "name=windard") |
| 39 | + |
| 40 | + resp = opener.open(request) |
| 41 | + print resp.read() |
| 42 | + |
| 43 | + for cookie in cookie_jar: |
| 44 | + print cookie.name, ":", cookie.value |
| 45 | + |
| 46 | + |
| 47 | +def main(): |
| 48 | + cookie_jar = cookielib.CookieJar() |
| 49 | + cookie_handler = urllib2.HTTPCookieProcessor(cookie_jar) |
| 50 | + opener = urllib2.build_opener(cookie_handler) |
| 51 | + cookie_jar.set_cookie(creat_cookie("name", "Windard")) |
| 52 | + cookie_jar.set_cookie(creat_cookie("location", "Shanghai")) |
| 53 | + |
| 54 | + resp = opener.open("http://httpbin.org/cookies") |
| 55 | + print resp.read() |
| 56 | + |
| 57 | + for cookie in cookie_jar: |
| 58 | + print cookie.name, ":", cookie.value |
| 59 | + |
| 60 | + |
| 61 | +if __name__ == '__main__': |
| 62 | + header() |
0 commit comments