python类override()的实例源码

test_models.py 文件源码 项目:django-modeltrans 作者: zostera 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test_get_has_no_translation(self):
        m = Blog(title='Falcon', i18n={
            'title_nl': 'Valk',
            'title_de': 'Falk'
        })

        # Fallback to base langauge
        with override('fr'):
            self.assertEquals(m.title_i18n, 'Falcon')

        # other translations are still there.
        self.assertEquals(m.title_nl, 'Valk')
        self.assertEquals(m.title_de, 'Falk')
test_models.py 文件源码 项目:django-modeltrans 作者: zostera 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def test_set_translatable_field_active_language(self):
        m = Blog.objects.create(title='Toad')

        with override('nl'):
            m.title_i18n = 'Pad'
        m.save()

        self.assertEquals(Blog.objects.get(title='Toad').title_nl, 'Pad')
test_models.py 文件源码 项目:django-modeltrans 作者: zostera 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_fallback_getting_TextField(self):
        DESCRIPTION = 'Story about Falcon'
        m = TextModel(title='Falcon', description_en=DESCRIPTION)
        with override('fr'):
            self.assertEquals(m.description_i18n, DESCRIPTION)

        m = NullableTextModel.objects.create(description=DESCRIPTION, description_fr='')
        with override('fr'):
            self.assertEquals(m.description_i18n, DESCRIPTION)
test_models.py 文件源码 项目:django-modeltrans 作者: zostera 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_creationg_prevents_double_definition(self):
        expected_message = (
            'Attempted override of "title" with "title_en". Only '
            'one of the two is allowed.'
        )
        with self.assertRaisesMessage(ValueError, expected_message):
            Blog.objects.create(
                title='Foo',
                title_en='Bar'
            )
test_models.py 文件源码 项目:django-modeltrans 作者: zostera 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_fallback_chain(self):
        '''
        Testing the fallback chain setting for model
        '''
        b = Blog.objects.create(title='Buzzard', i18n={
            'title_fy': 'Mûzefalk',
            'title_nl': 'Buizerd',
            'title_fr': 'Buse'
        })

        with override('nl'):
            self.assertEquals(b.title_i18n, 'Buizerd')
        with override('fr'):
            self.assertEquals(b.title_i18n, 'Buse')
        with override('fy'):
            self.assertEquals(b.title_i18n, 'Mûzefalk')

        b = Blog.objects.create(title='Buzzard', i18n={
            'title_nl': 'Buizerd',
            'title_fr': 'Buse'
        })
        with override('fy'):
            self.assertEquals(b.title_i18n, 'Buizerd')

        b = Blog.objects.create(title='Buzzard', i18n={
            'title_fr': 'Buse'
        })
        with override('fy'):
            self.assertEquals(b.title_i18n, 'Buzzard')
        with override('fr'):
            self.assertEquals(b.title_i18n, 'Buse')
test_querysets.py 文件源码 项目:django-modeltrans 作者: zostera 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def test_filter_i18n(self):
        Blog.objects.create(title='Cod')

        with override('nl'):
            # should fallback to english
            qs = Blog.objects.filter(title_i18n='Cod')
            self.assertEquals({m.title for m in qs}, {'Cod'})

            # should not fallback
            qs = Blog.objects.filter(title_nl='Cod')
            self.assertEquals({m.title for m in qs}, set())
test_querysets.py 文件源码 项目:django-modeltrans 作者: zostera 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def test_filter_Q_object(self):
        b = Blog.objects.get(Q(title_nl__contains='al'))
        self.assertEquals(b.title, 'Falcon')

        qs = Blog.objects.filter(Q(title_nl__contains='al') | Q(title_en__contains='Fro'))
        self.assertEquals({m.title for m in qs}, {'Falcon', 'Frog'})

        b = Blog.objects.get(Q(title_nl__contains='al'), Q(title_en__contains='al'))
        self.assertEquals(b.title, 'Falcon')

        with override('nl'):
            b = Blog.objects.get(Q(title_i18n='Kikker'))
            self.assertEquals(b.title, 'Frog')
test_querysets.py 文件源码 项目:django-modeltrans 作者: zostera 项目源码 文件源码 阅读 15 收藏 0 点赞 0 评论 0
def test_order_by_i18n(self):
        Blog.objects.create(title='H')
        with override('nl'):
            qs = Blog.objects.all().order_by('title_i18n')

            self.assertEquals(key(qs, 'title_i18n'), 'A B C D H X Y Z'.split())
test_querysets.py 文件源码 项目:django-modeltrans 作者: zostera 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_annotate_upper(self):
        with override('nl'):
            qs = Blog.objects.annotate(e=models.functions.Upper('title_i18n'))

            self.assertEquals(
                list(qs.values_list('e', flat=True)),
                ['VALK', 'VULTURE', 'BAT', 'DOLFIN', 'ZEBRA']
            )
test_querysets.py 文件源码 项目:django-modeltrans 作者: zostera 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def test_annotate_length(self):
        with override('nl'):
            qs = Blog.objects.annotate(l=models.functions.Length('title_i18n'))

            self.assertEquals(
                list(qs.values_list('l', flat=True)),
                list(map(len, ['VALK', 'VULTURE', 'BAT', 'DOLFIN', 'ZEBRA']))
            )
test_querysets.py 文件源码 项目:django-modeltrans 作者: zostera 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def test_order_by_lower(self):
        from django.db.models.functions import Lower

        c = Category.objects.create(name='test')
        Blog.objects.create(title='A', title_nl='c', category=c)
        Blog.objects.create(title='a', title_nl='b', category=c)

        filtered = Blog.objects.filter(category=c)

        # order by title should result in aA because it is case sensitive.
        qs = filtered.order_by('title', 'title_nl')
        self.assertEquals(key(qs, 'title'), ['a', 'A'])

        # order by Lower('title') should result in Aa because lower('A') == lower('A')
        # so the title_nl field should determine the sorting
        qs = filtered.order_by(Lower('title'), 'title_nl')
        self.assertEquals(key(qs, 'title'), ['a', 'A'])

        # applying lower to title_nl should not matter since it is not the same letter
        qs = filtered.order_by(Lower('title_nl'))
        self.assertEquals(key(qs, 'title'), ['a', 'A'])

        # should be the same as previous
        with override('nl'):
            qs = filtered.order_by(Lower('title_i18n'))
            self.assertEquals(key(qs, 'title'), ['a', 'A'])
test_querysets.py 文件源码 项目:django-modeltrans 作者: zostera 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def test_order_by_fallback_chain(self):

        class TestObj(models.Model):
            title = models.CharField(max_length=100)
            i18n = TranslationField(fields=('title', ))

            class Meta:
                app_label = 'django-modeltrans_tests'

        translate_model(TestObj)

        with CreateTestModel(TestObj):
            TestObj.objects.bulk_create([
                TestObj(title='Falcon', title_nl='Valk'),
                TestObj(title='Frog', title_nl='Kikker', title_fr='Grenouilles', title_fy='Frosk'),
                TestObj(title='Fox', title_nl='Vos', title_fy='Foks'),
                TestObj(title='Gecko'),
                TestObj(title='Gerbil'),
                TestObj(title='Vulture', title_nl='Gier', title_fr='Vautour')
            ])

            # should use the 'default' fallback chain
            with override('nl'):
                qs = TestObj.objects.all().order_by('title_i18n')
                self.assertEquals(key(qs, 'title_i18n'), ['Gecko', 'Gerbil', 'Gier', 'Kikker', 'Valk', 'Vos'])

            # should use the 'fy' fallback chain
            with override('fy'):
                expected = ['Foks', 'Frosk', 'Gecko', 'Gerbil', 'Gier', 'Valk']
                qs = TestObj.objects.all().order_by('title_i18n')
                self.assertEquals(key(qs, 'title_i18n'), expected)

                expected.reverse()
                qs = TestObj.objects.all().order_by('-title_i18n')
                self.assertEquals(key(qs, 'title_i18n'), expected)

            # should use the 'default' fallback chain
            with override('fr'):
                qs = TestObj.objects.all().order_by('title_i18n')
                self.assertEquals(key(qs, 'title_i18n'), ['Falcon', 'Fox', 'Gecko', 'Gerbil', 'Grenouilles', 'Vautour'])
test_querysets.py 文件源码 项目:django-modeltrans 作者: zostera 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def test_queryset_values_i18n(self):
        with override('nl'):
            self.assertEqualsList(
                Blog.objects.all().order_by('title_i18n').values('title_i18n'),
                [{'title_i18n': 'Gecko'}, {'title_i18n': 'Kikker'}, {'title_i18n': 'Valk'}]
            )
views.py 文件源码 项目:django-open-volunteering-platform 作者: OpenVolunteeringPlatform 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def startup(request):
  """ This view provides initial data to the client, such as available skills and causes """
  with translation.override(translation.get_language_from_request(request)):
    skills = serializers.SkillSerializer(models.Skill.objects.filter(channel__slug=request.channel), many=True)
    causes = serializers.FullCauseSerializer(models.Cause.objects.filter(channel__slug=request.channel), many=True, context={'request': request})

    return response.Response({
      "skills": skills.data,
      "causes": causes.data
    })
test_views.py 文件源码 项目:django-open-volunteering-platform 作者: OpenVolunteeringPlatform 项目源码 文件源码 阅读 15 收藏 0 点赞 0 评论 0
def test_returns_localized_startup_data(self):
    """ Test startup route returns skills and causes """
    client = APIClient(HTTP_ACCEPT_LANGUAGE="pt-br")
    response = client.get(reverse("startup"), format="json")

    with translation.override('pt-br'):
      skills_data = serializers.SkillSerializer(models.Skill.objects.all(), many=True).data
      causes_data = serializers.FullCauseSerializer(models.Cause.objects.all(), many=True).data
      self.assertTrue(response.status_code == 200)
      self.assertTrue(response.data["skills"] == skills_data)
      self.assertTrue(response.data["causes"] == causes_data)
schedule.py 文件源码 项目:pretalx 作者: pretalx 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def notify_speakers(self):
        tz = pytz.timezone(self.event.timezone)
        speakers = defaultdict(lambda: {'create': [], 'update': []})
        if self.changes['action'] == 'create':
            speakers = {
                speaker: {'create': self.talks.filter(submission__speakers=speaker), 'update': []}
                for speaker in User.objects.filter(submissions__slots__schedule=self)
            }
        else:
            if self.changes['count'] == len(self.changes['canceled_talks']):
                return

            for new_talk in self.changes['new_talks']:
                for speaker in new_talk.submission.speakers.all():
                    speakers[speaker]['create'].append(new_talk)
            for moved_talk in self.changes['moved_talks']:
                for speaker in moved_talk['submission'].speakers.all():
                    speakers[speaker]['update'].append(moved_talk)
        for speaker in speakers:
            with override(speaker.locale), tzoverride(tz):
                text = get_template('schedule/speaker_notification.txt').render(
                    {'speaker': speaker, **speakers[speaker]}
                )
            QueuedMail.objects.create(
                event=self.event,
                to=speaker.email,
                reply_to=self.event.email,
                subject=_('[{event}] New schedule!').format(event=self.event.slug),
                text=text
            )
submission.py 文件源码 项目:pretalx 作者: pretalx 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def create_user_as_orga(email, submission=None):
    if not email:
        return

    nick = email.split('@')[0].lower()
    while User.objects.filter(nick__iexact=nick).exists():
        nick += random.choice([
            '_1', '_2', '_11', '_42', '_the_first', '_the_third',
            '_speaker', '_third_of_their_name', '_', '123', nick
        ])

    user = User.objects.create_user(
        nick=nick,
        password=get_random_string(32),
        email=email.lower(),
        pw_reset_token=get_random_string(32),
        pw_reset_time=now() + timedelta(days=7),
    )
    with override(submission.content_locale):
        invitation_link = build_absolute_uri('cfp:event.recover', kwargs={'event': submission.event.slug, 'token': user.pw_reset_token})
        invitation_text = _('''Hi!

You have been set as the speaker of a submission to the Call for Participation
of {event}, titled »{title}«. An account has been created for you – please follow
this link to set your account password.

{invitation_link}

Afterwards, you can edit your user profile and see the state of your submission.

The {event} orga crew''').format(event=submission.event.name, title=submission.title, invitation_link=invitation_link)
        QueuedMail.objects.create(
            event=submission.event,
            to=user.email,
            reply_to=submission.event.email,
            subject=str(_('You have been added to a submission for {event}').format(event=submission.event.name)),
            text=invitation_text,
        )
    return user
mail.py 文件源码 项目:pretalx 作者: pretalx 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def mail(user: User, subject: str, template: Union[str, LazyI18nString],
         context: Dict[str, Any]=None, event: Event=None, locale: str=None,
         headers: dict=None):
    from pretalx.mail.models import QueuedMail
    headers = headers or {}

    with override(locale):
        body = str(template)
        if context:
            body = body.format_map(TolerantDict(context))

        QueuedMail(
            event=event, to=user.email, subject=str(subject), text=body,
            reply_to=headers.get('reply-to'), bcc=headers.get('bcc'),
        ).send()
mails.py 文件源码 项目:rudi 作者: lexxodus 项目源码 文件源码 阅读 14 收藏 0 点赞 0 评论 0
def send_code(request, team):
    text_template = loader.get_template(
        "rudi/mails/code.txt")

    context = Context({
        "team": team,
        "link": request.build_absolute_uri(reverse(
            "rudi:confirm",
            args=(
                team.code,
            ),
        )),
    })
    subject = SUBJECT_CODE % (team.event.name, team.event.semester)
    if team.participant_2_email:
        recipients = [
            team.participant_1_email,
            team.participant_2_email
        ]
    else:
        recipients = [team.participant_1_email]
    with override(team.language):
        send_single(
            context,
            text_template,
            subject,
            team.event.advisor.email,
            recipients,
        )
options.py 文件源码 项目:lifesoundtrack 作者: MTG 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def verbose_name_raw(self):
        """
        There are a few places where the untranslated verbose name is needed
        (so that we get the same value regardless of currently active
        locale).
        """
        with override(None):
            return force_text(self.verbose_name)


问题


面经


文章

微信
公众号

扫码关注公众号