| 11 | |
| 12 | |
| 13 | class SimpleApp: |
| 14 | def __init__(self): |
| 15 | self.etag_count = 0 |
| 16 | self.update_etag_string() |
| 17 | |
| 18 | def dispatch(self, env): |
| 19 | path = env["PATH_INFO"][1:].split("/") |
| 20 | segment = path.pop(0) |
| 21 | if segment and hasattr(self, segment): |
| 22 | return getattr(self, segment) |
| 23 | |
| 24 | return None |
| 25 | |
| 26 | def optional_cacheable_request(self, env, start_response): |
| 27 | """A request with no hints as to whether it should be |
| 28 | cached. Yet, we might still choose to cache it via a |
| 29 | heuristic.""" |
| 30 | |
| 31 | headers = [ |
| 32 | ("server", "nginx/1.2.6 (Ubuntu)"), |
| 33 | ("last-modified", "Mon, 21 Jul 2014 17:45:39 GMT"), |
| 34 | ("content-type", "text/html"), |
| 35 | ] |
| 36 | |
| 37 | start_response("200 OK", headers) |
| 38 | return [pformat(env).encode("utf8")] |
| 39 | |
| 40 | def vary_accept(self, env, start_response): |
| 41 | response = pformat(env).encode("utf8") |
| 42 | |
| 43 | headers = [ |
| 44 | ("Cache-Control", "max-age=5000"), |
| 45 | ("Content-Type", "text/plain"), |
| 46 | ("Vary", "Accept-Encoding, Accept"), |
| 47 | ] |
| 48 | start_response("200 OK", headers) |
| 49 | return [response] |
| 50 | |
| 51 | def update_etag_string(self): |
| 52 | self.etag_count += 1 |
| 53 | self.etag_string = f'"ETAG-{self.etag_count}"' |
| 54 | |
| 55 | def update_etag(self, env, start_response): |
| 56 | self.update_etag_string() |
| 57 | headers = [("Cache-Control", "max-age=5000"), ("Content-Type", "text/plain")] |
| 58 | start_response("200 OK", headers) |
| 59 | return [pformat(env).encode("utf8")] |
| 60 | |
| 61 | def conditional_get(self, env, start_response): |
| 62 | return start_response("304 Not Modified", []) |
| 63 | |
| 64 | def etag(self, env, start_response): |
| 65 | headers = [("Etag", self.etag_string)] |
| 66 | if env.get("HTTP_IF_NONE_MATCH") == self.etag_string: |
| 67 | start_response("304 Not Modified", headers) |
| 68 | return [] |
| 69 | else: |
| 70 | start_response("200 OK", headers) |