jpayne@68
|
1 ####
|
jpayne@68
|
2 # Copyright 2000 by Timothy O'Malley <timo@alum.mit.edu>
|
jpayne@68
|
3 #
|
jpayne@68
|
4 # All Rights Reserved
|
jpayne@68
|
5 #
|
jpayne@68
|
6 # Permission to use, copy, modify, and distribute this software
|
jpayne@68
|
7 # and its documentation for any purpose and without fee is hereby
|
jpayne@68
|
8 # granted, provided that the above copyright notice appear in all
|
jpayne@68
|
9 # copies and that both that copyright notice and this permission
|
jpayne@68
|
10 # notice appear in supporting documentation, and that the name of
|
jpayne@68
|
11 # Timothy O'Malley not be used in advertising or publicity
|
jpayne@68
|
12 # pertaining to distribution of the software without specific, written
|
jpayne@68
|
13 # prior permission.
|
jpayne@68
|
14 #
|
jpayne@68
|
15 # Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
|
jpayne@68
|
16 # SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
jpayne@68
|
17 # AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR
|
jpayne@68
|
18 # ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
jpayne@68
|
19 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
|
jpayne@68
|
20 # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
|
jpayne@68
|
21 # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
jpayne@68
|
22 # PERFORMANCE OF THIS SOFTWARE.
|
jpayne@68
|
23 #
|
jpayne@68
|
24 ####
|
jpayne@68
|
25 #
|
jpayne@68
|
26 # Id: Cookie.py,v 2.29 2000/08/23 05:28:49 timo Exp
|
jpayne@68
|
27 # by Timothy O'Malley <timo@alum.mit.edu>
|
jpayne@68
|
28 #
|
jpayne@68
|
29 # Cookie.py is a Python module for the handling of HTTP
|
jpayne@68
|
30 # cookies as a Python dictionary. See RFC 2109 for more
|
jpayne@68
|
31 # information on cookies.
|
jpayne@68
|
32 #
|
jpayne@68
|
33 # The original idea to treat Cookies as a dictionary came from
|
jpayne@68
|
34 # Dave Mitchell (davem@magnet.com) in 1995, when he released the
|
jpayne@68
|
35 # first version of nscookie.py.
|
jpayne@68
|
36 #
|
jpayne@68
|
37 ####
|
jpayne@68
|
38
|
jpayne@68
|
39 r"""
|
jpayne@68
|
40 Here's a sample session to show how to use this module.
|
jpayne@68
|
41 At the moment, this is the only documentation.
|
jpayne@68
|
42
|
jpayne@68
|
43 The Basics
|
jpayne@68
|
44 ----------
|
jpayne@68
|
45
|
jpayne@68
|
46 Importing is easy...
|
jpayne@68
|
47
|
jpayne@68
|
48 >>> from http import cookies
|
jpayne@68
|
49
|
jpayne@68
|
50 Most of the time you start by creating a cookie.
|
jpayne@68
|
51
|
jpayne@68
|
52 >>> C = cookies.SimpleCookie()
|
jpayne@68
|
53
|
jpayne@68
|
54 Once you've created your Cookie, you can add values just as if it were
|
jpayne@68
|
55 a dictionary.
|
jpayne@68
|
56
|
jpayne@68
|
57 >>> C = cookies.SimpleCookie()
|
jpayne@68
|
58 >>> C["fig"] = "newton"
|
jpayne@68
|
59 >>> C["sugar"] = "wafer"
|
jpayne@68
|
60 >>> C.output()
|
jpayne@68
|
61 'Set-Cookie: fig=newton\r\nSet-Cookie: sugar=wafer'
|
jpayne@68
|
62
|
jpayne@68
|
63 Notice that the printable representation of a Cookie is the
|
jpayne@68
|
64 appropriate format for a Set-Cookie: header. This is the
|
jpayne@68
|
65 default behavior. You can change the header and printed
|
jpayne@68
|
66 attributes by using the .output() function
|
jpayne@68
|
67
|
jpayne@68
|
68 >>> C = cookies.SimpleCookie()
|
jpayne@68
|
69 >>> C["rocky"] = "road"
|
jpayne@68
|
70 >>> C["rocky"]["path"] = "/cookie"
|
jpayne@68
|
71 >>> print(C.output(header="Cookie:"))
|
jpayne@68
|
72 Cookie: rocky=road; Path=/cookie
|
jpayne@68
|
73 >>> print(C.output(attrs=[], header="Cookie:"))
|
jpayne@68
|
74 Cookie: rocky=road
|
jpayne@68
|
75
|
jpayne@68
|
76 The load() method of a Cookie extracts cookies from a string. In a
|
jpayne@68
|
77 CGI script, you would use this method to extract the cookies from the
|
jpayne@68
|
78 HTTP_COOKIE environment variable.
|
jpayne@68
|
79
|
jpayne@68
|
80 >>> C = cookies.SimpleCookie()
|
jpayne@68
|
81 >>> C.load("chips=ahoy; vienna=finger")
|
jpayne@68
|
82 >>> C.output()
|
jpayne@68
|
83 'Set-Cookie: chips=ahoy\r\nSet-Cookie: vienna=finger'
|
jpayne@68
|
84
|
jpayne@68
|
85 The load() method is darn-tootin smart about identifying cookies
|
jpayne@68
|
86 within a string. Escaped quotation marks, nested semicolons, and other
|
jpayne@68
|
87 such trickeries do not confuse it.
|
jpayne@68
|
88
|
jpayne@68
|
89 >>> C = cookies.SimpleCookie()
|
jpayne@68
|
90 >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
|
jpayne@68
|
91 >>> print(C)
|
jpayne@68
|
92 Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
|
jpayne@68
|
93
|
jpayne@68
|
94 Each element of the Cookie also supports all of the RFC 2109
|
jpayne@68
|
95 Cookie attributes. Here's an example which sets the Path
|
jpayne@68
|
96 attribute.
|
jpayne@68
|
97
|
jpayne@68
|
98 >>> C = cookies.SimpleCookie()
|
jpayne@68
|
99 >>> C["oreo"] = "doublestuff"
|
jpayne@68
|
100 >>> C["oreo"]["path"] = "/"
|
jpayne@68
|
101 >>> print(C)
|
jpayne@68
|
102 Set-Cookie: oreo=doublestuff; Path=/
|
jpayne@68
|
103
|
jpayne@68
|
104 Each dictionary element has a 'value' attribute, which gives you
|
jpayne@68
|
105 back the value associated with the key.
|
jpayne@68
|
106
|
jpayne@68
|
107 >>> C = cookies.SimpleCookie()
|
jpayne@68
|
108 >>> C["twix"] = "none for you"
|
jpayne@68
|
109 >>> C["twix"].value
|
jpayne@68
|
110 'none for you'
|
jpayne@68
|
111
|
jpayne@68
|
112 The SimpleCookie expects that all values should be standard strings.
|
jpayne@68
|
113 Just to be sure, SimpleCookie invokes the str() builtin to convert
|
jpayne@68
|
114 the value to a string, when the values are set dictionary-style.
|
jpayne@68
|
115
|
jpayne@68
|
116 >>> C = cookies.SimpleCookie()
|
jpayne@68
|
117 >>> C["number"] = 7
|
jpayne@68
|
118 >>> C["string"] = "seven"
|
jpayne@68
|
119 >>> C["number"].value
|
jpayne@68
|
120 '7'
|
jpayne@68
|
121 >>> C["string"].value
|
jpayne@68
|
122 'seven'
|
jpayne@68
|
123 >>> C.output()
|
jpayne@68
|
124 'Set-Cookie: number=7\r\nSet-Cookie: string=seven'
|
jpayne@68
|
125
|
jpayne@68
|
126 Finis.
|
jpayne@68
|
127 """
|
jpayne@68
|
128
|
jpayne@68
|
129 #
|
jpayne@68
|
130 # Import our required modules
|
jpayne@68
|
131 #
|
jpayne@68
|
132 import re
|
jpayne@68
|
133 import string
|
jpayne@68
|
134
|
jpayne@68
|
135 __all__ = ["CookieError", "BaseCookie", "SimpleCookie"]
|
jpayne@68
|
136
|
jpayne@68
|
137 _nulljoin = ''.join
|
jpayne@68
|
138 _semispacejoin = '; '.join
|
jpayne@68
|
139 _spacejoin = ' '.join
|
jpayne@68
|
140
|
jpayne@68
|
141 #
|
jpayne@68
|
142 # Define an exception visible to External modules
|
jpayne@68
|
143 #
|
jpayne@68
|
144 class CookieError(Exception):
|
jpayne@68
|
145 pass
|
jpayne@68
|
146
|
jpayne@68
|
147
|
jpayne@68
|
148 # These quoting routines conform to the RFC2109 specification, which in
|
jpayne@68
|
149 # turn references the character definitions from RFC2068. They provide
|
jpayne@68
|
150 # a two-way quoting algorithm. Any non-text character is translated
|
jpayne@68
|
151 # into a 4 character sequence: a forward-slash followed by the
|
jpayne@68
|
152 # three-digit octal equivalent of the character. Any '\' or '"' is
|
jpayne@68
|
153 # quoted with a preceding '\' slash.
|
jpayne@68
|
154 # Because of the way browsers really handle cookies (as opposed to what
|
jpayne@68
|
155 # the RFC says) we also encode "," and ";".
|
jpayne@68
|
156 #
|
jpayne@68
|
157 # These are taken from RFC2068 and RFC2109.
|
jpayne@68
|
158 # _LegalChars is the list of chars which don't require "'s
|
jpayne@68
|
159 # _Translator hash-table for fast quoting
|
jpayne@68
|
160 #
|
jpayne@68
|
161 _LegalChars = string.ascii_letters + string.digits + "!#$%&'*+-.^_`|~:"
|
jpayne@68
|
162 _UnescapedChars = _LegalChars + ' ()/<=>?@[]{}'
|
jpayne@68
|
163
|
jpayne@68
|
164 _Translator = {n: '\\%03o' % n
|
jpayne@68
|
165 for n in set(range(256)) - set(map(ord, _UnescapedChars))}
|
jpayne@68
|
166 _Translator.update({
|
jpayne@68
|
167 ord('"'): '\\"',
|
jpayne@68
|
168 ord('\\'): '\\\\',
|
jpayne@68
|
169 })
|
jpayne@68
|
170
|
jpayne@68
|
171 _is_legal_key = re.compile('[%s]+' % re.escape(_LegalChars)).fullmatch
|
jpayne@68
|
172
|
jpayne@68
|
173 def _quote(str):
|
jpayne@68
|
174 r"""Quote a string for use in a cookie header.
|
jpayne@68
|
175
|
jpayne@68
|
176 If the string does not need to be double-quoted, then just return the
|
jpayne@68
|
177 string. Otherwise, surround the string in doublequotes and quote
|
jpayne@68
|
178 (with a \) special characters.
|
jpayne@68
|
179 """
|
jpayne@68
|
180 if str is None or _is_legal_key(str):
|
jpayne@68
|
181 return str
|
jpayne@68
|
182 else:
|
jpayne@68
|
183 return '"' + str.translate(_Translator) + '"'
|
jpayne@68
|
184
|
jpayne@68
|
185
|
jpayne@68
|
186 _OctalPatt = re.compile(r"\\[0-3][0-7][0-7]")
|
jpayne@68
|
187 _QuotePatt = re.compile(r"[\\].")
|
jpayne@68
|
188
|
jpayne@68
|
189 def _unquote(str):
|
jpayne@68
|
190 # If there aren't any doublequotes,
|
jpayne@68
|
191 # then there can't be any special characters. See RFC 2109.
|
jpayne@68
|
192 if str is None or len(str) < 2:
|
jpayne@68
|
193 return str
|
jpayne@68
|
194 if str[0] != '"' or str[-1] != '"':
|
jpayne@68
|
195 return str
|
jpayne@68
|
196
|
jpayne@68
|
197 # We have to assume that we must decode this string.
|
jpayne@68
|
198 # Down to work.
|
jpayne@68
|
199
|
jpayne@68
|
200 # Remove the "s
|
jpayne@68
|
201 str = str[1:-1]
|
jpayne@68
|
202
|
jpayne@68
|
203 # Check for special sequences. Examples:
|
jpayne@68
|
204 # \012 --> \n
|
jpayne@68
|
205 # \" --> "
|
jpayne@68
|
206 #
|
jpayne@68
|
207 i = 0
|
jpayne@68
|
208 n = len(str)
|
jpayne@68
|
209 res = []
|
jpayne@68
|
210 while 0 <= i < n:
|
jpayne@68
|
211 o_match = _OctalPatt.search(str, i)
|
jpayne@68
|
212 q_match = _QuotePatt.search(str, i)
|
jpayne@68
|
213 if not o_match and not q_match: # Neither matched
|
jpayne@68
|
214 res.append(str[i:])
|
jpayne@68
|
215 break
|
jpayne@68
|
216 # else:
|
jpayne@68
|
217 j = k = -1
|
jpayne@68
|
218 if o_match:
|
jpayne@68
|
219 j = o_match.start(0)
|
jpayne@68
|
220 if q_match:
|
jpayne@68
|
221 k = q_match.start(0)
|
jpayne@68
|
222 if q_match and (not o_match or k < j): # QuotePatt matched
|
jpayne@68
|
223 res.append(str[i:k])
|
jpayne@68
|
224 res.append(str[k+1])
|
jpayne@68
|
225 i = k + 2
|
jpayne@68
|
226 else: # OctalPatt matched
|
jpayne@68
|
227 res.append(str[i:j])
|
jpayne@68
|
228 res.append(chr(int(str[j+1:j+4], 8)))
|
jpayne@68
|
229 i = j + 4
|
jpayne@68
|
230 return _nulljoin(res)
|
jpayne@68
|
231
|
jpayne@68
|
232 # The _getdate() routine is used to set the expiration time in the cookie's HTTP
|
jpayne@68
|
233 # header. By default, _getdate() returns the current time in the appropriate
|
jpayne@68
|
234 # "expires" format for a Set-Cookie header. The one optional argument is an
|
jpayne@68
|
235 # offset from now, in seconds. For example, an offset of -3600 means "one hour
|
jpayne@68
|
236 # ago". The offset may be a floating point number.
|
jpayne@68
|
237 #
|
jpayne@68
|
238
|
jpayne@68
|
239 _weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
|
jpayne@68
|
240
|
jpayne@68
|
241 _monthname = [None,
|
jpayne@68
|
242 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
|
jpayne@68
|
243 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
|
jpayne@68
|
244
|
jpayne@68
|
245 def _getdate(future=0, weekdayname=_weekdayname, monthname=_monthname):
|
jpayne@68
|
246 from time import gmtime, time
|
jpayne@68
|
247 now = time()
|
jpayne@68
|
248 year, month, day, hh, mm, ss, wd, y, z = gmtime(now + future)
|
jpayne@68
|
249 return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % \
|
jpayne@68
|
250 (weekdayname[wd], day, monthname[month], year, hh, mm, ss)
|
jpayne@68
|
251
|
jpayne@68
|
252
|
jpayne@68
|
253 class Morsel(dict):
|
jpayne@68
|
254 """A class to hold ONE (key, value) pair.
|
jpayne@68
|
255
|
jpayne@68
|
256 In a cookie, each such pair may have several attributes, so this class is
|
jpayne@68
|
257 used to keep the attributes associated with the appropriate key,value pair.
|
jpayne@68
|
258 This class also includes a coded_value attribute, which is used to hold
|
jpayne@68
|
259 the network representation of the value.
|
jpayne@68
|
260 """
|
jpayne@68
|
261 # RFC 2109 lists these attributes as reserved:
|
jpayne@68
|
262 # path comment domain
|
jpayne@68
|
263 # max-age secure version
|
jpayne@68
|
264 #
|
jpayne@68
|
265 # For historical reasons, these attributes are also reserved:
|
jpayne@68
|
266 # expires
|
jpayne@68
|
267 #
|
jpayne@68
|
268 # This is an extension from Microsoft:
|
jpayne@68
|
269 # httponly
|
jpayne@68
|
270 #
|
jpayne@68
|
271 # This dictionary provides a mapping from the lowercase
|
jpayne@68
|
272 # variant on the left to the appropriate traditional
|
jpayne@68
|
273 # formatting on the right.
|
jpayne@68
|
274 _reserved = {
|
jpayne@68
|
275 "expires" : "expires",
|
jpayne@68
|
276 "path" : "Path",
|
jpayne@68
|
277 "comment" : "Comment",
|
jpayne@68
|
278 "domain" : "Domain",
|
jpayne@68
|
279 "max-age" : "Max-Age",
|
jpayne@68
|
280 "secure" : "Secure",
|
jpayne@68
|
281 "httponly" : "HttpOnly",
|
jpayne@68
|
282 "version" : "Version",
|
jpayne@68
|
283 "samesite" : "SameSite",
|
jpayne@68
|
284 }
|
jpayne@68
|
285
|
jpayne@68
|
286 _flags = {'secure', 'httponly'}
|
jpayne@68
|
287
|
jpayne@68
|
288 def __init__(self):
|
jpayne@68
|
289 # Set defaults
|
jpayne@68
|
290 self._key = self._value = self._coded_value = None
|
jpayne@68
|
291
|
jpayne@68
|
292 # Set default attributes
|
jpayne@68
|
293 for key in self._reserved:
|
jpayne@68
|
294 dict.__setitem__(self, key, "")
|
jpayne@68
|
295
|
jpayne@68
|
296 @property
|
jpayne@68
|
297 def key(self):
|
jpayne@68
|
298 return self._key
|
jpayne@68
|
299
|
jpayne@68
|
300 @property
|
jpayne@68
|
301 def value(self):
|
jpayne@68
|
302 return self._value
|
jpayne@68
|
303
|
jpayne@68
|
304 @property
|
jpayne@68
|
305 def coded_value(self):
|
jpayne@68
|
306 return self._coded_value
|
jpayne@68
|
307
|
jpayne@68
|
308 def __setitem__(self, K, V):
|
jpayne@68
|
309 K = K.lower()
|
jpayne@68
|
310 if not K in self._reserved:
|
jpayne@68
|
311 raise CookieError("Invalid attribute %r" % (K,))
|
jpayne@68
|
312 dict.__setitem__(self, K, V)
|
jpayne@68
|
313
|
jpayne@68
|
314 def setdefault(self, key, val=None):
|
jpayne@68
|
315 key = key.lower()
|
jpayne@68
|
316 if key not in self._reserved:
|
jpayne@68
|
317 raise CookieError("Invalid attribute %r" % (key,))
|
jpayne@68
|
318 return dict.setdefault(self, key, val)
|
jpayne@68
|
319
|
jpayne@68
|
320 def __eq__(self, morsel):
|
jpayne@68
|
321 if not isinstance(morsel, Morsel):
|
jpayne@68
|
322 return NotImplemented
|
jpayne@68
|
323 return (dict.__eq__(self, morsel) and
|
jpayne@68
|
324 self._value == morsel._value and
|
jpayne@68
|
325 self._key == morsel._key and
|
jpayne@68
|
326 self._coded_value == morsel._coded_value)
|
jpayne@68
|
327
|
jpayne@68
|
328 __ne__ = object.__ne__
|
jpayne@68
|
329
|
jpayne@68
|
330 def copy(self):
|
jpayne@68
|
331 morsel = Morsel()
|
jpayne@68
|
332 dict.update(morsel, self)
|
jpayne@68
|
333 morsel.__dict__.update(self.__dict__)
|
jpayne@68
|
334 return morsel
|
jpayne@68
|
335
|
jpayne@68
|
336 def update(self, values):
|
jpayne@68
|
337 data = {}
|
jpayne@68
|
338 for key, val in dict(values).items():
|
jpayne@68
|
339 key = key.lower()
|
jpayne@68
|
340 if key not in self._reserved:
|
jpayne@68
|
341 raise CookieError("Invalid attribute %r" % (key,))
|
jpayne@68
|
342 data[key] = val
|
jpayne@68
|
343 dict.update(self, data)
|
jpayne@68
|
344
|
jpayne@68
|
345 def isReservedKey(self, K):
|
jpayne@68
|
346 return K.lower() in self._reserved
|
jpayne@68
|
347
|
jpayne@68
|
348 def set(self, key, val, coded_val):
|
jpayne@68
|
349 if key.lower() in self._reserved:
|
jpayne@68
|
350 raise CookieError('Attempt to set a reserved key %r' % (key,))
|
jpayne@68
|
351 if not _is_legal_key(key):
|
jpayne@68
|
352 raise CookieError('Illegal key %r' % (key,))
|
jpayne@68
|
353
|
jpayne@68
|
354 # It's a good key, so save it.
|
jpayne@68
|
355 self._key = key
|
jpayne@68
|
356 self._value = val
|
jpayne@68
|
357 self._coded_value = coded_val
|
jpayne@68
|
358
|
jpayne@68
|
359 def __getstate__(self):
|
jpayne@68
|
360 return {
|
jpayne@68
|
361 'key': self._key,
|
jpayne@68
|
362 'value': self._value,
|
jpayne@68
|
363 'coded_value': self._coded_value,
|
jpayne@68
|
364 }
|
jpayne@68
|
365
|
jpayne@68
|
366 def __setstate__(self, state):
|
jpayne@68
|
367 self._key = state['key']
|
jpayne@68
|
368 self._value = state['value']
|
jpayne@68
|
369 self._coded_value = state['coded_value']
|
jpayne@68
|
370
|
jpayne@68
|
371 def output(self, attrs=None, header="Set-Cookie:"):
|
jpayne@68
|
372 return "%s %s" % (header, self.OutputString(attrs))
|
jpayne@68
|
373
|
jpayne@68
|
374 __str__ = output
|
jpayne@68
|
375
|
jpayne@68
|
376 def __repr__(self):
|
jpayne@68
|
377 return '<%s: %s>' % (self.__class__.__name__, self.OutputString())
|
jpayne@68
|
378
|
jpayne@68
|
379 def js_output(self, attrs=None):
|
jpayne@68
|
380 # Print javascript
|
jpayne@68
|
381 return """
|
jpayne@68
|
382 <script type="text/javascript">
|
jpayne@68
|
383 <!-- begin hiding
|
jpayne@68
|
384 document.cookie = \"%s\";
|
jpayne@68
|
385 // end hiding -->
|
jpayne@68
|
386 </script>
|
jpayne@68
|
387 """ % (self.OutputString(attrs).replace('"', r'\"'))
|
jpayne@68
|
388
|
jpayne@68
|
389 def OutputString(self, attrs=None):
|
jpayne@68
|
390 # Build up our result
|
jpayne@68
|
391 #
|
jpayne@68
|
392 result = []
|
jpayne@68
|
393 append = result.append
|
jpayne@68
|
394
|
jpayne@68
|
395 # First, the key=value pair
|
jpayne@68
|
396 append("%s=%s" % (self.key, self.coded_value))
|
jpayne@68
|
397
|
jpayne@68
|
398 # Now add any defined attributes
|
jpayne@68
|
399 if attrs is None:
|
jpayne@68
|
400 attrs = self._reserved
|
jpayne@68
|
401 items = sorted(self.items())
|
jpayne@68
|
402 for key, value in items:
|
jpayne@68
|
403 if value == "":
|
jpayne@68
|
404 continue
|
jpayne@68
|
405 if key not in attrs:
|
jpayne@68
|
406 continue
|
jpayne@68
|
407 if key == "expires" and isinstance(value, int):
|
jpayne@68
|
408 append("%s=%s" % (self._reserved[key], _getdate(value)))
|
jpayne@68
|
409 elif key == "max-age" and isinstance(value, int):
|
jpayne@68
|
410 append("%s=%d" % (self._reserved[key], value))
|
jpayne@68
|
411 elif key == "comment" and isinstance(value, str):
|
jpayne@68
|
412 append("%s=%s" % (self._reserved[key], _quote(value)))
|
jpayne@68
|
413 elif key in self._flags:
|
jpayne@68
|
414 if value:
|
jpayne@68
|
415 append(str(self._reserved[key]))
|
jpayne@68
|
416 else:
|
jpayne@68
|
417 append("%s=%s" % (self._reserved[key], value))
|
jpayne@68
|
418
|
jpayne@68
|
419 # Return the result
|
jpayne@68
|
420 return _semispacejoin(result)
|
jpayne@68
|
421
|
jpayne@68
|
422
|
jpayne@68
|
423 #
|
jpayne@68
|
424 # Pattern for finding cookie
|
jpayne@68
|
425 #
|
jpayne@68
|
426 # This used to be strict parsing based on the RFC2109 and RFC2068
|
jpayne@68
|
427 # specifications. I have since discovered that MSIE 3.0x doesn't
|
jpayne@68
|
428 # follow the character rules outlined in those specs. As a
|
jpayne@68
|
429 # result, the parsing rules here are less strict.
|
jpayne@68
|
430 #
|
jpayne@68
|
431
|
jpayne@68
|
432 _LegalKeyChars = r"\w\d!#%&'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\="
|
jpayne@68
|
433 _LegalValueChars = _LegalKeyChars + r'\[\]'
|
jpayne@68
|
434 _CookiePattern = re.compile(r"""
|
jpayne@68
|
435 \s* # Optional whitespace at start of cookie
|
jpayne@68
|
436 (?P<key> # Start of group 'key'
|
jpayne@68
|
437 [""" + _LegalKeyChars + r"""]+? # Any word of at least one letter
|
jpayne@68
|
438 ) # End of group 'key'
|
jpayne@68
|
439 ( # Optional group: there may not be a value.
|
jpayne@68
|
440 \s*=\s* # Equal Sign
|
jpayne@68
|
441 (?P<val> # Start of group 'val'
|
jpayne@68
|
442 "(?:[^\\"]|\\.)*" # Any doublequoted string
|
jpayne@68
|
443 | # or
|
jpayne@68
|
444 \w{3},\s[\w\d\s-]{9,11}\s[\d:]{8}\sGMT # Special case for "expires" attr
|
jpayne@68
|
445 | # or
|
jpayne@68
|
446 [""" + _LegalValueChars + r"""]* # Any word or empty string
|
jpayne@68
|
447 ) # End of group 'val'
|
jpayne@68
|
448 )? # End of optional value group
|
jpayne@68
|
449 \s* # Any number of spaces.
|
jpayne@68
|
450 (\s+|;|$) # Ending either at space, semicolon, or EOS.
|
jpayne@68
|
451 """, re.ASCII | re.VERBOSE) # re.ASCII may be removed if safe.
|
jpayne@68
|
452
|
jpayne@68
|
453
|
jpayne@68
|
454 # At long last, here is the cookie class. Using this class is almost just like
|
jpayne@68
|
455 # using a dictionary. See this module's docstring for example usage.
|
jpayne@68
|
456 #
|
jpayne@68
|
457 class BaseCookie(dict):
|
jpayne@68
|
458 """A container class for a set of Morsels."""
|
jpayne@68
|
459
|
jpayne@68
|
460 def value_decode(self, val):
|
jpayne@68
|
461 """real_value, coded_value = value_decode(STRING)
|
jpayne@68
|
462 Called prior to setting a cookie's value from the network
|
jpayne@68
|
463 representation. The VALUE is the value read from HTTP
|
jpayne@68
|
464 header.
|
jpayne@68
|
465 Override this function to modify the behavior of cookies.
|
jpayne@68
|
466 """
|
jpayne@68
|
467 return val, val
|
jpayne@68
|
468
|
jpayne@68
|
469 def value_encode(self, val):
|
jpayne@68
|
470 """real_value, coded_value = value_encode(VALUE)
|
jpayne@68
|
471 Called prior to setting a cookie's value from the dictionary
|
jpayne@68
|
472 representation. The VALUE is the value being assigned.
|
jpayne@68
|
473 Override this function to modify the behavior of cookies.
|
jpayne@68
|
474 """
|
jpayne@68
|
475 strval = str(val)
|
jpayne@68
|
476 return strval, strval
|
jpayne@68
|
477
|
jpayne@68
|
478 def __init__(self, input=None):
|
jpayne@68
|
479 if input:
|
jpayne@68
|
480 self.load(input)
|
jpayne@68
|
481
|
jpayne@68
|
482 def __set(self, key, real_value, coded_value):
|
jpayne@68
|
483 """Private method for setting a cookie's value"""
|
jpayne@68
|
484 M = self.get(key, Morsel())
|
jpayne@68
|
485 M.set(key, real_value, coded_value)
|
jpayne@68
|
486 dict.__setitem__(self, key, M)
|
jpayne@68
|
487
|
jpayne@68
|
488 def __setitem__(self, key, value):
|
jpayne@68
|
489 """Dictionary style assignment."""
|
jpayne@68
|
490 if isinstance(value, Morsel):
|
jpayne@68
|
491 # allow assignment of constructed Morsels (e.g. for pickling)
|
jpayne@68
|
492 dict.__setitem__(self, key, value)
|
jpayne@68
|
493 else:
|
jpayne@68
|
494 rval, cval = self.value_encode(value)
|
jpayne@68
|
495 self.__set(key, rval, cval)
|
jpayne@68
|
496
|
jpayne@68
|
497 def output(self, attrs=None, header="Set-Cookie:", sep="\015\012"):
|
jpayne@68
|
498 """Return a string suitable for HTTP."""
|
jpayne@68
|
499 result = []
|
jpayne@68
|
500 items = sorted(self.items())
|
jpayne@68
|
501 for key, value in items:
|
jpayne@68
|
502 result.append(value.output(attrs, header))
|
jpayne@68
|
503 return sep.join(result)
|
jpayne@68
|
504
|
jpayne@68
|
505 __str__ = output
|
jpayne@68
|
506
|
jpayne@68
|
507 def __repr__(self):
|
jpayne@68
|
508 l = []
|
jpayne@68
|
509 items = sorted(self.items())
|
jpayne@68
|
510 for key, value in items:
|
jpayne@68
|
511 l.append('%s=%s' % (key, repr(value.value)))
|
jpayne@68
|
512 return '<%s: %s>' % (self.__class__.__name__, _spacejoin(l))
|
jpayne@68
|
513
|
jpayne@68
|
514 def js_output(self, attrs=None):
|
jpayne@68
|
515 """Return a string suitable for JavaScript."""
|
jpayne@68
|
516 result = []
|
jpayne@68
|
517 items = sorted(self.items())
|
jpayne@68
|
518 for key, value in items:
|
jpayne@68
|
519 result.append(value.js_output(attrs))
|
jpayne@68
|
520 return _nulljoin(result)
|
jpayne@68
|
521
|
jpayne@68
|
522 def load(self, rawdata):
|
jpayne@68
|
523 """Load cookies from a string (presumably HTTP_COOKIE) or
|
jpayne@68
|
524 from a dictionary. Loading cookies from a dictionary 'd'
|
jpayne@68
|
525 is equivalent to calling:
|
jpayne@68
|
526 map(Cookie.__setitem__, d.keys(), d.values())
|
jpayne@68
|
527 """
|
jpayne@68
|
528 if isinstance(rawdata, str):
|
jpayne@68
|
529 self.__parse_string(rawdata)
|
jpayne@68
|
530 else:
|
jpayne@68
|
531 # self.update() wouldn't call our custom __setitem__
|
jpayne@68
|
532 for key, value in rawdata.items():
|
jpayne@68
|
533 self[key] = value
|
jpayne@68
|
534 return
|
jpayne@68
|
535
|
jpayne@68
|
536 def __parse_string(self, str, patt=_CookiePattern):
|
jpayne@68
|
537 i = 0 # Our starting point
|
jpayne@68
|
538 n = len(str) # Length of string
|
jpayne@68
|
539 parsed_items = [] # Parsed (type, key, value) triples
|
jpayne@68
|
540 morsel_seen = False # A key=value pair was previously encountered
|
jpayne@68
|
541
|
jpayne@68
|
542 TYPE_ATTRIBUTE = 1
|
jpayne@68
|
543 TYPE_KEYVALUE = 2
|
jpayne@68
|
544
|
jpayne@68
|
545 # We first parse the whole cookie string and reject it if it's
|
jpayne@68
|
546 # syntactically invalid (this helps avoid some classes of injection
|
jpayne@68
|
547 # attacks).
|
jpayne@68
|
548 while 0 <= i < n:
|
jpayne@68
|
549 # Start looking for a cookie
|
jpayne@68
|
550 match = patt.match(str, i)
|
jpayne@68
|
551 if not match:
|
jpayne@68
|
552 # No more cookies
|
jpayne@68
|
553 break
|
jpayne@68
|
554
|
jpayne@68
|
555 key, value = match.group("key"), match.group("val")
|
jpayne@68
|
556 i = match.end(0)
|
jpayne@68
|
557
|
jpayne@68
|
558 if key[0] == "$":
|
jpayne@68
|
559 if not morsel_seen:
|
jpayne@68
|
560 # We ignore attributes which pertain to the cookie
|
jpayne@68
|
561 # mechanism as a whole, such as "$Version".
|
jpayne@68
|
562 # See RFC 2965. (Does anyone care?)
|
jpayne@68
|
563 continue
|
jpayne@68
|
564 parsed_items.append((TYPE_ATTRIBUTE, key[1:], value))
|
jpayne@68
|
565 elif key.lower() in Morsel._reserved:
|
jpayne@68
|
566 if not morsel_seen:
|
jpayne@68
|
567 # Invalid cookie string
|
jpayne@68
|
568 return
|
jpayne@68
|
569 if value is None:
|
jpayne@68
|
570 if key.lower() in Morsel._flags:
|
jpayne@68
|
571 parsed_items.append((TYPE_ATTRIBUTE, key, True))
|
jpayne@68
|
572 else:
|
jpayne@68
|
573 # Invalid cookie string
|
jpayne@68
|
574 return
|
jpayne@68
|
575 else:
|
jpayne@68
|
576 parsed_items.append((TYPE_ATTRIBUTE, key, _unquote(value)))
|
jpayne@68
|
577 elif value is not None:
|
jpayne@68
|
578 parsed_items.append((TYPE_KEYVALUE, key, self.value_decode(value)))
|
jpayne@68
|
579 morsel_seen = True
|
jpayne@68
|
580 else:
|
jpayne@68
|
581 # Invalid cookie string
|
jpayne@68
|
582 return
|
jpayne@68
|
583
|
jpayne@68
|
584 # The cookie string is valid, apply it.
|
jpayne@68
|
585 M = None # current morsel
|
jpayne@68
|
586 for tp, key, value in parsed_items:
|
jpayne@68
|
587 if tp == TYPE_ATTRIBUTE:
|
jpayne@68
|
588 assert M is not None
|
jpayne@68
|
589 M[key] = value
|
jpayne@68
|
590 else:
|
jpayne@68
|
591 assert tp == TYPE_KEYVALUE
|
jpayne@68
|
592 rval, cval = value
|
jpayne@68
|
593 self.__set(key, rval, cval)
|
jpayne@68
|
594 M = self[key]
|
jpayne@68
|
595
|
jpayne@68
|
596
|
jpayne@68
|
597 class SimpleCookie(BaseCookie):
|
jpayne@68
|
598 """
|
jpayne@68
|
599 SimpleCookie supports strings as cookie values. When setting
|
jpayne@68
|
600 the value using the dictionary assignment notation, SimpleCookie
|
jpayne@68
|
601 calls the builtin str() to convert the value to a string. Values
|
jpayne@68
|
602 received from HTTP are kept as strings.
|
jpayne@68
|
603 """
|
jpayne@68
|
604 def value_decode(self, val):
|
jpayne@68
|
605 return _unquote(val), val
|
jpayne@68
|
606
|
jpayne@68
|
607 def value_encode(self, val):
|
jpayne@68
|
608 strval = str(val)
|
jpayne@68
|
609 return strval, _quote(strval)
|