当前位置:
首页 > temp > Python基础教程 >
-
Python3标准库:http.cookies HTTP cookie
1. http.cookies HTTP cookie
http.cookies模块为大多数符合RFC2109的cookie实现一个解析器。这个实现没有标准那么严格,因为MSIE3.0x不支持完整的标准。
1.1 创建和设置cookie
可以用cookie为基于浏览器的应用实现状态管理,因此,cookie通常由服务器设置,并由客户存储和返回。下面给出一个最简单的例子,创建一个cookie设置一个键值对。
- from http import cookies
- c = cookies.SimpleCookie()
- c['mycookie'] = 'cookie_value'
- print(c)
输出是一个合法的Set-Cookie首部,可以作为HTTP响应的一部分传递到客户。
1.2 Morsel
还可以控制 cookie的其他方面,如到期时间、路径和域。实际上,cookie的所有RFC属性都可以通过表示cookie值的Morse1对象来管理。
- from http import cookies
- import datetime
- def show_cookie(c):
- print(c)
- for key, morsel in c.items():
- print()
- print('key =', morsel.key)
- print(' value =', morsel.value)
- print(' coded_value =', morsel.coded_value)
- for name in morsel.keys():
- if morsel[name]:
- print(' {} = {}'.format(name, morsel[name]))
- c = cookies.SimpleCookie()
- # A cookie with a value that has to be encoded
- # to fit into the header
- c['encoded_value_cookie'] = '"cookie,value;"'
- c['encoded_value_cookie']['comment'] = 'Has escaped punctuation'
- # A cookie that only applies to part of a site
- c['restricted_cookie'] = 'cookie_value'
- c['restricted_cookie']['path'] = '/sub/path'
- c['restricted_cookie']['domain'] = 'PyMOTW'
- c['restricted_cookie']['secure'] = True
- # A cookie that expires in 5 minutes
- c['with_max_age'] = 'expires in 5 minutes'
- c['with_max_age']['max-age'] = 300 # seconds
- # A cookie that expires at a specific time
- c['expires_at_time'] = 'cookie_value'
- time_to_live = datetime.timedelta(hours=1)
- expires = (datetime.datetime(2020, 4, 8, 18, 30, 14) +
- time_to_live)
- # Date format: Wdy, DD-Mon-YY HH:MM:SS GMT
- expires_at_time = expires.strftime('%a, %d %b %Y %H:%M:%S')
- c['expires_at_time']['expires'] = expires_at_time
- show_cookie(c)
这个例子使用两个不同的方法设置到期的cookie。其中一个方法将max-age设置为一个秒数,另一个方法将expires设置为一个日期时间,达到这个日期时间就会丢弃这个cookie。
Cookie和Morsel对象都相当于字典。Morsel响应一个固定的键集。
expires
path
comment
domain
secure
version
Cookie实例的键是所存储的各个cookie的名。这个信息也可以从Morsel的键属性得到。
1.3 编码的值
cookie首部值必须经过编码才能被正确的解析。
- from http import cookies
- c = cookies.SimpleCookie()
- c['integer'] = 5
- c['with_quotes'] = 'He said, "Hello, World!"'
- for name in ['integer', 'with_quotes']:
- print(c[name].key)
- print(' {}'.format(c[name]))
- print(' value={!r}'.format(c[name].value))
- print(' coded_value={!r}
最新更新
Beginner with c# 3
Beginner with c# 2
Beginner with C# 1
用C#创建Web应用程序
SUNWEN教程之----C#进阶十
SUNWEN教程之----C#进阶九
SUNWEN教程之----C#进阶八
SUNWEN教程之----C#进阶七
SUNWEN教程之----C#进阶六
SUNWEN教程之----C#进阶五
【15天掌握SQLServer基础】-01 创建、修改
用 Access+Outlook 来采集信息
使用PowerDesigner生成Access数据库
让我们一起用开源数据库和开源框架废弃
随说秋色园从Access升迁到MSSQL过程
当爬虫被拒绝时(Access Denied)
Web API与OAuth:既生access token,何生refres
[认证 & 授权] 6. Permission Based Access Co
Access之C#连接Access
oracle 19c下载和安装教程(database和client)
php的计数器每次都会清零
PHP基础
数据类型之对象
数据类型之布尔型、整型、浮点型和字符
php教程之数据类型之数组
php教程之PHP 常量
php教程之变量
php教程之语法
PHP简介与安装
phpMyAdmin配置安装全攻略