我们从Python开源项目中,提取了以下19个代码示例,用于说明如何使用django.utils.functional.lazy()。
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) _get_val = lazy(_get_val, six.text_type) return {'csrf_token': _get_val() }
def debug(request): """ Returns context variables helpful for debugging. """ context_extras = {} if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS: context_extras['debug'] = True from django.db import connection # Return a lazy reference that computes connection.queries on access, # to ensure it contains queries triggered after this function runs. context_extras['sql_queries'] = lazy(lambda: connection.queries, list) return context_extras
def lazy_number(func, resultclass, number=None, **kwargs): if isinstance(number, six.integer_types): kwargs['number'] = number proxy = lazy(func, resultclass)(**kwargs) else: original_kwargs = kwargs.copy() class NumberAwareString(resultclass): def __mod__(self, rhs): if isinstance(rhs, dict) and number: try: number_value = rhs[number] except KeyError: raise KeyError('Your dictionary lacks key \'%s\'. ' 'Please provide it, because it is required to ' 'determine whether string is singular or plural.' % number) else: number_value = rhs kwargs['number'] = number_value translated = func(**kwargs) try: translated = translated % rhs except TypeError: # String doesn't contain a placeholder for the number pass return translated proxy = lazy(lambda **kwargs: NumberAwareString(), NumberAwareString)(**kwargs) proxy.__reduce__ = lambda: (_lazy_number_unpickle, (func, resultclass, number, original_kwargs)) return proxy
def override_gettext(real_translation): """Replace Django's translation functions with safe versions.""" translation.gettext = real_translation.gettext translation.ugettext = real_translation.ugettext translation.ngettext = real_translation.ngettext translation.ungettext = real_translation.ungettext translation.gettext_lazy = lazy(real_translation.gettext, str) translation.ugettext_lazy = lazy(real_translation.ugettext, unicode) translation.ngettext_lazy = lazy(real_translation.ngettext, str) translation.ungettext_lazy = lazy(real_translation.ungettext, unicode)
def patch_reverse(): """Overwrite the default reverse implementation. Monkey-patches the urlresolvers.reverse function. Will not patch twice. """ global django_reverse, django_reverse_lazy if hasattr(settings, 'REVERSE_METHOD') and django_reverse is None: django_reverse = urls.reverse django_reverse_lazy = urls.reverse_lazy module_name, func_name = settings.REVERSE_METHOD.rsplit('.', 1) reverse = getattr(importlib.import_module(module_name), func_name) urls.reverse = reverse urls.reverse_lazy = lazy(reverse, six.text_type)
def get_actions(self): resolved = self.RESOLVED.copy() resolved['help_text'] = lazy( lambda: self.RESOLVED['help_text'] + self.creator_assign_text() ) reopened = self.REOPENED.copy() reopened['help_text'] = lazy( lambda: self.REOPENED['help_text'] + self.resolver_assign_text() ) verified = self.VERIFIED.copy() verified['help_text'] = lazy( lambda: self.VERIFIED['help_text'] + self.resolver_assign_text() ) if self.bug: state = self.bug.state else: state = None if state == State.NEW: return [self.COMMENT, resolved, self.ENTRUSTED] elif state == State.ENTRUSTED: return [self.COMMENT, resolved] elif state in self.RESOLVED_STATES: return [self.COMMENT, verified, reopened, self.LIVE, self.CLOSED] elif state == State.REOPENED: return [self.COMMENT, resolved, self.ENTRUSTED] elif state == State.LIVE: return [self.COMMENT, reopened, self.CLOSED] elif state == State.CLOSED: return [self.COMMENT, reopened] elif state == State.VERIFIED: return [self.COMMENT, reopened, self.LIVE, self.CLOSED] elif state is None: return [ {'action': 'create', 'label': 'Create', 'help_text': "Create a bug."}, ] else: assert False, 'Unknown state %s' % state
def __init__(self, target_model, filter_name=None, **kwargs): super(ModelChooserBlock, self).__init__(**kwargs) self._target_model = target_model self.filter_name = filter_name if self.meta.icon == 'placeholder': # Get the icon from the chooser. # The chooser may not have been registered yet, depending upon # import orders and things, so get the icon lazily self.meta.icon = lazy(lambda: self.chooser.icon, str)()
def debug(request): """ Returns context variables helpful for debugging. """ context_extras = {} if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS: context_extras['debug'] = True from django.db import connections # Return a lazy reference that computes connection.queries on access, # to ensure it contains queries triggered after this function runs. context_extras['sql_queries'] = lazy( lambda: list(itertools.chain(*[connections[x].queries for x in connections])), list ) return context_extras
def lazy_number(func, resultclass, number=None, **kwargs): if isinstance(number, six.integer_types): kwargs['number'] = number proxy = lazy(func, resultclass)(**kwargs) else: original_kwargs = kwargs.copy() class NumberAwareString(resultclass): def __bool__(self): return bool(kwargs['singular']) def __nonzero__(self): # Python 2 compatibility return type(self).__bool__(self) def __mod__(self, rhs): if isinstance(rhs, dict) and number: try: number_value = rhs[number] except KeyError: raise KeyError( "Your dictionary lacks key '%s\'. Please provide " "it, because it is required to determine whether " "string is singular or plural." % number ) else: number_value = rhs kwargs['number'] = number_value translated = func(**kwargs) try: translated = translated % rhs except TypeError: # String doesn't contain a placeholder for the number pass return translated proxy = lazy(lambda **kwargs: NumberAwareString(), NumberAwareString)(**kwargs) proxy.__reduce__ = lambda: (_lazy_number_unpickle, (func, resultclass, number, original_kwargs)) return proxy
def test_find_item_lazy(self): lazy_attribute = lazy(lambda x: x, str)('Test') api = ToolbarAPIMixin() api.add_link_item(lazy_attribute, None) result = api.find_first(LinkItem, name='Test') self.assertNotEqual(result, None) self.assertEqual(result.index, 0)
def _lazy_get_settings(opt, ttype, default_value=obj): return lazy(_call_getattr, ttype)(opt, default_value) # Lazyly read configurations to allow @override_settings
def lazy_number(func, resultclass, number=None, **kwargs): if isinstance(number, six.integer_types): kwargs['number'] = number proxy = lazy(func, resultclass)(**kwargs) else: class NumberAwareString(resultclass): def __mod__(self, rhs): if isinstance(rhs, dict) and number: try: number_value = rhs[number] except KeyError: raise KeyError('Your dictionary lacks key \'%s\'. ' 'Please provide it, because it is required to ' 'determine whether string is singular or plural.' % number) else: number_value = rhs kwargs['number'] = number_value translated = func(**kwargs) try: translated = translated % rhs except TypeError: # String doesn't contain a placeholder for the number pass return translated proxy = lazy(lambda **kwargs: NumberAwareString(), NumberAwareString)(**kwargs) return proxy