当前位置: 首页>>代码示例>>Python>>正文


Python functional.SimpleLazyObject方法代码示例

本文整理汇总了Python中django.utils.functional.SimpleLazyObject方法的典型用法代码示例。如果您正苦于以下问题:Python functional.SimpleLazyObject方法的具体用法?Python functional.SimpleLazyObject怎么用?Python functional.SimpleLazyObject使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.utils.functional的用法示例。


在下文中一共展示了functional.SimpleLazyObject方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: encode_scope

# 需要导入模块: from django.utils import functional [as 别名]
# 或者: from django.utils.functional import SimpleLazyObject [as 别名]
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])) 
开发者ID:rapidpro,项目名称:casepro,代码行数:21,代码来源:models.py

示例2: csrf

# 需要导入模块: from django.utils import functional [as 别名]
# 或者: from django.utils.functional import SimpleLazyObject [as 别名]
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)} 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:18,代码来源:context_processors.py

示例3: _register

# 需要导入模块: from django.utils import functional [as 别名]
# 或者: from django.utils.functional import SimpleLazyObject [as 别名]
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 
开发者ID:pennersr,项目名称:django-trackstats,代码行数:20,代码来源:models.py

示例4: csp_middleware

# 需要导入模块: from django.utils import functional [as 别名]
# 或者: from django.utils.functional import SimpleLazyObject [as 别名]
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 
开发者ID:zentralopensource,项目名称:zentral,代码行数:22,代码来源:middlewares.py

示例5: csrf

# 需要导入模块: from django.utils import functional [as 别名]
# 或者: from django.utils.functional import SimpleLazyObject [as 别名]
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)} 
开发者ID:Yeah-Kun,项目名称:python,代码行数:18,代码来源:context_processors.py

示例6: csrf

# 需要导入模块: from django.utils import functional [as 别名]
# 或者: from django.utils.functional import SimpleLazyObject [as 别名]
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)} 
开发者ID:drexly,项目名称:openhgsenti,代码行数:18,代码来源:context_processors.py

示例7: test_should_query_simplelazy_objects

# 需要导入模块: from django.utils import functional [as 别名]
# 或者: from django.utils.functional import SimpleLazyObject [as 别名]
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"}} 
开发者ID:graphql-python,项目名称:graphene-django,代码行数:25,代码来源:test_query.py

示例8: test_should_query_wrapped_simplelazy_objects

# 需要导入模块: from django.utils import functional [as 别名]
# 或者: from django.utils.functional import SimpleLazyObject [as 别名]
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"}} 
开发者ID:graphql-python,项目名称:graphene-django,代码行数:25,代码来源:test_query.py

示例9: process_request

# 需要导入模块: from django.utils import functional [as 别名]
# 或者: from django.utils.functional import SimpleLazyObject [as 别名]
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")
                ) 
开发者ID:labd,项目名称:wagtail-2fa,代码行数:20,代码来源:middleware.py

示例10: test_ignore_traceback_evaluation_exceptions

# 需要导入模块: from django.utils import functional [as 别名]
# 或者: from django.utils.functional import SimpleLazyObject [as 别名]
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"
        ) 
开发者ID:nesdis,项目名称:djongo,代码行数:25,代码来源:test_debug.py

示例11: test_pickle_with_reduce

# 需要导入模块: from django.utils import functional [as 别名]
# 或者: from django.utils.functional import SimpleLazyObject [as 别名]
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') 
开发者ID:nesdis,项目名称:djongo,代码行数:18,代码来源:test_lazyobject.py

示例12: test_pickle_model

# 需要导入模块: from django.utils import functional [as 别名]
# 或者: from django.utils.functional import SimpleLazyObject [as 别名]
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) 
开发者ID:nesdis,项目名称:djongo,代码行数:19,代码来源:test_lazyobject.py

示例13: lazy_profile

# 需要导入模块: from django.utils import functional [as 别名]
# 或者: from django.utils.functional import SimpleLazyObject [as 别名]
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 
开发者ID:wise-team,项目名称:steemprojects.com,代码行数:18,代码来源:context_processors.py

示例14: process_request

# 需要导入模块: from django.utils import functional [as 别名]
# 或者: from django.utils.functional import SimpleLazyObject [as 别名]
def process_request(self, request):
        assert hasattr(request, 'session'), (
            "The Django authentication middleware requires session middleware "
            "to be installed. Edit your MIDDLEWARE_CLASSES setting to insert "
            "'django.contrib.sessions.middleware.SessionMiddleware' before "
            "'django.contrib.auth.middleware.AuthenticationMiddleware'."
        )
        request.user = SimpleLazyObject(lambda: get_user(request)) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:10,代码来源:middleware.py

示例15: process_request

# 需要导入模块: from django.utils import functional [as 别名]
# 或者: from django.utils.functional import SimpleLazyObject [as 别名]
def process_request(self, request):
        request.user_agent = SimpleLazyObject(lambda: get_user_agent(request)) 
开发者ID:yandenghong,项目名称:KortURL,代码行数:4,代码来源:user_agents_middleware.py


注:本文中的django.utils.functional.SimpleLazyObject方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。