• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

avanov / Rhetoric / 97

pending completion
97

push

travis-ci

Maxim Avanov
Cache request.json_body value after the first access to the attribute.

7 of 7 new or added lines in 1 file covered. (100.0%)

579 of 675 relevant lines covered (85.78%)

1.7 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.0
/rhetoric/middleware.py
1
import json
2✔
2
from django.http import HttpResponse, HttpRequest
2✔
3
from django.middleware.csrf import CsrfViewMiddleware
2✔
4

5
from .view import ViewCallback
2✔
6
from .compat import text_
2✔
7

8

9
def json_body_getter(request_instance):
2✔
10
    if hasattr(request_instance, '_json_body'):
2✔
11
        return request_instance._json_body
2✔
12
    json_body = json.loads(text_(request_instance.read(), request_instance.encoding or 'utf-8'))
2✔
13
    setattr(request_instance, '_json_body', json_body)
2✔
14
    return json_body
2✔
15

16

17
class CsrfProtectedViewDispatchMiddleware(CsrfViewMiddleware):
2✔
18

19
    def __init__(self):
2✔
20
        super(CsrfProtectedViewDispatchMiddleware, self).__init__()
2✔
21
        self.add_property(HttpRequest, 'json_body', json_body_getter)
2✔
22

23
    def process_request(self, request):
2✔
24
        # We assume here that CsrfViewMiddleware doesn't have the process_request method
25
        # which should be called via super().
26
        # -------------------------------------------------
27
        # set request.response object as in
28
        # http://docs.pylonsproject.org/projects/pyramid/en/latest/api/request.html#pyramid.request.Request.response
29
        setattr(request, 'response', HttpResponse())
2✔
30

31

32
    def process_view(self, request, callback, callback_args, callback_kwargs):
2✔
33
        if isinstance(callback, ViewCallback):
2✔
34
            view_settings = callback.find_view_settings(request, callback_args, callback_kwargs)
2✔
35
            # Check the actual view callable rather than ViewCallback wrapper with CsrfViewMiddleware
36
            return super(CsrfProtectedViewDispatchMiddleware, self).process_view(
2✔
37
                request, view_settings['view'], callback_args, callback_kwargs
38
            )
39

40
        # The callable is a regular django view
41
        return super(CsrfProtectedViewDispatchMiddleware, self).process_view(
×
42
            request, callback, callback_args, callback_kwargs
43
        )
44

45
    def add_property(self, cls, name, method):
2✔
46
        if not hasattr(cls, name):
2✔
47
            setattr(cls, name, property(method))
2✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc