r"""Parse a HTTP_COOKIE header and return dict of cookie names and decoded values. >>> sorted(parse_cookies('').items()) [] >>> sorted(parse_cookies('a=1').items()) [('a', '1')] >>> sorted(parse_cookies('a=1%202').items()) [('a', '1 2')] >>> sorted(parse_cookies('a=Z%C3%
(http_cookie)
| 509 | |
| 510 | |
| 511 | def parse_cookies(http_cookie): |
| 512 | r"""Parse a HTTP_COOKIE header and return dict of cookie names and decoded values. |
| 513 | |
| 514 | >>> sorted(parse_cookies('').items()) |
| 515 | [] |
| 516 | >>> sorted(parse_cookies('a=1').items()) |
| 517 | [('a', '1')] |
| 518 | >>> sorted(parse_cookies('a=1%202').items()) |
| 519 | [('a', '1 2')] |
| 520 | >>> sorted(parse_cookies('a=Z%C3%A9Z').items()) |
| 521 | [('a', 'Z\xc3\xa9Z')] |
| 522 | >>> sorted(parse_cookies('a=1; b=2; c=3').items()) |
| 523 | [('a', '1'), ('b', '2'), ('c', '3')] |
| 524 | |
| 525 | # TODO: cclauss re-enable this test |
| 526 | # >>> sorted(parse_cookies('a=1; b=w("x")|y=z; c=3').items()) |
| 527 | # [('a', '1'), ('b', 'w('), ('c', '3')] |
| 528 | |
| 529 | >>> sorted(parse_cookies('a=1; b=w(%22x%22)|y=z; c=3').items()) |
| 530 | [('a', '1'), ('b', 'w("x")|y=z'), ('c', '3')] |
| 531 | |
| 532 | >>> sorted(parse_cookies('keebler=E=mc2').items()) |
| 533 | [('keebler', 'E=mc2')] |
| 534 | >>> sorted(parse_cookies(r'keebler="E=mc2; L=\"Loves\"; fudge=\012;"').items()) |
| 535 | [('keebler', 'E=mc2; L="Loves"; fudge=\n;')] |
| 536 | """ |
| 537 | # print "parse_cookies" |
| 538 | if '"' in http_cookie: |
| 539 | # HTTP_COOKIE has quotes in it, use slow but correct cookie parsing |
| 540 | cookie = SimpleCookie() |
| 541 | try: |
| 542 | cookie.load(http_cookie) |
| 543 | except CookieError: |
| 544 | # If HTTP_COOKIE header is malformed, try at least to load the cookies we can by |
| 545 | # first splitting on ';' and loading each attr=value pair separately |
| 546 | cookie = SimpleCookie() |
| 547 | for attr_value in http_cookie.split(";"): |
| 548 | try: |
| 549 | cookie.load(attr_value) |
| 550 | except CookieError: |
| 551 | pass |
| 552 | cookies = {k: unquote(v.value) for k, v in cookie.items()} |
| 553 | else: |
| 554 | # HTTP_COOKIE doesn't have quotes, use fast cookie parsing |
| 555 | cookies = {} |
| 556 | for key_value in http_cookie.split(";"): |
| 557 | key_value = key_value.split("=", 1) |
| 558 | if len(key_value) == 2: |
| 559 | key, value = key_value |
| 560 | cookies[key.strip()] = unquote(value.strip()) |
| 561 | return cookies |
| 562 | |
| 563 | |
| 564 | def cookies(*requireds, **defaults): |