VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • Python3标准库:http.cookies HTTP cookie

1. http.cookies HTTP cookie

http.cookies模块为大多数符合RFC2109的cookie实现一个解析器。这个实现没有标准那么严格,因为MSIE3.0x不支持完整的标准。

1.1 创建和设置cookie

可以用cookie为基于浏览器的应用实现状态管理,因此,cookie通常由服务器设置,并由客户存储和返回。下面给出一个最简单的例子,创建一个cookie设置一个键值对。


  1. from http import cookies
  2.  
  3. c = cookies.SimpleCookie()
  4. c['mycookie'] = 'cookie_value'
  5. print(c)

输出是一个合法的Set-Cookie首部,可以作为HTTP响应的一部分传递到客户。

1.2 Morsel

还可以控制 cookie的其他方面,如到期时间、路径和域。实际上,cookie的所有RFC属性都可以通过表示cookie值的Morse1对象来管理。


  1. from http import cookies
  2. import datetime
  3.  
  4. def show_cookie(c):
  5. print(c)
  6. for key, morsel in c.items():
  7. print()
  8. print('key =', morsel.key)
  9. print(' value =', morsel.value)
  10. print(' coded_value =', morsel.coded_value)
  11. for name in morsel.keys():
  12. if morsel[name]:
  13. print(' {} = {}'.format(name, morsel[name]))
  14.  
  15. c = cookies.SimpleCookie()
  16.  
  17. # A cookie with a value that has to be encoded
  18. # to fit into the header
  19. c['encoded_value_cookie'] = '"cookie,value;"'
  20. c['encoded_value_cookie']['comment'] = 'Has escaped punctuation'
  21.  
  22. # A cookie that only applies to part of a site
  23. c['restricted_cookie'] = 'cookie_value'
  24. c['restricted_cookie']['path'] = '/sub/path'
  25. c['restricted_cookie']['domain'] = 'PyMOTW'
  26. c['restricted_cookie']['secure'] = True
  27.  
  28. # A cookie that expires in 5 minutes
  29. c['with_max_age'] = 'expires in 5 minutes'
  30. c['with_max_age']['max-age'] = 300 # seconds
  31.  
  32. # A cookie that expires at a specific time
  33. c['expires_at_time'] = 'cookie_value'
  34. time_to_live = datetime.timedelta(hours=1)
  35. expires = (datetime.datetime(2020, 4, 8, 18, 30, 14) +
  36. time_to_live)
  37.  
  38. # Date format: Wdy, DD-Mon-YY HH:MM:SS GMT
  39. expires_at_time = expires.strftime('%a, %d %b %Y %H:%M:%S')
  40. c['expires_at_time']['expires'] = expires_at_time
  41.  
  42. show_cookie(c)

这个例子使用两个不同的方法设置到期的cookie。其中一个方法将max-age设置为一个秒数,另一个方法将expires设置为一个日期时间,达到这个日期时间就会丢弃这个cookie。

Cookie和Morsel对象都相当于字典。Morsel响应一个固定的键集。 

expires

path

comment

domain

secure

version

Cookie实例的键是所存储的各个cookie的名。这个信息也可以从Morsel的键属性得到。

1.3 编码的值

cookie首部值必须经过编码才能被正确的解析。


  1. from http import cookies
  2.  
  3. c = cookies.SimpleCookie()
  4. c['integer'] = 5
  5. c['with_quotes'] = 'He said, "Hello, World!"'
  6.  
  7. for name in ['integer', 'with_quotes']:
  8. print(c[name].key)
  9. print(' {}'.format(c[name]))
  10. print(' value={!r}'.format(c[name].value))
  11. print(' coded_value={!r}