示例#1
0
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
def lazy_number(func, resultclass, number=None, **kwargs):
    if isinstance(number, int):
        kwargs['number'] = number
        proxy = lazy(func, resultclass)(**kwargs)
    else:
        original_kwargs = kwargs.copy()

        class NumberAwareString(resultclass):
            def __bool__(self):
                return bool(kwargs['singular'])

            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
示例#3
0
def auth(request):
    """
    Returns context variables required by apps that use Django's authentication
    system.

    If there is no 'user' attribute in the request, uses AnonymousUser (from
    django.contrib.auth).
    """
    # If we access request.user, request.session is accessed, which results in
    # 'Vary: Cookie' being sent in every request that uses this context
    # processor, which can easily be every request on a site if
    # TEMPLATE_CONTEXT_PROCESSORS has this context processor added.  This kills
    # the ability to cache.  So, we carefully ensure these attributes are lazy.
    # We don't use django.utils.functional.lazy() for User, because that
    # requires knowing the class of the object we want to proxy, which could
    # break with custom auth backends.  LazyObject is a less complete but more
    # flexible solution that is a good enough wrapper for 'User'.
    def get_user():
        if hasattr(request, 'user'):
            return request.user
        else:
            from django.contrib.auth.models import AnonymousUser
            return AnonymousUser()

    return {
        'user': SimpleLazyObject(get_user),
        'messages': lazy(memoize(lambda: get_user().get_and_delete_messages(), {}, 0), list)(),
        'perms':  lazy(lambda: PermWrapper(get_user()), PermWrapper)(),
    }
示例#4
0
    def __init__(self, attrs=None, date_format=None, time_format=None):
        attrs = attrs or {}
        if 'placeholder' in attrs:
            del attrs['placeholder']
        date_attrs = dict(attrs)
        time_attrs = dict(attrs)
        date_attrs.setdefault('class', 'form-control splitdatetimepart')
        time_attrs.setdefault('class', 'form-control splitdatetimepart')
        date_attrs.setdefault('autocomplete', 'off')
        time_attrs.setdefault('autocomplete', 'off')
        date_attrs['class'] += ' datepickerfield'
        time_attrs['class'] += ' timepickerfield'

        def date_placeholder():
            df = date_format or get_format('DATE_INPUT_FORMATS')[0]
            return now().replace(
                year=2000, month=12, day=31, hour=18, minute=0, second=0, microsecond=0
            ).strftime(df)

        def time_placeholder():
            tf = time_format or get_format('TIME_INPUT_FORMATS')[0]
            return now().replace(
                year=2000, month=1, day=1, hour=0, minute=0, second=0, microsecond=0
            ).strftime(tf)

        date_attrs['placeholder'] = lazy(date_placeholder, str)
        time_attrs['placeholder'] = lazy(time_placeholder, str)

        widgets = (
            forms.DateInput(attrs=date_attrs, format=date_format),
            forms.TimeInput(attrs=time_attrs, format=time_format),
        )
        # Skip one hierarchy level
        forms.MultiWidget.__init__(self, widgets, attrs)
示例#5
0
    def display_text(cls, bc):
        """Return the text to be used for representing the given choice
        instance `bc` to the user.

        Override this to customize the display text of choices.
        :class:`lino.modlib.users.choicelists.UserGroups` and
        :class:`lino.modlib.cv.models.CefLevel` used to do this before
        we had the :attr:`ChoiceList.show_values` option.

        This must be lazyly translatable because the result are also
        used to build the `choices` attribute of ChoiceListFields on
        this choicelist.

        Note that Django's `lazy` function has a list of
        "resultclasses" which are used "so that the automatic forcing
        of the lazy evaluation code is triggered".

        """
        if cls.show_values:
            # if unicodeerror:
            # assert_pure(str(bc))
            # str(bc)

            def fn(bc):
                # return "%s (%s)" % (bc.value, str(bc))
                return "{0} ({1})".format(bc.value, bc)
            return lazy(fn, str, six.text_type)(bc)
        return lazy(str, str, six.text_type)(bc)
示例#6
0
def stats(request):
    def _formations():
        return str(Formation.objects.exclude(statut=StatutsFormation.supprimee).count())

    def _etablissements():
        data = Formation.objects.exclude(statut=StatutsFormation.supprimee) \
            .values('etablissement')
        etablissements = set()
        for d in data:
            etablissements.add(d['etablissement'])
        return str(len(etablissements))

    def _disciplines():
        data = Formation.objects.exclude(statut=StatutsFormation.supprimee) \
            .values('discipline_1', 'discipline_2', 'discipline_3')
        disciplines = set()
        for d in data:
            disciplines.add(d['discipline_1'])
            disciplines.add(d['discipline_2'])
            disciplines.add(d['discipline_3'])
        return str(len(disciplines))

    def _pays():
        data = Formation.objects.exclude(statut=StatutsFormation.supprimee).values('etablissement__pays')
        pays = set()
        for d in data:
            pays.add(d['etablissement__pays'])
        return str(len(pays))

    return {
        'stats_formations': lazy(_formations, str),
        'stats_etablissements': lazy(_etablissements, str),
        'stats_disciplines': lazy(_disciplines, str),
        'stats_pays': lazy(_pays, str),
        }
示例#7
0
    def __init__(self, *args, **kwargs):
        """We need to override this to make the choices lazy and prevent import madness"""
        super(Group, self).__init__(*args, **kwargs)

        field = self._meta.get_field('permissions')
        field._choices = lazy(get_permission_choices, list)()
        field.item_field_type._choices = lazy(get_permission_choices, list)()
示例#8
0
 def test_IPAddressField(self):
     with warnings.catch_warnings(record=True):
         warnings.simplefilter("always")
         lazy_func = lazy(lambda: "127.0.0.1", six.text_type)
         self.assertIsInstance(IPAddressField().get_prep_value(lazy_func()), six.text_type)
         lazy_func = lazy(lambda: 0, int)
         self.assertIsInstance(IPAddressField().get_prep_value(lazy_func()), six.text_type)
示例#9
0
文件: tests.py 项目: BSgitcep/django
 def test_CommaSeparatedIntegerField(self):
     lazy_func = lazy(lambda: '1,2', six.text_type)
     self.assertIsInstance(
         CommaSeparatedIntegerField().get_prep_value(lazy_func()),
         six.text_type)
     lazy_func = lazy(lambda: 0, int)
     self.assertIsInstance(
         CommaSeparatedIntegerField().get_prep_value(lazy_func()),
         six.text_type)
示例#10
0
文件: tests.py 项目: BSgitcep/django
 def test_FileField(self):
     lazy_func = lazy(lambda: 'filename.ext', six.text_type)
     self.assertIsInstance(
         FileField().get_prep_value(lazy_func()),
         six.text_type)
     lazy_func = lazy(lambda: 0, int)
     self.assertIsInstance(
         FileField().get_prep_value(lazy_func()),
         six.text_type)
示例#11
0
文件: tests.py 项目: BSgitcep/django
 def test_FilePathField(self):
     lazy_func = lazy(lambda: 'tests.py', six.text_type)
     self.assertIsInstance(
         FilePathField().get_prep_value(lazy_func()),
         six.text_type)
     lazy_func = lazy(lambda: 0, int)
     self.assertIsInstance(
         FilePathField().get_prep_value(lazy_func()),
         six.text_type)
示例#12
0
文件: tests.py 项目: BSgitcep/django
 def test_GenericIPAddressField(self):
     lazy_func = lazy(lambda: '127.0.0.1', six.text_type)
     self.assertIsInstance(
         GenericIPAddressField().get_prep_value(lazy_func()),
         six.text_type)
     lazy_func = lazy(lambda: 0, int)
     self.assertIsInstance(
         GenericIPAddressField().get_prep_value(lazy_func()),
         six.text_type)
示例#13
0
文件: tests.py 项目: BSgitcep/django
 def test_TextField(self):
     lazy_func = lazy(lambda: 'Abc', six.text_type)
     self.assertIsInstance(
         TextField().get_prep_value(lazy_func()),
         six.text_type)
     lazy_func = lazy(lambda: 0, int)
     self.assertIsInstance(
         TextField().get_prep_value(lazy_func()),
         six.text_type)
示例#14
0
    def test_lazy_equality(self):
        """
        == and != work correctly for Promises.
        """
        lazy_a = lazy(lambda: 4, int)
        lazy_b = lazy(lambda: 4, int)
        lazy_c = lazy(lambda: 5, int)

        self.assertEqual(lazy_a(), lazy_b())
        self.assertNotEqual(lazy_b(), lazy_c())
示例#15
0
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)
示例#16
0
 def display_text(cls, bc):
     """
     Override this to customize the display text of choices.
     :class:`lino.core.perms.UserGroups` and :class:`lino.modlib.cv.models.CefLevel`
     used to do this before we had the 
     :attr:`ChoiceList.show_values` option.
     """
     if cls.show_values:
         def fn(bc):
             return u"%s (%s)" % (bc.value, unicode(bc))
         return lazy(fn, unicode)(bc)
     return lazy(unicode, unicode)(bc)
示例#17
0
    def display_text(cls, bc):
        """Override this to customize the display text of choices.
        :class:`lino.modlib.users.choicelists.UserGroups` and
        :class:`lino.modlib.cv.models.CefLevel` used to do this before
        we had the :attr:`ChoiceList.show_values` option.

        """
        if cls.show_values or True:
            def fn(bc):
                # return "%s (%s)" % (bc.value, str(bc))
                return "{0} ({1})".format(bc.value, bc)
            return lazy(fn, bytes)(bc)
        return lazy(bytes, bytes)(bc)
示例#18
0
    def test_lazy(self):
        from django.utils import functional
        from django.utils.encoding import force_text

        lazy_unicode = functional.lazy(lambda: u'abc', unicode)()
        lazy_string = functional.lazy(lambda: 'abc', str)()

        self.assertEqual(force_text(lazy_unicode), 'abc')
        self.assertEqual(force_text(lazy_string), 'abc')
        self.assertEqual(unicode(lazy_unicode), 'abc')
        self.assertEqual(unicode(lazy_string), 'abc')
        self.assertEqual(str(lazy_unicode), 'abc')
        self.assertEqual(str(lazy_string), 'abc')
示例#19
0
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:
            key = force_bytes(get_random_string(16))
            aes = AES.new(key)
            pad_length = 16 - (len(token) % 16 or 16)
            padding = ''.join('#' for _ in range(pad_length))
            value = base64.b64encode(
                aes.encrypt('{0}{1}'.format(token, padding))
            )
            token = '$'.join((force_text(key), force_text(value)))
            return force_text(token)
    _get_val = lazy(_get_val, text_type)

    return {'csrf_token': _get_val()}
示例#20
0
def register_recent_contests(request):
    if not hasattr(request, 'contest') or not hasattr(request, 'session'):
        return {}

    def generator():
        return recent_contests(request)
    return {'recent_contests': lazy(generator, list)()}
示例#21
0
    def test_basic(self):
        from django.utils.functional import lazy

        obj = lazy(lambda: 'bar', six.text_type)()
        res = transform(obj)
        expected = "'bar'" if six.PY3 else "u'bar'"
        self.assertEquals(res, expected)
示例#22
0
文件: forms.py 项目: mcr/ietfdb
 def __init__(self, *args, **kwargs):
     kwargs["max_length"] = 1000
     if not "help_text" in kwargs:
         kwargs["help_text"] = "Type in name to search for person"
     super(EmailsField, self).__init__(*args, **kwargs)
     self.widget.attrs["class"] = "tokenized-field"
     self.widget.attrs["data-ajax-url"] = lazy(urlreverse, str)("ajax_search_emails") # make this lazy to prevent initialization problem
示例#23
0
文件: utils.py 项目: fnp/wolnelektury
def likes(user, work, request=None):
    if not user.is_authenticated():
        return False

    if request is None:
        return work.tags.filter(category='set', user=user).exists()

    if not hasattr(request, 'social_likes'):
        # tuple: unchecked, checked, liked
        request.social_likes = defaultdict(lambda: (set(), set(), set()))

    ct = ContentType.objects.get_for_model(type(work))
    likes_t = request.social_likes[ct.pk]
    if work.pk in likes_t[1]:
        return work.pk in likes_t[2]
    else:
        likes_t[0].add(work.pk)

        def _likes():
            if likes_t[0]:
                ids = tuple(likes_t[0])
                likes_t[0].clear()
                likes_t[2].update(Tag.intermediary_table_model.objects.filter(
                    content_type_id=ct.pk, tag__user_id=user.pk,
                    object_id__in=ids
                ).distinct().values_list('object_id', flat=True))
                likes_t[1].update(ids)
            return work.pk in likes_t[2]
        return lazy(_likes, bool)()
示例#24
0
def dangling_problems_processor(request):
    if not getattr(request, 'contest', None):
        return {}
    if not is_contest_admin(request):
        return {}

    def generator():
        dangling_pis = ProblemInstance.objects.filter(contest=request.contest,
                round__isnull=True)
        count = dangling_pis.count()
        if not count:
            return ''
        elif count == 1:
            pi = dangling_pis.get()
            link = reverse('oioioiadmin:contests_probleminstance_change',
                        args=(pi.id,))
            if request.path == link:
                return ''
        else:
            link = reverse('oioioiadmin:contests_probleminstance_changelist')
        text = ungettext('%(count)d PROBLEM WITHOUT ROUND',
                '%(count)d PROBLEMS WITHOUT ROUNDS',
                count) % {'count': count}
        return make_navbar_badge(link, text)
    return {'extra_navbar_right_dangling_problems': lazy(generator, unicode)()}
示例#25
0
def auth(request):
    """Adds a new 'obj_perms' context variable.

    If there is no 'user' attribute in the request, uses AnonymousUser (from
    django.contrib.auth).
    """
    # If we access request.user, request.session is accessed, which results in
    # 'Vary: Cookie' being sent in every request that uses this context
    # processor, which can easily be every request on a site if
    # TEMPLATE_CONTEXT_PROCESSORS has this context processor added.  This kills
    # the ability to cache.  So, we carefully ensure these attributes are lazy.
    # We don't use django.utils.functional.lazy() for User, because that
    # requires knowing the class of the object we want to proxy, which could
    # break with custom auth backends.  LazyObject is a less complete but more
    # flexible solution that is a good enough wrapper for 'User'.
    def _get_user():
        user = None
        if hasattr(request, 'user'):
            user = request.user
        if not user:
            from django.contrib.auth.models import AnonymousUser
            user = AnonymousUser()
        return user

    return {
        'obj_perms': lazy(lambda: ObjPermWrapper(_get_user()), ObjPermWrapper)(),
    }
示例#26
0
def patch():
    global django_reverse
    # Will not patch twice.
    if urlresolvers.reverse is not reverse:
        django_reverse = urlresolvers.reverse
        urlresolvers.reverse = reverse
        urlresolvers.reverse_lazy = lazy(reverse, str)
示例#27
0
def navbar_tip_processor(request):
    if not getattr(request, 'contest', None):
        return {}
    if not request.user.is_authenticated():
        return {}
    def generator():
        is_admin = request.user.has_perm('contests.contest_admin',
                request.contest)
        messages = visible_messages(request)
        if is_admin:
            messages = messages.filter(message__isnull=True,
                    top_reference__isnull=True, kind='QUESTION')
        else:
            messages = new_messages(request, messages)
        count = messages.count()
        if count:
            text = ungettext('%(count)d NEW MESSAGE', '%(count)d NEW MESSAGES',
                    count) % {'count': count}
            if count == 1:
                message = messages.get()
                link = reverse('message', kwargs={
                        'contest_id': request.contest.id,
                        'message_id': message.top_reference_id or message.id
                    })
            else:
                link = reverse('contest_messages', kwargs={'contest_id':
                    request.contest.id})
            return make_navbar_badge(link, text)
        else:
            return ''
    return {'extra_navbar_right_messages': lazy(generator, unicode)()}
示例#28
0
 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)
示例#29
0
 def wrapper(*args, **kwargs):
     for arg in list(args) + list(six.itervalues(kwargs)):
         if isinstance(arg, Promise):
             break
     else:
         return func(*args, **kwargs)
     return lazy(func, six.text_type)(*args, **kwargs)
示例#30
0
    def test_basic(self):
        from django.utils.functional import lazy

        obj = lazy(lambda: 'bar', text_type)()
        res = transform(obj)
        expected = "'bar'" if not PY2 else "u'bar'"
        assert res == expected
示例#31
0
from django.conf.urls.defaults import *

from h1ds_configdb.views import HomeView

from django.utils.functional import lazy
from django.core.urlresolvers import reverse
from django.views.generic import RedirectView

# TODO: when update to django 1.4, use inbuilt reverse_lazy
reverse_lazy = lazy(reverse, str)

urlpatterns = patterns(
    '',
    url(r'^$',
        RedirectView.as_view(
            url=reverse_lazy("h1ds-configdb-filetypes",
                             kwargs={'filetype_str': 'all_filetypes'})),
        name="h1ds-configdb-homepage"),
    url(r'^(?P<filetype_str>[^/]+)/$',
        HomeView.as_view(),
        name="h1ds-configdb-filetypes"),
    url(r'^(?P<filetype_str>[^/]+)/(?P<filter_str>[^/]+)/$',
        HomeView.as_view(),
        name="h1ds-configdb-filtered"))
示例#32
0
 def test_charfield_get_choices_doesnt_evaluate_lazy_strings(self):
     # Regression test for #23098
     # Will raise ZeroDivisionError if lazy is evaluated
     lazy_func = lazy(lambda x: 0 / 0, int)
     f = models.CharField(choices=[(lazy_func('group'), (('a', 'A'), ('b', 'B')))])
     self.assertEqual(f.get_choices(True)[0], ('', '---------'))
示例#33
0
 def test_BigIntegerField(self):
     lazy_func = lazy(lambda: long(9999999999999999999), long)
     self.assertIsInstance(
         BigIntegerField().get_prep_value(lazy_func()),
         long)
示例#34
0
from django.utils.safestring import mark_safe
from django.urls import reverse
from collections import OrderedDict

from rdrf.forms.dynamic import fields
from rdrf.forms.widgets import widgets
import logging
from rdrf.forms.dynamic.calculated_fields import CalculatedFieldScriptCreator, CalculatedFieldScriptCreatorError
from rdrf.forms.dynamic.validation import ValidatorFactory
from rdrf.models.definition.models import CommonDataElement

from django.utils.functional import lazy
from django.utils.translation import ugettext_lazy as _
from django.conf import settings

mark_safe_lazy = lazy(mark_safe, str)

logger = logging.getLogger(__name__)


class FieldContext:
    """
    Where a field can appear - on a form or in a questionnaire
    On the questionnaire we use a different label text
    """
    CLINICAL_FORM = "Form"
    QUESTIONNAIRE = "Questionnaire"


class FieldFactory(object):
    # registry overrides
示例#35
0
 def test_BooleanField(self):
     lazy_func = lazy(lambda: True, bool)
     self.assertIsInstance(
         BooleanField().get_prep_value(lazy_func()),
         bool)
示例#36
0
 def test_DecimalField(self):
     lazy_func = lazy(lambda: Decimal('1.2'), Decimal)
     self.assertIsInstance(
         DecimalField().get_prep_value(lazy_func()),
         Decimal)
示例#37
0
class FormField(models.Model):
    form = models.ForeignKey(Form,
                             related_name='fields',
                             verbose_name=_('form'),
                             on_delete=models.CASCADE)
    ordering = models.IntegerField(_('ordering'), default=0)

    title = models.CharField(_('title'), max_length=100)
    name = models.CharField(_('name'), max_length=100)
    type = models.CharField(_('type'),
                            max_length=20,
                            choices=lazy(get_type_choices, list)())
    choices = models.CharField(_('choices'),
                               max_length=1024,
                               blank=True,
                               help_text=_('Comma-separated'))
    help_text = models.CharField(
        _('help text'),
        max_length=1024,
        blank=True,
        help_text=_('Optional extra explanatory text beside the field'))
    default_value = models.CharField(
        _('default value'),
        max_length=255,
        blank=True,
        help_text=_('Optional default value of the field'))
    is_required = models.BooleanField(_('is required'), default=True)

    class Meta:
        ordering = ['ordering', 'id']
        unique_together = (('form', 'name'), )
        verbose_name = _('form field')
        verbose_name_plural = _('form fields')

    def __str__(self):
        return self.title

    def clean(self):
        if self.choices and not isinstance(self.get_type(), forms.ChoiceField):
            raise forms.ValidationError(
                _("You can't specify choices for %s fields") % self.type)

    def get_choices(self):
        def get_tuple(value):
            return (slugify(value.strip()), value.strip())

        choices = [get_tuple(value) for value in self.choices.split(',')]
        if not self.is_required and self.type == 'select':
            choices = BLANK_CHOICE_DASH + choices
        return tuple(choices)

    def get_type(self, **kwargs):
        types = dict((r[0], r[2]) for r in FIELD_TYPES)
        return types[self.type](**kwargs)

    def add_formfield(self, fields, form):
        fields[slugify(self.name)] = self.formfield()

    def formfield(self):
        kwargs = dict(
            label=self.title,
            required=self.is_required,
            initial=self.default_value,
        )
        if self.choices:
            kwargs['choices'] = self.get_choices()
        if self.help_text:
            kwargs['help_text'] = self.help_text
        return self.get_type(**kwargs)
示例#38
0
def test_comparison_with_lazy():
    x = Translation(localized_string='xxx')
    lazy_u = lazy(lambda x: x, unicode)
    x == lazy_u('xxx')
    lazy_u('xxx') == x
示例#39
0
def get_langs():
    return DEV_LANGUAGES if DEV else PROD_LANGUAGES


LANGUAGE_URL_MAP = dict([(i.lower(), i) for i in get_langs()])


def lazy_langs():
    from product_details import product_details

    return [(lang.lower(), product_details.languages[lang]['native'])
            for lang in get_langs() if lang in product_details.languages]


LANGUAGES = lazy(lazy_langs, list)()

# Not all URLs need locale.
SUPPORTED_NONLOCALES = [
    'media', 'static', 'admin', 'csp', 'api', 'contribute.json', 'admin',
    'autocomplete', 'humans.txt'
]

# Email
SERVER_EMAIL = config('SERVER_EMAIL', default='*****@*****.**')
EMAIL_BACKEND = config(
    'EMAIL_BACKEND', default='django.core.mail.backends.console.EmailBackend')
FROM_NOREPLY = config('FROM_NOREPLY',
                      default='Mozillians.org <*****@*****.**>')
FROM_NOREPLY_VIA = config(
    'FROM_NOREPLY_VIA',
示例#40
0
 def test_ImageField(self):
     lazy_func = lazy(lambda: 'filename.ext', six.text_type)
     self.assertIsInstance(
         ImageField().get_prep_value(lazy_func()),
         six.text_type)
示例#41
0
 def test_FloatField(self):
     lazy_func = lazy(lambda: 1.2, float)
     self.assertIsInstance(
         FloatField().get_prep_value(lazy_func()),
         float)
示例#42
0
 def test_EmailField(self):
     lazy_func = lazy(lambda: '*****@*****.**', six.text_type)
     self.assertIsInstance(
         EmailField().get_prep_value(lazy_func()),
         six.text_type)
示例#43
0
    if val is None:
        if format_type not in FORMAT_SETTINGS:
            return format_type
        val = getattr(settings, format_type)
    elif format_type in ISO_INPUT_FORMATS.keys():
        # If a list of input formats from one of the format_modules was
        # retrieved, make sure the ISO_INPUT_FORMATS are in this list.
        val = list(val)
        for iso_input in ISO_INPUT_FORMATS.get(format_type, ()):
            if iso_input not in val:
                val.append(iso_input)
    _format_cache[cache_key] = val
    return val


get_format_lazy = lazy(get_format, six.text_type, list, tuple)


def date_format(value, format=None, use_l10n=None):
    """
    Formats a datetime.date or datetime.datetime object using a
    localizable format

    If use_l10n is provided and is not None, that will force the value to
    be localized (or not), overriding the value of settings.USE_L10N.
    """
    return dateformat.format(
        value, get_format(format or 'DATE_FORMAT', use_l10n=use_l10n))


def time_format(value, format=None, use_l10n=None):
示例#44
0
 def test_DateTimeField(self):
     lazy_func = lazy(lambda: datetime.datetime.now(), datetime.datetime)
     self.assertIsInstance(
         DateTimeField().get_prep_value(lazy_func()),
         datetime.datetime)
示例#45
0
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from enumfields import Enum, EnumIntegerField

from shuup.core.excs import (ProductNotOrderableProblem,
                             ProductNotVisibleProblem)
from shuup.core.fields import MoneyValueField, QuantityField, UnsavedForeignKey
from shuup.core.signals import get_orderability_errors, get_visibility_errors
from shuup.core.utils import context_cache
from shuup.utils.analog import define_log_model
from shuup.utils.properties import MoneyPropped, PriceProperty

from ._product_media import ProductMediaKind
from ._products import ProductMode, ProductVisibility, StockBehavior

mark_safe_lazy = lazy(mark_safe, six.text_type)


class ShopProductVisibility(Enum):
    NOT_VISIBLE = 0
    SEARCHABLE = 1
    LISTED = 2
    ALWAYS_VISIBLE = 3

    class Labels:
        NOT_VISIBLE = _("not visible")
        SEARCHABLE = _("searchable")
        LISTED = _("listed")
        ALWAYS_VISIBLE = _("always visible")

示例#46
0
 def widget_attrs(self, widget):
     lazy_reverse = lazy(reverse, str)
     return {
         'class': 'email-autocomplete',
         'data-src': lazy_reverse('users.ajax')
     }
from django.utils.functional import lazy

from modeltranslation.settings import *


def get_language():
    """
    Return an active language code that is guaranteed to be in
    settings.LANGUAGES (Django does not seem to guarantee this for us).
    """
    lang = _get_language()
    if lang not in AVAILABLE_LANGUAGES and '-' in lang:
        lang = lang.split('-')[0]
    if lang in AVAILABLE_LANGUAGES:
        return lang
    return DEFAULT_LANGUAGE


def get_translation_fields(field):
    """Returns a list of localized fieldnames for a given field."""
    return [build_localized_fieldname(field, l) for l in AVAILABLE_LANGUAGES]


def build_localized_fieldname(field_name, lang):
    return str('%s_%s' % (field_name, lang.replace('-', '_')))


def _build_localized_verbose_name(verbose_name, lang):
    return u'%s [%s]' % (verbose_name, LANGUAGE_VERBOSE_NAMES.get(lang, lang))
build_localized_verbose_name = lazy(_build_localized_verbose_name, unicode)
示例#48
0
 def test_BinaryField(self):
     lazy_func = lazy(lambda: b'', bytes)
     self.assertIsInstance(
         BinaryField().get_prep_value(lazy_func()),
         bytes)
示例#49
0
    for validator in password_validators:
        help_texts.append(validator.get_help_text())
    return help_texts


def _password_validators_help_text_html(password_validators=None):
    """
    Return an HTML string with all help texts of all configured validators
    in an <ul>.
    """
    help_texts = password_validators_help_texts(password_validators)
    help_items = [format_html('<li>{}</li>', help_text) for help_text in help_texts]
    return '<ul>%s</ul>' % ''.join(help_items) if help_items else ''


password_validators_help_text_html = lazy(_password_validators_help_text_html, text_type)


class MinimumLengthValidator(object):
    """
    Validate whether the password is of a minimum length.
    """
    def __init__(self, min_length=8):
        self.min_length = min_length

    def validate(self, password, user=None):
        if len(password) < self.min_length:
            raise ValidationError(
                ungettext(
                    "This password is too short. It must contain at least %(min_length)d character.",
                    "This password is too short. It must contain at least %(min_length)d characters.",
示例#50
0
           'NestedGenericStackedInlineMixin',
           'NestedGenericTabularInlineMixin',
           'NestedGenericInlineModelAdminMixin',
           'NestedInlineAdminFormsetMixin')


def get_method_function(fn):
    return fn.im_func if six.PY2 else fn


def get_model_id(model_cls):
    opts = model_cls._meta
    return "%s-%s" % (opts.app_label, opts.model_name)


lazy_reverse = lazy(reverse, str)
server_data_js_url = lazy_reverse('nesting_server_data')


class NestedAdminMixin(object):
    @property
    def _djn_js_deps(self):
        """
        Returns a set of js files that, if present, ought to precede
        nested_admin.js in the media load order
        """
        extra = '' if settings.DEBUG else '.min'

        return {
            'admin/js/core.js',
            'admin/js/vendor/jquery/jquery%s.js' % extra,
示例#51
0
        except NoReverseMatch:
            # In case the versioning scheme reversal fails, fallback to the
            # default implementation
            url = _reverse(viewname, args, kwargs, request, format, **extra)
    else:
        url = _reverse(viewname, args, kwargs, request, format, **extra)

    return preserve_builtin_query_params(url, request)


def _reverse(viewname,
             args=None,
             kwargs=None,
             request=None,
             format=None,
             **extra):
    """
    Same as `django.urls.reverse`, but optionally takes a request
    and returns a fully qualified URL, using the request to get the base URL.
    """
    if format is not None:
        kwargs = kwargs or {}
        kwargs['format'] = format
    url = django_reverse(viewname, args=args, kwargs=kwargs, **extra)
    if request:
        return request.build_absolute_uri(url)
    return url


reverse_lazy = lazy(reverse, six.text_type)
示例#52
0
from oslo_utils import units

from django.conf import settings
from django.contrib.auth import logout
from django import http
from django.utils.encoding import force_text
from django.utils.functional import lazy
from django.utils import translation


def _lazy_join(separator, strings):
    return separator.join([force_text(s) for s in strings])


lazy_join = lazy(_lazy_join, str)


def bytes_to_gigabytes(bytes):
    # Converts the number of bytes to the next highest number of Gigabytes
    # For example 5000000 (5 Meg) would return '1'
    return int(math.ceil(float(bytes) / units.Gi))


def add_logout_reason(request, response, reason, status='success'):
    # Store the translated string in the cookie
    lang = translation.get_language_from_request(request)
    with translation.override(lang):
        reason = force_text(reason).encode('unicode_escape').decode('ascii')
        response.set_cookie('logout_reason', reason, max_age=10)
        response.set_cookie('logout_status', status, max_age=10)
示例#53
0
文件: forms.py 项目: yward/appstore
class IntegrationScaffoldingForm(Form):
    name = CharField(max_length=80,
                     label=_('Integration name'),
                     widget=TextInput())
    author_homepage = URLField(label=_('Author\'s homepage'), required=False)
    issue_tracker = URLField(label=_('Issue tracker URL'),
                             required=False,
                             help_text=_('Bug reports and feature requests'))
    categories = MultipleChoiceField(widget=HiddenInput(),
                                     disabled=True,
                                     required=True,
                                     label=_('Categories'),
                                     choices=lazy(get_categories, list),
                                     help_text=_('Hold down Ctrl and click to '
                                                 'select multiple entries'))
    summary = CharField(
        max_length=256,
        label=_('Summary'),
        help_text=
        _('Short description of your app that will be rendered as short teaser'
          ))
    screenshot = URLField(max_length=256,
                          label=_('Screenshot URL'),
                          required=False,
                          help_text=_('URL for integration screenshot'))
    screenshot_thumbnail = URLField(max_length=256,
                                    label=_('Screenshot '
                                            'thumbnail URL'),
                                    required=False,
                                    help_text=_('URL for integration '
                                                'screenshot in '
                                                'smaller dimensions. '
                                                'Must be used in combination '
                                                'with a larger screenshot.'))
    description = CharField(widget=Textarea,
                            label=_('Description'),
                            help_text=_('Full description of what your'
                                        ' integration '
                                        'does. Can contain Markdown.'))

    def _create_discourse_category(self, app_id: str) -> None:
        url = '%s/categories?api_key=%s&api_username=%s' % (
            settings.DISCOURSE_URL.rstrip('/'), settings.DISCOURSE_TOKEN,
            settings.DISCOURSE_USER)
        data = {
            'name': app_id.replace('_', '-'),
            'color': '3c3945',
            'text_color': 'ffffff'
        }
        if settings.DISCOURSE_PARENT_CATEGORY_ID:
            data['parent_category_id'] = settings.DISCOURSE_PARENT_CATEGORY_ID

        # ignore requests errors because there can be many issues and we do not
        # want to abort app registration just because the forum is down or
        # leak sensitive data like tokens or users
        try:
            requests.post(url, data=data)
        except requests.HTTPError:
            pass

    def save(self, user, app_id, action):
        if app_id is None:
            app_id = slugify(self.cleaned_data['name']).replace('-', '_')[:80]
        try:
            app = App.objects.get(id=app_id)
            if app.can_update(user) or user.is_superuser:
                if action == "reject" and user.is_superuser:
                    '''Not optimal but works'''
                    Screenshot.objects.filter(app=app).delete()
                    app.delete()
                elif action == "approve" and user.is_superuser:
                    app.approved = True
                    if settings.DISCOURSE_TOKEN:
                        self._create_discourse_category(app_id)
                    app.save()
                    return app_id
                else:
                    '''Not optimal but works'''
                    Screenshot.objects.filter(app=app).delete()
                    if self.data['screenshot']:
                        screenshot = Screenshot.objects.create(
                            url=self.cleaned_data['screenshot'],
                            small_thumbnail=self.
                            cleaned_data['screenshot_thumbnail'],
                            ordering=1,
                            app=app)
                        screenshot.save()

                    app.description = self.cleaned_data['description']
                    app.name = self.cleaned_data['name']
                    app.summary = self.cleaned_data['summary']
                    app.website = self.cleaned_data['author_homepage']
                    app.issue_tracker = self.cleaned_data['issue_tracker']
                    app.save()
                    return app_id
        except App.DoesNotExist:
            app = App.objects.create(id=app_id,
                                     owner=user,
                                     certificate=uuid.uuid1().urn)
            app.set_current_language('en')
            app.categories.set(self.cleaned_data['categories'])
            app.description = self.cleaned_data['description']
            app.name = self.cleaned_data['name']
            app.summary = self.cleaned_data['summary']
            app.website = self.cleaned_data['author_homepage']
            app.issue_tracker = self.cleaned_data['issue_tracker']
            app.save()
            p = App.objects.get(id=app_id)
            p.is_integration = True
            if user.is_superuser:
                p.approved = True
                if settings.DISCOURSE_TOKEN:
                    self._create_discourse_category(app_id)
            else:
                send_mail(
                    "New integration submitted", "Please review the "
                    "integration to make "
                    "sure it fits the "
                    "guidelines.", settings.NEXTCLOUD_FROM_EMAIL,
                    settings.NEXTCLOUD_INTEGRATIONS_APPROVAL_EMAILS)
            p.save()
            if self.data['screenshot']:
                screenshot = Screenshot.objects.create(
                    url=self.cleaned_data['screenshot'],
                    small_thumbnail=self.cleaned_data['screenshot_thumbnail'],
                    ordering=1,
                    app=p)
                screenshot.save()
            if not p.is_integration or p.approved or user.is_superuser:
                return app_id
示例#54
0
    # In order to be able to use ALLOWED_HOSTS to validate URLs, we need to
    # have a version of the host that contains the port. This only applies
    # to local development (usually the host is localhost:8000).
    if ":" in host:
        host_no_port = host.rsplit(":", 1)[0]
        result = [host, host_no_port]

    # add values from environment variable. Needed in case of URL/domain redirections
    env_vars_str = os.getenv("ALLOWED_HOSTS", "127.0.0.1:8000")
    env_vars = [x.strip() for x in env_vars_str.split(",")]
    result.extend(env_vars)

    return result


ALLOWED_HOSTS = lazy(_allowed_hosts, list)()

# Auth
# The first hasher in this list will be used for new passwords.
# Any other hasher in the list can be used for existing passwords.
PASSWORD_HASHERS = (
    "django.contrib.auth.hashers.PBKDF2PasswordHasher",
    "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher",
    "django.contrib.auth.hashers.BCryptSHA256PasswordHasher",
    "django.contrib.auth.hashers.BCryptPasswordHasher",
    "django.contrib.auth.hashers.SHA1PasswordHasher",
    "django.contrib.auth.hashers.MD5PasswordHasher",
    "django.contrib.auth.hashers.UnsaltedMD5PasswordHasher",
)

# Logging
示例#55
0
    Remove characters that aren't alphanumerics, underscores, or hyphens.
    Convert to lowercase. Also strip leading and trailing whitespace.
    """
    value = str(value)
    if allow_unicode:
        value = unicodedata.normalize('NFKC', value)
    else:
        value = unicodedata.normalize('NFKD',
                                      value).encode('ascii',
                                                    'ignore').decode('ascii')
    value = re.sub(r'[^\w\s-]', '', value).strip().lower()
    return re.sub(r'[-\s]+', '-', value)


def camel_case_to_spaces(value):
    """
    Split CamelCase and convert to lowercase. Strip surrounding whitespace.
    """
    return re_camel_case.sub(r' \1', value).strip().lower()


def _format_lazy(format_string, *args, **kwargs):
    """
    Apply str.format() on 'format_string' where format_string, args,
    and/or kwargs might be lazy.
    """
    return format_string.format(*args, **kwargs)


format_lazy = lazy(_format_lazy, str)
示例#56
0
 def test_AutoField(self):
     lazy_func = lazy(lambda: 1, int)
     self.assertIsInstance(
         AutoField(primary_key=True).get_prep_value(lazy_func()),
         int)
示例#57
0
def ngettext(singular, plural, number):
    return _trans.ngettext(singular, plural, number)

def ugettext(message):
    return _trans.ugettext(message)

def ungettext(singular, plural, number):
    return _trans.ungettext(singular, plural, number)

def pgettext(context, message):
    return _trans.pgettext(context, message)

def npgettext(context, singular, plural, number):
    return _trans.npgettext(context, singular, plural, number)

ngettext_lazy = lazy(ngettext, str)
gettext_lazy = lazy(gettext, str)
ungettext_lazy = lazy(ungettext, unicode)
ugettext_lazy = lazy(ugettext, unicode)
pgettext_lazy = lazy(pgettext, unicode)
npgettext_lazy = lazy(npgettext, unicode)

def activate(language):
    return _trans.activate(language)

def deactivate():
    return _trans.deactivate()

def get_language():
    return _trans.get_language()
示例#58
0
 def __init__(self, *args, **kwargs):
     """We need to override this to make the choices lazy and prevent import madness"""
     super(PermissionsMixin, self).__init__(*args, **kwargs)
     self._meta.get_field('user_permissions')._choices = lazy(get_permission_choices, list)()
示例#59
0
 def test_IntegerField(self):
     lazy_func = lazy(lambda: 1, int)
     self.assertIsInstance(
         IntegerField().get_prep_value(lazy_func()),
         int)
示例#60
0
import logging

logger = logging.getLogger(__name__)


class TranslationDoesNotExist(AttributeError):
    """
    A tagging interface to detect missing translations.
    The exception inherits from :class:`AttributeError` to reflect what is actually happening.
    It also causes the templates to handle the missing attributes silently, which is very useful in the admin for example.
    """
    pass


_lazy_verbose_name = lazy(
    lambda x: ugettext("{0} Translation").format(x._meta.verbose_name),
    unicode)


def create_translations_model(shared_model, related_name, meta, **fields):
    """
    Dynamically create the translations model.
    Create the translations model for the shared model 'model'.

    :param related_name: The related name for the reverse FK from the translations model.
    :param meta: A (optional) dictionary of attributes for the translations model's inner Meta class.
    :param fields: A dictionary of fields to put on the translations model.

    Two fields are enforced on the translations model:

        language_code: A 15 char, db indexed field.