杰瑞科技汇

Python SimpleCookie如何使用?

Of course! Let's dive into SimpleCookie from Python's standard library.

Python SimpleCookie如何使用?-图1
(图片来源网络,侵删)

What is SimpleCookie?

SimpleCookie is a class in Python's http.cookies module. Its primary purpose is to parse, create, and manage HTTP cookies. It handles the messy details of cookie formatting, such as the special string format used in the Cookie HTTP header.

Think of it as a smart dictionary that understands the rules of cookies.


Key Features

  1. Parsing: It can take a raw cookie string (e.g., from an HTTP request header) and convert it into a dictionary-like object where you can easily access the values.
  2. Serialization: It can take a dictionary of your data and convert it into the proper string format for an HTTP response header.
  3. Morsels: Each cookie is stored as a "morsel." A morsel is more than just a key-value pair; it also contains cookie attributes like Path, Domain, Expires, Secure, HttpOnly, etc.
  4. Security: It provides a safe way to encode and decode values, preventing common issues.

The Core Concept: Morsels

When you work with SimpleCookie, you're not directly working with a dictionary. You're working with a SimpleCookie object, which acts like a dictionary of Morsel objects.

  • Key: The name of the cookie (e.g., username).
  • Value: The value of the cookie (e.g., jane_doe).
  • Morsel: The combination of the key, value, and all its associated attributes (Path, Max-Age, etc.).

Example 1: Creating and Serializing Cookies (Server Response)

This is the most common use case on a server. You have data, and you want to send it to the client as one or more cookies.

Python SimpleCookie如何使用?-图2
(图片来源网络,侵删)
from http.cookies import SimpleCookie
import datetime
# 1. Create a SimpleCookie object
c = SimpleCookie()
# 2. Set values for cookies. This automatically creates Morsel objects.
c['username'] = 'jane_doe'
c['session_id'] = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890'
c['prefers_dark_mode'] = 'true'
# 3. Set attributes for the cookies (these are Morsel properties)
c['username']['path'] = '/'
c['username']['domain'] = '.example.com'
c['username']['expires'] = (datetime.datetime.now() + datetime.timedelta(days=30)).strftime("%a, %d-%b-%Y %H:%M:%S GMT")
c['session_id']['path'] = '/app'
c['session_id']['httponly'] = True  # No JavaScript access
c['session_id']['secure'] = True    # Only sent over HTTPS
c['prefers_dark_mode']['path'] = '/'
# 4. Serialize the cookies to a string for an HTTP response header
# This is the magic part!
output_header = c.output(header='').strip() # .output(header='') removes the "Set-Cookie: " prefix
print("HTTP Response Header:")
print("Set-Cookie: " + output_header)

Output:

HTTP Response Header:
Set-Cookie: username=jane_doe; Path=/; Domain=.example.com; expires=Tue, 14-Nov-2025 15:30:00 GMT; session_id=a1b2c3d4-e5f6-7890-abcd-ef1234567890; Path=/app; httponly; secure; prefers_dark_mode=true; Path=/

Notice how SimpleCookie correctly formats each cookie with its attributes, separated by semicolons.


Example 2: Parsing Cookies (Server Request)

When a client sends a request to your server, it includes a Cookie header. SimpleCookie is perfect for parsing this.

from http.cookies import SimpleCookie
# 1. A raw cookie string from an HTTP request header
# (Imagine this came from the client's browser)
cookie_string = (
    "username=john_doe; "
    "theme=light; "
    "last_visit=2025-10-27T10:00:00Z; "
    "session_id=e9f8a7b6-c5d4-3210-fedc-ba9876543210"
)
# 2. Create a SimpleCookie object and load the string
c = SimpleCookie()
c.load(cookie_string)
# 3. Access the cookie values. It behaves like a dictionary.
print(f"Username: {c['username'].value}")
print(f"Theme: {c['theme'].value}")
print(f"Session ID: {c['session_id'].value}")
# 4. Access attributes of a specific cookie (the Morsel)
# Note: The client usually doesn't send attributes like 'expires' back,
# but the structure is there.
print(f"Session ID was set with path: {c['session_id'].get('path', 'Not specified')}")
# You can also check if an attribute exists
if 'httponly' in c['session_id']:
    print("The session_id cookie is HttpOnly.")
else:
    print("The session_id cookie is NOT HttpOnly.")

Output:

Python SimpleCookie如何使用?-图3
(图片来源网络,侵删)
Username: john_doe
Theme: light
Session ID: e9f8a7b6-c5d4-3210-fedc-ba9876543210
Session ID was set with path: Not specified
The session_id cookie is NOT HttpOnly.

Important Security Note: quote and unquote

Cookie values can't contain just any character (like spaces or semicolons). SimpleCookie handles this automatically by URL-encoding (quoting) values when you serialize them and decoding (unquoting) them when you parse them.

You don't usually need to call these methods yourself, but it's good to know they exist.

from http.cookies import SimpleCookie
# A value with a space
c = SimpleCookie()
c['user prefs'] = 'large text'
# When serialized, the space becomes a plus sign (%20 in URL encoding)
print(c.output())
# Output: Set-Cookie: user prefs=large+text
# When parsed, it's automatically decoded back
c2 = SimpleCookie()
c2.load('user prefs=large+text')
print(c2['user prefs'].value)
# Output: large text

SimpleCookie vs. Morsel

  • SimpleCookie: The main container. It's a dictionary-like object that holds multiple Morsel objects. Use this for managing a set of cookies.
  • Morsel: A single cookie item (key, value, and attributes). You interact with Morsel objects when you need to set specific attributes like Path or Expires.

Summary: When to Use SimpleCookie

Use SimpleCookie whenever you are building a web application or script that needs to interact with HTTP cookies. It simplifies the process of:

  • Reading cookies from an incoming request.
  • Writing cookies to an outgoing response.
  • Managing cookie attributes (Path, Domain, Secure, etc.) in a clean, structured way.
分享:
扫描分享到社交APP
上一篇
下一篇