Completed
Pull Request — master (#22)
by
unknown
01:23
created

conditional_http_tween_factory()   D

Complexity

Conditions 8

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 8
c 1
b 0
f 1
dl 0
loc 29
rs 4

1 Method

Rating   Name   Duplication   Size   Complexity  
C conditional_http_tween() 0 23 7
1
# -*- coding: utf-8 -*-
2
from collections import Sequence
3
4
5
def conditional_http_tween_factory(handler, registry):
6
    '''
7
    Tween that adds ETag headers and tells Pyramid to enable
8
    conditional responses where appropriate.
9
    '''
10
    def conditional_http_tween(request):
11
        response = handler(request)
12
13
        # If the Last-Modified header has been set, we want to enable the
14
        # conditional response processing.
15
        if response.last_modified is not None:
16
            response.conditional_response = True
17
18
        # We want to only enable the conditional machinery if either we
19
        # were given an explicit ETag header by the view or we have a
20
        # buffered response and can generate the ETag header ourself.
21
        if response.etag is not None:
22
            response.conditional_response = True
23
        # We can only reasonably implement automatic ETags on 200 responses
24
        # to GET or HEAD requests. The subtles of doing it in other cases
25
        # are too hard to get right.
26
        elif request.method in {"GET", "HEAD"} and response.status_code == 200:
27
            if (isinstance(response.app_iter, Sequence) and
28
                    len(response.app_iter) == 1):
29
                response.conditional_response = True
30
                response.md5_etag()
31
32
        return response
33
    return conditional_http_tween
34