Patch the Cache-Control header by adding all keyword arguments to it. The transformation is as follows: * All keyword parameter names are turned to lowercase, and underscores are converted to hyphens. * If the value of a parameter is True (exactly True, not just a true
(response, **kwargs)
| 32 | |
| 33 | |
| 34 | def patch_cache_control(response, **kwargs): |
| 35 | """ |
| 36 | Patch the Cache-Control header by adding all keyword arguments to it. |
| 37 | The transformation is as follows: |
| 38 | |
| 39 | * All keyword parameter names are turned to lowercase, and underscores |
| 40 | are converted to hyphens. |
| 41 | * If the value of a parameter is True (exactly True, not just a |
| 42 | true value), only the parameter name is added to the header. |
| 43 | * All other parameters are added with their value, after applying |
| 44 | str() to it. |
| 45 | """ |
| 46 | |
| 47 | def dictitem(s): |
| 48 | t = s.split("=", 1) |
| 49 | if len(t) > 1: |
| 50 | return (t[0].lower(), t[1]) |
| 51 | else: |
| 52 | return (t[0].lower(), True) |
| 53 | |
| 54 | def dictvalue(*t): |
| 55 | if t[1] is True: |
| 56 | return t[0] |
| 57 | else: |
| 58 | return "%s=%s" % (t[0], t[1]) |
| 59 | |
| 60 | cc = defaultdict(set) |
| 61 | if response.get("Cache-Control"): |
| 62 | for field in cc_delim_re.split(response.headers["Cache-Control"]): |
| 63 | directive, value = dictitem(field) |
| 64 | if directive == "no-cache": |
| 65 | # no-cache supports multiple field names. |
| 66 | cc[directive].add(value) |
| 67 | else: |
| 68 | cc[directive] = value |
| 69 | |
| 70 | # If there's already a max-age header but we're being asked to set a new |
| 71 | # max-age, use the minimum of the two ages. In practice this happens when |
| 72 | # a decorator and a piece of middleware both operate on a given view. |
| 73 | if "max-age" in cc and "max_age" in kwargs: |
| 74 | kwargs["max_age"] = min(int(cc["max-age"]), kwargs["max_age"]) |
| 75 | |
| 76 | # Allow overriding private caching and vice versa |
| 77 | if "private" in cc and "public" in kwargs: |
| 78 | del cc["private"] |
| 79 | elif "public" in cc and "private" in kwargs: |
| 80 | del cc["public"] |
| 81 | |
| 82 | for k, v in kwargs.items(): |
| 83 | directive = k.replace("_", "-") |
| 84 | if directive == "no-cache": |
| 85 | # no-cache supports multiple field names. |
| 86 | cc[directive].add(v) |
| 87 | else: |
| 88 | cc[directive] = v |
| 89 | |
| 90 | directives = [] |
| 91 | for directive, values in cc.items(): |