Variable._resolve_lookup monkeypatch

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
    from django.template import Variable

    def patch_resolver():
        Variable._resolve_lookup = our_resolver

    def our_resolver(self, context):
        current = context
        how_resolved_steps = []
        for bit in self.lookups:
            how_resolved, current = resolve_bit(current, bit)
            how_resolved_steps.append((how_resolved, current))
        debug(self.lookups, how_resolved_steps)
        return current
        
    def resolve_bit(current, bit):
        # Strict, does not allow list lookups, for example
        try:
            return 'dictionary', current[bit]
        except (TypeError, AttributeError, KeyError):
            pass

        current = getattr(current, bit)
        if not callable(current):
            return 'attribute', current
        if getattr(current, 'alters_data', False):
            raise Exception('trying to alter data')
        return 'called attribute', current()

    def debug(lookups, how_resolved_steps):
        name = 'context'
        for i, (how_resolved, value) in enumerate(how_resolved_steps):
            bit = lookups[i]
            if how_resolved == 'dictionary':
                name += "['%s']" % bit
            elif how_resolved == 'attribute':
                name += '.%s' % bit
            else:
                name += '.%s()' % bit
        print '%.40s' % name, value

More like this

  1. safe(r) monkeypatching scheme for django testing by showell 4 years, 4 months ago
  2. Forcing unit test runner to abort after failed test by simonbun 6 years, 11 months ago
  3. FieldsetForm by Ciantic 7 years ago
  4. Accessing URL variable from within a Form by blacktav 7 months, 2 weeks ago
  5. Repeat blocks with new context / simple Jinja-like macro system by miracle2k 6 years, 8 months ago

Comments

(Forgotten your password?)