本文整理汇总了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]))
示例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)}
示例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
示例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
示例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)}
示例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)}
示例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"}}
示例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"}}
示例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")
)
示例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"
)
示例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')
示例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)
示例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
示例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))
示例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))