Completed
Push — master ( 628ad1...d7965f )
by Bart
01:21
created

conditional_http_tween()   C

Complexity

Conditions 7

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 7
c 1
b 0
f 1
dl 0
loc 21
rs 6.4705
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
    settings = registry.settings if hasattr(registry, 'settings') else {}
11
    not_cacheble_list = []
12
    if 'not.cachable.list' in settings:
13
        not_cacheble_list = settings.get('not.cachable.list').split()
14
15
    def conditional_http_tween(request):
16
        response = handler(request)
17
18
        if request.path not in not_cacheble_list:
19
20
            # If the Last-Modified header has been set, we want to enable the
21
            # conditional response processing.
22
            if response.last_modified is not None:
23
                response.conditional_response = True
24
25
            # We want to only enable the conditional machinery if either we
26
            # were given an explicit ETag header by the view or we have a
27
            # buffered response and can generate the ETag header ourself.
28
            if response.etag is not None:
29
                response.conditional_response = True
30
            elif (isinstance(response.app_iter, Sequence) and
31
                          len(response.app_iter) == 1) and response.body is not None:
32
                response.conditional_response = True
33
                response.md5_etag()
34
35
        return response
36
37
    return conditional_http_tween
38