如何在 Python CGI Programming 中设置 cookies?

如何在 Python CGI Programming 中设置 cookies?

在网络应用中,cookie是非常常见的一个概念。通过cookie,服务器可以在客户端存储数据,以便在客户端的请求中当做参数使用。Python CGI Programming也可以使用cookie,下面我们将结合示例代码讲述如何在Python CGI Programming中设置cookies。

阅读更多:Python 教程

什么是cookie?

Cookie是存储在浏览器上的一个小文本文件,它的最大特点是可以存储会话状态,或者是客户端的信息。他记录了用户访问过的网站,保存了这些信息,在下一次同样访问这个网站的时候,会自动把这些信息带到这个网站中。而且cookie 还有存储时间,时间过后cookie就会过期,就像牛奶一样过期后不能再喝,cookie过期后也不能再用。

创建 Cookie

下面是一个Python CGI Programming设置cookie的示例代码:

#!/usr/bin/env python
import cgi
import cgitb
import os
import datetime

import hashlib
import binascii
import hmac
import random 

cgitb.enable()

expiration_date = datetime.datetime.now() + datetime.timedelta(days=10)
expiration_timestamp = expiration_date.strftime("%a, %d-%b-%Y %H:%M:%S GMT")

def get_secure_cookie(secret_cookie):
    """Return secure cookie from plain text"""
    secure_cookie = hmac.new(secret_cookie.encode(), os.urandom(20))
    return binascii.hexlify(secure_cookie.digest()).decode()

cookie_name = "mycookie"
cookie_value = get_secure_cookie("secret")
print("Content-type: text/html")
print("Set-Cookie: {0}={1}; expires={2}".format(cookie_name, cookie_value, expiration_timestamp))
print("")
print("<html><head>")
print("<title>Python CGI Programming - Set Cookies Demo</title>")
print("</head><body>")
print("<h3>Python CGI Programming - Set Cookies Demo</h3>")
print("<p>")
print("cookie_name: {}".format(cookie_name))
print("<br/>")
print("cookie_value: {}".format(cookie_value))
print("</p>")
print("</body></html>")

代码实现功能:

  1. 生成mycookie cookie键值对
  2. secret作为密钥将cookie变为sha1形式
  3. 将cookie键值对和过期时间一起放入响应头中,用Set-Cookie:返回
  4. 在响应体输出cookie的键值对,并用exit方法退出程序

在浏览器中访问该cgi程序会产生如下响应,放在请求头中的Set-Cookie已经可以看到

HTTP/1.0 200 OK
Content-type: text/html
Set-Cookie: mycookie=b17cfdd80afc84cbd5f1c95d3acb2d160798e806; expires=Sun, 15 Aug 2021 07:14:56 GMT

<html><head>
<title>Python CGI Programming - Set Cookies Demo</title>
</head><body>
<h3>Python CGI Programming - Set Cookies Demo</h3>
<p>
cookie_name: mycookie
<br/>
cookie_value: b17cfdd80afc84cbd5f1c95d3acb2d160798e806
</p>
</body></html>%

读取 Cookie

要读取cookie,我们需要使用Python CGI Programming的Cookie模块。下面是段读取cookie的代码示例:

#!/usr/bin/env python
import cgi
import cgitb
import os
import datetime

import hashlib
import binascii
import hmac
import random 
import http.cookies

cgitb.enable()
cookie = http.cookies.SimpleCookie(os.environ.get("HTTP_COOKIE"))
cookie_name = "mycookie"

print("Content-type: text/html")
print("")
print("<html><head>")
print("<title>Python CGI Programming - Get Cookies Demo</title>")
print("</head><body>")
print("<h3>Python CGI Programming - Set Cookies Demo</h3>")
print("<p>")
if cookie.get(cookie_name) is not None:
    print("cookie_name: {}".format(cookie.get(cookie_name)))
else:
    print("cookie {} is not set".format(cookie_name))
print("</p>")
print("</body></html>")

代码实现功能:

  1. 从请求头中获取cookie,并用http.cookies.SimpleCookie()转换为对象
  2. 通过cookie对象获取指定cookie键值对,输出结果

在浏览器中访问该cgi程序会产生如下响应,

HTTP/1.0 200 OK
Content-type: text/html

<html><head>
<title>Python CGI Programming - Get Cookies Demo</title>
</head><body>
<h3>Python CGI Programming - Set Cookies Demo</h3>
<p>
cookie_name: mycookie=b17cfdd80afc84cbd5f1c95d3acb2d160798e806
</p>
</body></html>

删除 Cookie

要删除cookie,我们需要通过设置expires字段将cookie的过期时间设置为过去的时间,以使cookie过期。下面是一个示例代码:

#!/usr/bin/env python
import cgi
import cgitb
import os
import datetime

import hashlib
import binascii
import hmac
import random 
import http.cookies

cgitb.enable()
cookie_name = "mycookie"

expiration_date = datetime.datetime.now() - datetime.timedelta(days=10)
expiration_timestamp = expiration_date.strftime("%a, %d-%b-%Y %H:%M:%S GMT")

print("Content-type: text/html")
print("Set-Cookie: {0}=deleted; expires={1}".format(cookie_name, expiration_timestamp))
print("")
print("<html><head>")
print("<title>Python CGI Programming - Delete Cookies Demo</title>")
print("</head><body>")
print("<h3>Python CGI Programming - Delete Cookies Demo</h3>")
print("<p>")
print("cookie {} deleted.".format(cookie_name))
print("</p>")
print("</body></html>")

代码实现功能:

  1. 通过设置expires字段把cookie标记为已过期
  2. 在响应头中设置该cookie已过期,返回一个Set-Cookie:

在浏览器中访问该cgi程序会产生如下响应,

HTTP/1.0 200 OK
Content-type: text/html
Set-Cookie: mycookie=deleted; expires=Wed, 04 Aug 2021 07:34:59 GMT

<html><head>
<title>Python CGI Programming - Delete Cookies Demo</title>
</head><body>
<h3>Python CGI Programming - Delete Cookies Demo</h3>
<p>
cookie mycookie deleted.
</p>
</body></html>

注意,设置cookie的时候,如果需要设置多个cookie,可以在Set-Cookie:字段后面追加多个cookie键值对,用分号隔开即可。

结论

在Python CGI Programming中,设置和读取cookie非常简单,只需要使用http.cookies模块即可实现。无论是设置、读取还是删除cookie,都非常简单。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程