Python django.utils.functional.SimpleLazyObject() Examples

The following are 30 code examples of django.utils.functional.SimpleLazyObject(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.utils.functional , or try the search function .
Example #1
Source File: context_processors.py    From bioforum with MIT License 7 votes vote down vote up
def csrf(request):
    """
    Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if
    it has not been provided by either a view decorator or the middleware
    """
    def _get_val():
        token = get_token(request)
        if token is None:
            # In order to be able to provide debugging info in the
            # case of misconfiguration, we use a sentinel value
            # instead of returning an empty dict.
            return 'NOTPROVIDED'
        else:
            return token

    return {'csrf_token': SimpleLazyObject(_get_val)} 
Example #2
Source File: context_processors.py    From python with Apache License 2.0 6 votes vote down vote up
def csrf(request):
    """
    Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if
    it has not been provided by either a view decorator or the middleware
    """
    def _get_val():
        token = get_token(request)
        if token is None:
            # In order to be able to provide debugging info in the
            # case of misconfiguration, we use a sentinel value
            # instead of returning an empty dict.
            return 'NOTPROVIDED'
        else:
            return force_text(token)

    return {'csrf_token': SimpleLazyObject(_get_val)} 
Example #3
Source File: test_debug.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_ignore_traceback_evaluation_exceptions(self):
        """
        Don't trip over exceptions generated by crafted objects when
        evaluating them while cleansing (#24455).
        """
        class BrokenEvaluation(Exception):
            pass

        def broken_setup():
            raise BrokenEvaluation

        request = self.rf.get('/test_view/')
        broken_lazy = SimpleLazyObject(broken_setup)
        try:
            bool(broken_lazy)
        except BrokenEvaluation:
            exc_type, exc_value, tb = sys.exc_info()

        self.assertIn(
            "BrokenEvaluation",
            ExceptionReporter(request, exc_type, exc_value, tb).get_traceback_html(),
            "Evaluation exception reason not mentioned in traceback"
        ) 
Example #4
Source File: middleware.py    From wagtail-2fa with MIT License 6 votes vote down vote up
def process_request(self, request):
        if request.user:
            request.user = SimpleLazyObject(partial(self._verify_user, request, request.user))
        user = request.user
        if self._require_verified_user(request):
            user_has_device = django_otp.user_has_device(user, confirmed=True)

            if user_has_device and not user.is_verified():
                return redirect_to_login(
                    request.get_full_path(), login_url=reverse("wagtail_2fa_auth")
                )

            elif not user_has_device and settings.WAGTAIL_2FA_REQUIRED:
                # only allow the user to visit the admin index page and the
                # admin setup page
                return redirect_to_login(
                    request.get_full_path(), login_url=reverse("wagtail_2fa_device_new")
                ) 
Example #5
Source File: test_lazyobject.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_pickle_with_reduce(self):
        """
        Test in a fairly synthetic setting.
        """
        # Test every pickle protocol available
        for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
            lazy_objs = [
                SimpleLazyObject(lambda: BaseBaz()),
                SimpleLazyObject(lambda: Baz(1)),
                SimpleLazyObject(lambda: BazProxy(Baz(2))),
            ]
            for obj in lazy_objs:
                pickled = pickle.dumps(obj, protocol)
                unpickled = pickle.loads(pickled)
                self.assertEqual(unpickled, obj)
                self.assertEqual(unpickled.baz, 'right') 
Example #6
Source File: test_lazyobject.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_pickle_model(self):
        """
        Test on an actual model, based on the report in #25426.
        """
        category = Category.objects.create(name="thing1")
        CategoryInfo.objects.create(category=category)
        # Test every pickle protocol available
        for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
            lazy_category = SimpleLazyObject(lambda: category)
            # Test both if we accessed a field on the model and if we didn't.
            lazy_category.categoryinfo
            lazy_category_2 = SimpleLazyObject(lambda: category)
            with warnings.catch_warnings(record=True) as recorded:
                self.assertEqual(pickle.loads(pickle.dumps(lazy_category, protocol)), category)
                self.assertEqual(pickle.loads(pickle.dumps(lazy_category_2, protocol)), category)
                # Assert that there were no warnings.
                self.assertEqual(len(recorded), 0) 
Example #7
Source File: test_query.py    From graphene-django with MIT License 6 votes vote down vote up
def test_should_query_wrapped_simplelazy_objects():
    class ReporterType(DjangoObjectType):
        class Meta:
            model = Reporter
            fields = ("id",)

    class Query(graphene.ObjectType):
        reporter = graphene.Field(ReporterType)

        def resolve_reporter(self, info):
            return SimpleLazyObject(lambda: SimpleLazyObject(lambda: Reporter(id=1)))

    schema = graphene.Schema(query=Query)
    query = """
        query {
          reporter {
            id
          }
        }
    """
    result = schema.execute(query)
    assert not result.errors
    assert result.data == {"reporter": {"id": "1"}} 
Example #8
Source File: test_query.py    From graphene-django with MIT License 6 votes vote down vote up
def test_should_query_simplelazy_objects():
    class ReporterType(DjangoObjectType):
        class Meta:
            model = Reporter
            fields = ("id",)

    class Query(graphene.ObjectType):
        reporter = graphene.Field(ReporterType)

        def resolve_reporter(self, info):
            return SimpleLazyObject(lambda: Reporter(id=1))

    schema = graphene.Schema(query=Query)
    query = """
        query {
          reporter {
            id
          }
        }
    """
    result = schema.execute(query)
    assert not result.errors
    assert result.data == {"reporter": {"id": "1"}} 
Example #9
Source File: context_processors.py    From python2017 with MIT License 6 votes vote down vote up
def csrf(request):
    """
    Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if
    it has not been provided by either a view decorator or the middleware
    """
    def _get_val():
        token = get_token(request)
        if token is None:
            # In order to be able to provide debugging info in the
            # case of misconfiguration, we use a sentinel value
            # instead of returning an empty dict.
            return 'NOTPROVIDED'
        else:
            return force_text(token)

    return {'csrf_token': SimpleLazyObject(_get_val)} 
Example #10
Source File: test_debug.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_ignore_traceback_evaluation_exceptions(self):
        """
        Don't trip over exceptions generated by crafted objects when
        evaluating them while cleansing (#24455).
        """
        class BrokenEvaluation(Exception):
            pass

        def broken_setup():
            raise BrokenEvaluation

        request = self.rf.get('/test_view/')
        broken_lazy = SimpleLazyObject(broken_setup)
        try:
            bool(broken_lazy)
        except BrokenEvaluation:
            exc_type, exc_value, tb = sys.exc_info()

        self.assertIn(
            "BrokenEvaluation",
            ExceptionReporter(request, exc_type, exc_value, tb).get_traceback_html(),
            "Evaluation exception reason not mentioned in traceback"
        ) 
Example #11
Source File: context_processors.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def csrf(request):
    """
    Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if
    it has not been provided by either a view decorator or the middleware
    """
    def _get_val():
        token = get_token(request)
        if token is None:
            # In order to be able to provide debugging info in the
            # case of misconfiguration, we use a sentinel value
            # instead of returning an empty dict.
            return 'NOTPROVIDED'
        else:
            return smart_text(token)

    return {'csrf_token': SimpleLazyObject(_get_val)} 
Example #12
Source File: middlewares.py    From zentral with Apache License 2.0 6 votes vote down vote up
def csp_middleware(get_response):
    def middleware(request):
        nonce_func = partial(make_csp_nonce, request)
        request.csp_nonce = SimpleLazyObject(nonce_func)

        response = get_response(request)

        if CSP_HEADER in response:
            # header already present (HOW ???)
            return response

        if response.status_code in (INTERNAL_SERVER_ERROR, NOT_FOUND) and settings.DEBUG:
            # no policies in debug views
            return response

        response[CSP_HEADER] = build_csp_header(request)

        return response

    return middleware 
Example #13
Source File: context_processors.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def csrf(request):
    """
    Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if
    it has not been provided by either a view decorator or the middleware
    """
    def _get_val():
        token = get_token(request)
        if token is None:
            # In order to be able to provide debugging info in the
            # case of misconfiguration, we use a sentinel value
            # instead of returning an empty dict.
            return 'NOTPROVIDED'
        else:
            return token

    return {'csrf_token': SimpleLazyObject(_get_val)} 
Example #14
Source File: context_processors.py    From steemprojects.com with MIT License 6 votes vote down vote up
def lazy_profile(request):
    """
    Returns context variables required by templates that assume a profile
    on each request
    """

    def get_user_profile():
        if hasattr(request, 'profile'):
            return request.profile
        else:
            return request.user.profile

    data = {
        'profile': SimpleLazyObject(get_user_profile),
        }
    return data 
Example #15
Source File: models.py    From casepro with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def encode_scope(*args):
        types = []
        for arg in args:
            # request.user is actually a SimpleLazyObject proxy
            if isinstance(arg, User) and isinstance(arg, SimpleLazyObject):
                arg = User(pk=arg.pk)

            types.append(type(arg))

        if types == [Org]:
            return "org:%d" % args[0].pk
        elif types == [Partner]:
            return "partner:%d" % args[0].pk
        elif types == [Org, User]:
            return "org:%d:user:%d" % (args[0].pk, args[1].pk)
        elif types == [Label]:
            return "label:%d" % args[0].pk
        else:  # pragma: no cover
            raise ValueError("Unsupported scope: %s" % ",".join([t.__name__ for t in types])) 
Example #16
Source File: test_lazyobject.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_pickle_with_reduce(self):
        """
        Test in a fairly synthetic setting.
        """
        # Test every pickle protocol available
        for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
            lazy_objs = [
                SimpleLazyObject(lambda: BaseBaz()),
                SimpleLazyObject(lambda: Baz(1)),
                SimpleLazyObject(lambda: BazProxy(Baz(2))),
            ]
            for obj in lazy_objs:
                pickled = pickle.dumps(obj, protocol)
                unpickled = pickle.loads(pickled)
                self.assertEqual(unpickled, obj)
                self.assertEqual(unpickled.baz, 'right') 
Example #17
Source File: test_lazyobject.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_pickle_model(self):
        """
        Test on an actual model, based on the report in #25426.
        """
        category = Category.objects.create(name="thing1")
        CategoryInfo.objects.create(category=category)
        # Test every pickle protocol available
        for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
            lazy_category = SimpleLazyObject(lambda: category)
            # Test both if we accessed a field on the model and if we didn't.
            lazy_category.categoryinfo
            lazy_category_2 = SimpleLazyObject(lambda: category)
            with warnings.catch_warnings(record=True) as recorded:
                self.assertEqual(pickle.loads(pickle.dumps(lazy_category, protocol)), category)
                self.assertEqual(pickle.loads(pickle.dumps(lazy_category_2, protocol)), category)
                # Assert that there were no warnings.
                self.assertEqual(len(recorded), 0) 
Example #18
Source File: models.py    From django-trackstats with MIT License 6 votes vote down vote up
def _register(self, defaults=None, **kwargs):
        """Fetch (update or create)  an instance, lazily.

        We're doing this lazily, so that it becomes possible to define
        custom enums in your code, even before the Django ORM is fully
        initialized.

        Domain.objects.SHOPPING = Domain.objects.register(
            ref='shopping',
            name='Webshop')
        Domain.objects.USERS = Domain.objects.register(
            ref='users',
            name='User Accounts')
        """
        f = lambda: self.update_or_create(defaults=defaults, **kwargs)[0]
        ret = SimpleLazyObject(f)
        self._lazy_entries.append(ret)
        return ret 
Example #19
Source File: utils.py    From django-tracking-analyzer with GNU General Public License v3.0 5 votes vote down vote up
def build_mock_request(url, user_agent=None):
    """
    Helper function to manually build a ``WSGIRequest`` object to be used
    to test the view.

    :param url: A string representing the URL for the request.
    :return: A prepared ``WSGIRequest`` object.
    """
    # Build an interesting request.
    request = RequestFactory().get(url)
    request.COOKIES = {
        # Some silly cookies, just a PoC.
        'company': 'MaykinMedia',
        'worker': 'Jose',
    }

    request.META['HTTP_USER_AGENT'] = user_agent or (
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 '
        '(KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36'
    )
    # Set up a known IP address to retrieve GeoIP data. This one is from
    # OpenDNS service, check https://www.opendns.com/
    request.META['REMOTE_ADDR'] = '208.67.222.222'

    # Request is performed by a system user.
    request.user, _ = User.objects.get_or_create(
        username='test_user',
        first_name='Test',
        last_name='User',
        email='test_user@maykinmedia.nl'
    )

    # Set up the 'django-user-agent' machinery in the request, as its own
    # middleware does.
    request.user_agent = SimpleLazyObject(lambda: get_user_agent(request))

    return request 
Example #20
Source File: test_simplelazyobject.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_pickle(self):
        user = User.objects.create_user('johndoe', 'john@example.com', 'pass')
        x = SimpleLazyObject(lambda: user)
        pickle.dumps(x)
        # Try the variant protocol levels.
        pickle.dumps(x, 0)
        pickle.dumps(x, 1)
        pickle.dumps(x, 2) 
Example #21
Source File: test_lazyobject.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def lazy_wrap(self, wrapped_object):
        return SimpleLazyObject(lambda: wrapped_object) 
Example #22
Source File: test_lazyobject.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_repr(self):
        # First, for an unevaluated SimpleLazyObject
        obj = self.lazy_wrap(42)
        # __repr__ contains __repr__ of setup function and does not evaluate
        # the SimpleLazyObject
        self.assertRegex(repr(obj), '^<SimpleLazyObject:')
        self.assertIs(obj._wrapped, empty)  # make sure evaluation hasn't been triggered

        self.assertEqual(obj, 42)  # evaluate the lazy object
        self.assertIsInstance(obj._wrapped, int)
        self.assertEqual(repr(obj), '<SimpleLazyObject: 42>') 
Example #23
Source File: test_lazyobject.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_dict(self):
        # See ticket #18447
        lazydict = SimpleLazyObject(lambda: {'one': 1})
        self.assertEqual(lazydict['one'], 1)
        lazydict['one'] = -1
        self.assertEqual(lazydict['one'], -1)
        self.assertIn('one', lazydict)
        self.assertNotIn('two', lazydict)
        self.assertEqual(len(lazydict), 1)
        del lazydict['one']
        with self.assertRaises(KeyError):
            lazydict['one'] 
Example #24
Source File: test_lazyobject.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_list_set(self):
        lazy_list = SimpleLazyObject(lambda: [1, 2, 3, 4, 5])
        lazy_set = SimpleLazyObject(lambda: {1, 2, 3, 4})
        self.assertIn(1, lazy_list)
        self.assertIn(1, lazy_set)
        self.assertNotIn(6, lazy_list)
        self.assertNotIn(6, lazy_set)
        self.assertEqual(len(lazy_list), 5)
        self.assertEqual(len(lazy_set), 4) 
Example #25
Source File: middleware.py    From django-otp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __call__(self, request):
        user = getattr(request, 'user', None)
        if user is not None:
            request.user = SimpleLazyObject(functools.partial(self._verify_user, request, user))

        return self.get_response(request) 
Example #26
Source File: permissions.py    From django-is-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def validator_kwargs(self, request, validator):
        if 'pk' in request.kwargs:
            Model = getattr(validator.im_self, 'model')
            if Model:
                return {'obj': SimpleLazyObject(lambda: get_obj(Model, request.kwargs['pk']))}
        return {} 
Example #27
Source File: test_lazyobject.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_list_set(self):
        lazy_list = SimpleLazyObject(lambda: [1, 2, 3, 4, 5])
        lazy_set = SimpleLazyObject(lambda: {1, 2, 3, 4})
        self.assertIn(1, lazy_list)
        self.assertIn(1, lazy_set)
        self.assertNotIn(6, lazy_list)
        self.assertNotIn(6, lazy_set)
        self.assertEqual(len(lazy_list), 5)
        self.assertEqual(len(lazy_set), 4) 
Example #28
Source File: test_encoding.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_force_text_lazy(self):
        s = SimpleLazyObject(lambda: 'x')
        self.assertTrue(type(force_text(s)), str) 
Example #29
Source File: measure_tags.py    From openprescribing with MIT License 5 votes vote down vote up
def _lazy_load_measure_tags(path):
    return SimpleLazyObject(partial(_load_measure_tags, path)) 
Example #30
Source File: test_encoding.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_force_text_lazy(self):
        s = SimpleLazyObject(lambda: 'x')
        self.assertIs(type(force_text(s)), str)