当前位置: 首页>>代码示例>>Python>>正文


Python safestring.SafeText方法代码示例

本文整理汇总了Python中django.utils.safestring.SafeText方法的典型用法代码示例。如果您正苦于以下问题:Python safestring.SafeText方法的具体用法?Python safestring.SafeText怎么用?Python safestring.SafeText使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.utils.safestring的用法示例。


在下文中一共展示了safestring.SafeText方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_all_markup_langs

# 需要导入模块: from django.utils import safestring [as 别名]
# 或者: from django.utils.safestring import SafeText [as 别名]
def test_all_markup_langs(self):
        """
        Make sure each markup option returns the same way.
        """
        correct = '<p>Paragraph <strong>1</strong> \u2605\U0001F600</p>'
        markup_samples = [
            ('creole', '''Paragraph **1** \u2605\U0001F600'''),
            ('markdown', '''Paragraph **1** \u2605\U0001F600'''),
            ('html', '''<p>Paragraph <strong>1</strong> \u2605\U0001F600'''),
            ('textile', '''Paragraph *1* \u2605\U0001F600'''),
        ]
        for lang, markup in markup_samples:
            result = markup_to_html(markup, lang)
            self.assertIsInstance(result, SafeText)
            self.assertEqual(result.strip(), correct)

        result = markup_to_html('Paragraph <1> \u2605\U0001F600', 'plain')
        self.assertIsInstance(result, SafeText)
        self.assertEqual(result.strip(), '<p>Paragraph &lt;1&gt; \u2605\U0001F600</p>') 
开发者ID:sfu-fas,项目名称:coursys,代码行数:21,代码来源:tests.py

示例2: adapt_datetime_with_timezone_support

# 需要导入模块: from django.utils import safestring [as 别名]
# 或者: from django.utils.safestring import SafeText [as 别名]
def adapt_datetime_with_timezone_support(value, conv):
    # Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL.
    if settings.USE_TZ:
        if timezone.is_naive(value):
            warnings.warn("MySQL received a naive datetime (%s)"
                          " while time zone support is active." % value,
                          RuntimeWarning)
            default_timezone = timezone.get_default_timezone()
            value = timezone.make_aware(value, default_timezone)
        value = value.astimezone(timezone.utc).replace(tzinfo=None)
    return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S.%f"), conv)

# MySQLdb-1.2.1 returns TIME columns as timedelta -- they are more like
# timedelta in terms of actual behavior as they are signed and include days --
# and Django expects time, so we still need to override that. We also need to
# add special handling for SafeText and SafeBytes as MySQLdb's type
# checking is too tight to catch those (see Django ticket #6052).
# Finally, MySQLdb always returns naive datetime objects. However, when
# timezone support is active, Django expects timezone-aware datetime objects. 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:21,代码来源:base.py

示例3: html_safe

# 需要导入模块: from django.utils import safestring [as 别名]
# 或者: from django.utils.safestring import SafeText [as 别名]
def html_safe(klass):
    """
    A decorator that defines the __html__ method. This helps non-Django
    templates to detect classes whose __str__ methods return SafeText.
    """
    if '__html__' in klass.__dict__:
        raise ValueError(
            "can't apply @html_safe to %s because it defines "
            "__html__()." % klass.__name__
        )
    if '__str__' not in klass.__dict__:
        raise ValueError(
            "can't apply @html_safe to %s because it doesn't "
            "define __str__()." % klass.__name__
        )
    klass_str = klass.__str__
    klass.__str__ = lambda self: mark_safe(klass_str(self))
    klass.__html__ = lambda self: str(self)
    return klass 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:21,代码来源:html.py

示例4: render

# 需要导入模块: from django.utils import safestring [as 别名]
# 或者: from django.utils.safestring import SafeText [as 别名]
def render(self, name: str, value, attrs=None, renderer=None):
        """
        name='project', value=None, attrs={'id': 'id_project'}
        <select name="project" id="id_project">
        """
        wig_id = attrs['id']
        html = self.build_master_change_script(wig_id)
        html += f'<select name="{name}" id="{wig_id}">\n'
        html += '    <option value="" selected>---------</option>\n'

        proj_set = [(p.pk, p.type.code, p.name, p.type_id) for p in self.choices.queryset.order_by('-pk')]

        for id, proj_type, proj_name, proj_type_pk in proj_set:
            val_str = f'{proj_name} ({proj_type}, #{id})'
            html += f'    <option value="{id}" data_type="{proj_type_pk}" >'
            html += f'{val_str}</option>\n'

        html += '</select>\n'
        html_safe = SafeText(html)
        return html_safe 
开发者ID:LexPredict,项目名称:lexpredict-contraxsuite,代码行数:22,代码来源:widgets.py

示例5: test_custom_render_form_template

# 需要导入模块: from django.utils import safestring [as 别名]
# 或者: from django.utils.safestring import SafeText [as 别名]
def test_custom_render_form_template(self):
        class LinkBlock(blocks.StructBlock):
            title = blocks.CharBlock(required=False)
            link = blocks.URLBlock(required=False)

            class Meta:
                form_template = 'tests/block_forms/struct_block_form_template.html'

        block = LinkBlock()
        html = block.render_form(block.to_python({
            'title': "Wagtail site",
            'link': 'http://www.wagtail.io',
        }), prefix='mylink')

        self.assertIn('<div>Hello</div>', html)
        self.assertHTMLEqual('<div>Hello</div>', html)
        self.assertTrue(isinstance(html, SafeText)) 
开发者ID:wagtail,项目名称:wagtail,代码行数:19,代码来源:test_blocks.py

示例6: test_custom_render_form_template_jinja

# 需要导入模块: from django.utils import safestring [as 别名]
# 或者: from django.utils.safestring import SafeText [as 别名]
def test_custom_render_form_template_jinja(self):
        class LinkBlock(blocks.StructBlock):
            title = blocks.CharBlock(required=False)
            link = blocks.URLBlock(required=False)

            class Meta:
                form_template = 'tests/jinja2/struct_block_form_template.html'

        block = LinkBlock()
        html = block.render_form(block.to_python({
            'title': "Wagtail site",
            'link': 'http://www.wagtail.io',
        }), prefix='mylink')

        self.assertIn('<div>Hello</div>', html)
        self.assertHTMLEqual('<div>Hello</div>', html)
        self.assertTrue(isinstance(html, SafeText)) 
开发者ID:wagtail,项目名称:wagtail,代码行数:19,代码来源:test_blocks.py

示例7: adapt_datetime_warn_on_aware_datetime

# 需要导入模块: from django.utils import safestring [as 别名]
# 或者: from django.utils.safestring import SafeText [as 别名]
def adapt_datetime_warn_on_aware_datetime(value, conv):
    # Remove this function and rely on the default adapter in Django 2.0.
    if settings.USE_TZ and timezone.is_aware(value):
        warnings.warn(
            "The MySQL database adapter received an aware datetime (%s), "
            "probably from cursor.execute(). Update your code to pass a "
            "naive datetime in the database connection's time zone (UTC by "
            "default).", RemovedInDjango20Warning)
        # This doesn't account for the database connection's timezone,
        # which isn't known. (That's why this adapter is deprecated.)
        value = value.astimezone(timezone.utc).replace(tzinfo=None)
    return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S.%f"), conv)


# MySQLdb returns TIME columns as timedelta -- they are more like timedelta in
# terms of actual behavior as they are signed and include days -- and Django
# expects time, so we still need to override that. We also need to add special
# handling for SafeText and SafeBytes as MySQLdb's type checking is too tight
# to catch those (see Django ticket #6052). 
开发者ID:Yeah-Kun,项目名称:python,代码行数:21,代码来源:base.py

示例8: render_field

# 需要导入模块: from django.utils import safestring [as 别名]
# 或者: from django.utils.safestring import SafeText [as 别名]
def render_field(field: Field, render_labels: bool = True) -> SafeText:
    """
    Renders a form field using a custom template designed specifically for the wiki forms.

    As the wiki uses custom form rendering logic, we were unable to make use of Crispy Forms for
    it. This means that, in order to customize the form fields, we needed to be able to render
    the fields manually. This function handles that logic.

    Sometimes we don't want to render the label that goes with a field - the `render_labels`
    argument defaults to True, but can be set to False if the label shouldn't be rendered.

    The label rendering logic is left up to the template.

    Usage: `{% render_field field_obj [render_labels=True/False] %}`
    """
    unbound_field = get_unbound_field(field)

    if not isinstance(render_labels, bool):
        render_labels = True

    template_path = TEMPLATES.get(unbound_field.__class__, TEMPLATE_PATH.format("in_place_render"))
    is_markitup = isinstance(unbound_field.widget, MarkItUpWidget)
    context = {"field": field, "is_markitup": is_markitup, "render_labels": render_labels}

    return render(template_path, context) 
开发者ID:python-discord,项目名称:site,代码行数:27,代码来源:wiki_extra.py

示例9: adapt_datetime_with_timezone_support

# 需要导入模块: from django.utils import safestring [as 别名]
# 或者: from django.utils.safestring import SafeText [as 别名]
def adapt_datetime_with_timezone_support(value, conv):
    # Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL.
    if settings.USE_TZ:
        if timezone.is_naive(value):
            warnings.warn("MySQL received a naive datetime (%s)"
                          " while time zone support is active." % value,
                          RuntimeWarning)
            default_timezone = timezone.get_default_timezone()
            value = timezone.make_aware(value, default_timezone)
        value = value.astimezone(timezone.utc).replace(tzinfo=None)
    return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S"), conv)

# MySQLdb-1.2.1 returns TIME columns as timedelta -- they are more like
# timedelta in terms of actual behavior as they are signed and include days --
# and Django expects time, so we still need to override that. We also need to
# add special handling for SafeText and SafeBytes as MySQLdb's type
# checking is too tight to catch those (see Django ticket #6052).
# Finally, MySQLdb always returns naive datetime objects. However, when
# timezone support is active, Django expects timezone-aware datetime objects. 
开发者ID:blackye,项目名称:luscan-devel,代码行数:21,代码来源:base.py

示例10: adapt_datetime_warn_on_aware_datetime

# 需要导入模块: from django.utils import safestring [as 别名]
# 或者: from django.utils.safestring import SafeText [as 别名]
def adapt_datetime_warn_on_aware_datetime(value, conv):
    # Remove this function and rely on the default adapter in Django 2.0.
    if settings.USE_TZ and timezone.is_aware(value):
        warnings.warn(
            "The MySQL database adapter received an aware datetime (%s), "
            "probably from cursor.execute(). Update your code to pass a "
            "naive datetime in the database connection's time zone (UTC by "
            "default).", RemovedInDjango20Warning)
        # This doesn't account for the database connection's timezone,
        # which isn't known. (That's why this adapter is deprecated.)
        value = value.astimezone(timezone.utc).replace(tzinfo=None)
    return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S.%f"), conv)

# MySQLdb-1.2.1 returns TIME columns as timedelta -- they are more like
# timedelta in terms of actual behavior as they are signed and include days --
# and Django expects time, so we still need to override that. We also need to
# add special handling for SafeText and SafeBytes as MySQLdb's type
# checking is too tight to catch those (see Django ticket #6052). 
开发者ID:drexly,项目名称:openhgsenti,代码行数:20,代码来源:base.py

示例11: test_safe_status

# 需要导入模块: from django.utils import safestring [as 别名]
# 或者: from django.utils.safestring import SafeText [as 别名]
def test_safe_status(self):
        """
        Translating a string requiring no auto-escaping with gettext or pgettext
        shouldn't change the "safe" status.
        """
        trans_real._active = local()
        trans_real._translations = {}
        s1 = mark_safe('Password')
        s2 = mark_safe('May')
        with translation.override('de', deactivate=True):
            self.assertIs(type(gettext(s1)), SafeText)
            self.assertIs(type(pgettext('month name', s2)), SafeText)
        self.assertEqual('aPassword', SafeText('a') + s1)
        self.assertEqual('Passworda', s1 + SafeText('a'))
        self.assertEqual('Passworda', s1 + mark_safe('a'))
        self.assertEqual('aPassword', mark_safe('a') + s1)
        self.assertEqual('as', mark_safe('a') + mark_safe('s')) 
开发者ID:nesdis,项目名称:djongo,代码行数:19,代码来源:tests.py

示例12: intro_html

# 需要导入模块: from django.utils import safestring [as 别名]
# 或者: from django.utils.safestring import SafeText [as 别名]
def intro_html(self) -> SafeText:
        return markup_to_html(self.intro, markuplang=self.markup, math=self.math) 
开发者ID:sfu-fas,项目名称:coursys,代码行数:4,代码来源:models.py

示例13: honour_code_html

# 需要导入模块: from django.utils import safestring [as 别名]
# 或者: from django.utils.safestring import SafeText [as 别名]
def honour_code_html(self) -> SafeText:
        return markup_to_html(self.honour_code_text, markuplang=self.honour_code_markup, math=self.honour_code_math) 
开发者ID:sfu-fas,项目名称:coursys,代码行数:4,代码来源:models.py

示例14: question_html

# 需要导入模块: from django.utils import safestring [as 别名]
# 或者: from django.utils.safestring import SafeText [as 别名]
def question_html(self) -> SafeText:
        """
        Markup for the question itself
        """
        helper = self.helper()
        return helper.question_html() 
开发者ID:sfu-fas,项目名称:coursys,代码行数:8,代码来源:models.py

示例15: question_preview_html

# 需要导入模块: from django.utils import safestring [as 别名]
# 或者: from django.utils.safestring import SafeText [as 别名]
def question_preview_html(self) -> SafeText:
        """
        Markup for an instructor's preview of the question (e.g. question + MC options)
        """
        helper = self.helper()
        return helper.question_preview_html() 
开发者ID:sfu-fas,项目名称:coursys,代码行数:8,代码来源:models.py


注:本文中的django.utils.safestring.SafeText方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。