我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用django.utils.functional.SimpleLazyObject()。
def __init__(self, queue_name, serializer, rabbitmq_configs, *args, **kwargs): self.queue_name = queue_name self.serialize = serializer super(RabbitMQRunner, self).__init__(*args, **kwargs) self.log(logging.DEBUG, "RabbitMQ Runner is ready...") def _create_pool(): connection_pool_configs = rabbitmq_configs.get('connection_pool_configs', {}) def create_connection(): self.log(logging.DEBUG, "Creating new rabbitmq connection") con_params = pika.ConnectionParameters(**rabbitmq_configs.get('connection_parameters', {})) return pika.BlockingConnection(con_params) return pika_pool.QueuedPool( create=create_connection, **connection_pool_configs ) self._pool = SimpleLazyObject(_create_pool)
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
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)}
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)}
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
def _lazy_re_compile(regex, flags=0): """Lazily compile a regex with flags.""" def _compile(): # Compile the regex if it was not passed pre-compiled. if isinstance(regex, six.string_types): return re.compile(regex, flags) else: assert not flags, "flags must be empty if regex is passed pre-compiled" return regex return SimpleLazyObject(_compile)
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))
def process_request(self, request): assert hasattr(request, 'session'), ( "The Django authentication middleware requires session middleware " "to be installed. Edit your MIDDLEWARE%s setting to insert " "'django.contrib.sessions.middleware.SessionMiddleware' before " "'django.contrib.auth.middleware.AuthenticationMiddleware'." ) % ("_CLASSES" if settings.MIDDLEWARE is None else "") request.user = SimpleLazyObject(lambda: get_user(request))
def process_request(self, request): assert hasattr(request, 'session'), ( "The Django authentication middleware requires session middleware " "to be installed. Edit your MIDDLEWARE setting to insert " "'django.contrib.sessions.middleware.SessionMiddleware' before " "'django.contrib.auth.middleware.AuthenticationMiddleware'." ) request.user = SimpleLazyObject(lambda: get_user(request))
def set_tenant(cls, tenant_slug): cls._threadmap[threading.get_ident()] = SimpleLazyObject( lambda: Tenant.objects.filter(slug=tenant_slug).first())
def process_request(self, request): request.tenant = SimpleLazyObject(lambda: get_tenant(request)) self._threadmap[threading.get_ident()] = request.tenant return request
def process_request(self, request): request.maybe_intercooler = _maybe_intercooler.__get__(request) request.is_intercooler = _is_intercooler.__get__(request) request.intercooler_data = SimpleLazyObject(intercooler_data.__get__(request))
def regions(self, item, inherit_from=None, regions=Regions): """regions(self, item, *, inherit_from=None, regions=Regions) Return a ``Regions`` instance which lazily wraps the ``contents_for_item`` call. This is especially useful in conjunction with the ``render_region`` template tag. The ``inherit_from`` argument is directly forwarded to ``contents_for_item`` to allow regions with inherited content. """ return regions( item=item, contents=SimpleLazyObject( lambda: contents_for_item(item, self.plugins(), inherit_from) ), renderer=self, )
def site(request): return { 'site': SimpleLazyObject(lambda: get_current_site(request)), }
def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. if not request.user.is_authenticated(): request.user = SimpleLazyObject(lambda : get_user_jwt(request)) response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response
def process_request(self, request): assert hasattr(request, 'session'), ( "The authentication middleware requires session middleware " "to be installed. Edit your MIDDLEWARE_CLASSES setting to insert " "'django.contrib.sessions.middleware.SessionMiddleware' before " "'kolibri.auth.middleware.CustomAuthenticationMiddleware'." ) request.user = SimpleLazyObject(lambda: _get_user(request))
def __call__(self, request): if not (request.user and is_authenticated(request.user)): request.user = SimpleLazyObject(lambda: get_user_jwt(request)) return self.get_response(request)
def resolve(self, next, root, args, context, info): if not (context.user and is_authenticated(context.user)): context.user = SimpleLazyObject(lambda: get_user_jwt(context)) return next(root, args, context, info)
def register_system_offer_group(slug, default_name=None): """ Register a system offer group (an offer group that referenced by code). Returns the OfferGroup instance. To get / create a system offer group, call this function somewhere in your code base and assign the result to a constant. The return value is a lazy evaluated function which will, on-first-access, create the OfferGroup. On subsequent accesses, it will simply fetch the offer group and return it. """ lazy_group = SimpleLazyObject(lambda: insupd_system_offer_group(slug, default_name)) _system_group_registry.append(lazy_group) return lazy_group
def site(request): site = SimpleLazyObject(lambda: get_current_site(request)) protocol = 'https' if request.is_secure() else 'http' return { 'site': site, 'site_root': SimpleLazyObject(lambda: "{0}://{1}".format(protocol, site.domain)), }
def is_type_of(cls, root, info): if isinstance(root, SimpleLazyObject): root._setup() root = root._wrapped if isinstance(root, cls): return True if not is_valid_django_model(type(root)): raise Exception(( 'Received incompatible instance "{}".' ).format(root)) model = root._meta.model return model == cls._meta.model
def test_should_query_simplelazy_objects(): class ReporterType(DjangoObjectType): class Meta: model = Reporter only_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' } }