本文整理汇总了Python中django.utils方法的典型用法代码示例。如果您正苦于以下问题:Python django.utils方法的具体用法?Python django.utils怎么用?Python django.utils使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django
的用法示例。
在下文中一共展示了django.utils方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _execute_wrapper
# 需要导入模块: import django [as 别名]
# 或者: from django import utils [as 别名]
def _execute_wrapper(self, method, query, args):
"""Wrapper around execute() and executemany()"""
try:
return method(query, args)
except (PyMysqlPool.mysql.connector.ProgrammingError) as err:
six.reraise(utils.ProgrammingError,
utils.ProgrammingError(err.msg), sys.exc_info()[2])
except (PyMysqlPool.mysql.connector.IntegrityError) as err:
six.reraise(utils.IntegrityError,
utils.IntegrityError(err.msg), sys.exc_info()[2])
except PyMysqlPool.mysql.connector.OperationalError as err:
# Map some error codes to IntegrityError, since they seem to be
# misclassified and Django would prefer the more logical place.
if err.args[0] in self.codes_for_integrityerror:
six.reraise(utils.IntegrityError,
utils.IntegrityError(err.msg), sys.exc_info()[2])
else:
six.reraise(utils.DatabaseError,
utils.DatabaseError(err.msg), sys.exc_info()[2])
except PyMysqlPool.mysql.connector.DatabaseError as err:
six.reraise(utils.DatabaseError,
utils.DatabaseError(err.msg), sys.exc_info()[2])
示例2: test_format_html
# 需要导入模块: import django [as 别名]
# 或者: from django import utils [as 别名]
def test_format_html(self):
"""
Test: format_html
url: https://github.com/django/django/blob/stable/1.8.x/tests/utils_tests/test_html.py#L44-L53
"""
from django.utils import html
from compat import format_html
self.assertEqual(
format_html("{0} {1} {third} {fourth}",
"< Dangerous >",
html.mark_safe("<b>safe</b>"),
third="< dangerous again",
fourth=html.mark_safe("<i>safe again</i>")
),
"< Dangerous > <b>safe</b> < dangerous again <i>safe again</i>"
)
示例3: _execute_wrapper
# 需要导入模块: import django [as 别名]
# 或者: from django import utils [as 别名]
def _execute_wrapper(self, method, query, args):
"""Wrapper around execute() and executemany()"""
try:
return method(query, args)
except (mysql.connector.ProgrammingError) as err:
six.reraise(utils.ProgrammingError,
utils.ProgrammingError(err.msg), sys.exc_info()[2])
except (mysql.connector.IntegrityError) as err:
six.reraise(utils.IntegrityError,
utils.IntegrityError(err.msg), sys.exc_info()[2])
except mysql.connector.OperationalError as err:
# Map some error codes to IntegrityError, since they seem to be
# misclassified and Django would prefer the more logical place.
if err.args[0] in self.codes_for_integrityerror:
six.reraise(utils.IntegrityError,
utils.IntegrityError(err.msg), sys.exc_info()[2])
else:
six.reraise(utils.DatabaseError,
utils.DatabaseError(err.msg), sys.exc_info()[2])
except mysql.connector.DatabaseError as err:
six.reraise(utils.DatabaseError,
utils.DatabaseError(err.msg), sys.exc_info()[2])
示例4: test_dates_with_aggregation
# 需要导入模块: import django [as 别名]
# 或者: from django import utils [as 别名]
def test_dates_with_aggregation(self):
"""
.dates() returns a distinct set of dates when applied to a
QuerySet with aggregation.
Refs #18056. Previously, .dates() would return distinct (date_kind,
aggregation) sets, in this case (year, num_authors), so 2008 would be
returned twice because there are books from 2008 with a different
number of authors.
"""
srv_ver = connection.get_server_version()
if (12, 0, 0, 0) <= srv_ver < (13, 0, 0, 0):
# this test fails on SQL server 2014
self.skipTest("TODO fix django.db.utils.OperationalError: ORDER BY items must appear in the select list if SELECT DISTINCT is specified.")
dates = Book.objects.annotate(num_authors=Count("authors")).dates('pubdate', 'year')
self.assertQuerysetEqual(
dates, [
"datetime.date(1991, 1, 1)",
"datetime.date(1995, 1, 1)",
"datetime.date(2007, 1, 1)",
"datetime.date(2008, 1, 1)"
]
)
示例5: test_saml_ok
# 需要导入模块: import django [as 别名]
# 或者: from django import utils [as 别名]
def test_saml_ok(self):
"""
test with a valid (ticket, service), with a ST and a PT,
the username and all attributes are transmited"""
tickets = [
# return a ServiceTicket (standard ticket) waiting for validation
get_user_ticket_request(self.service)[1],
# return a PT waiting for validation
get_proxy_ticket(self.service)
]
for ticket in tickets:
client = Client()
# we send the POST validation requests
response = client.post(
'/samlValidate?TARGET=%s' % self.service,
self.xml_template % {
'ticket': ticket.value,
'request_id': utils.gen_saml_id(),
'issue_instant': timezone.now().isoformat()
},
content_type="text/xml; encoding='utf-8'"
)
# and it should succeed
self.assert_success(response, settings.CAS_TEST_USER, settings.CAS_TEST_ATTRIBUTES)
示例6: test_saml_ok_user_field
# 需要导入模块: import django [as 别名]
# 或者: from django import utils [as 别名]
def test_saml_ok_user_field(self):
"""test with a valid(ticket, service), use a attributes as transmitted username"""
for (service, username) in [
(self.service_field_needed_success, settings.CAS_TEST_ATTRIBUTES['alias'][0]),
(self.service_field_needed_success_alt, settings.CAS_TEST_ATTRIBUTES['nom'])
]:
ticket = get_user_ticket_request(service)[1]
client = Client()
response = client.post(
'/samlValidate?TARGET=%s' % service,
self.xml_template % {
'ticket': ticket.value,
'request_id': utils.gen_saml_id(),
'issue_instant': timezone.now().isoformat()
},
content_type="text/xml; encoding='utf-8'"
)
self.assert_success(response, username, {})
示例7: test_saml_bad_ticket
# 需要导入模块: import django [as 别名]
# 或者: from django import utils [as 别名]
def test_saml_bad_ticket(self):
"""test validation with a bad ST and a bad PT, validation should fail"""
tickets = [utils.gen_st(), utils.gen_pt()]
for ticket in tickets:
client = Client()
response = client.post(
'/samlValidate?TARGET=%s' % self.service,
self.xml_template % {
'ticket': ticket,
'request_id': utils.gen_saml_id(),
'issue_instant': timezone.now().isoformat()
},
content_type="text/xml; encoding='utf-8'"
)
self.assert_error(
response,
"AuthnFailed",
'ticket %s not found' % ticket
)
示例8: test_saml_bad_ticket_prefix
# 需要导入模块: import django [as 别名]
# 或者: from django import utils [as 别名]
def test_saml_bad_ticket_prefix(self):
"""test validation with a bad ticket prefix. Validation should fail with 'AuthnFailed'"""
bad_ticket = "RANDOM-NOT-BEGINING-WITH-ST-OR-ST"
client = Client()
response = client.post(
'/samlValidate?TARGET=%s' % self.service,
self.xml_template % {
'ticket': bad_ticket,
'request_id': utils.gen_saml_id(),
'issue_instant': timezone.now().isoformat()
},
content_type="text/xml; encoding='utf-8'"
)
self.assert_error(
response,
"AuthnFailed",
'ticket %s should begin with PT- or ST-' % bad_ticket
)
示例9: test_saml_bad_target
# 需要导入模块: import django [as 别名]
# 或者: from django import utils [as 别名]
def test_saml_bad_target(self):
"""test with a valid ticket, but using a bad target, validation should fail"""
bad_target = "https://www.example.org"
ticket = get_user_ticket_request(self.service)[1]
client = Client()
response = client.post(
'/samlValidate?TARGET=%s' % bad_target,
self.xml_template % {
'ticket': ticket.value,
'request_id': utils.gen_saml_id(),
'issue_instant': timezone.now().isoformat()
},
content_type="text/xml; encoding='utf-8'"
)
self.assert_error(
response,
"AuthnFailed",
'TARGET %s does not match ticket service' % bad_target
)
示例10: test_json_attributes
# 需要导入模块: import django [as 别名]
# 或者: from django import utils [as 别名]
def test_json_attributes(self):
"""test the json storage of ``atrributs`` in ``_attributs``"""
provider = models.FederatedIendityProvider.objects.get(suffix="example.com")
user = models.FederatedUser.objects.create(
username=settings.CAS_TEST_USER,
provider=provider,
attributs=settings.CAS_TEST_ATTRIBUTES,
ticket=""
)
self.assertEqual(utils.json_encode(settings.CAS_TEST_ATTRIBUTES), user._attributs)
user.delete()
user = models.FederatedUser.objects.create(
username=settings.CAS_TEST_USER,
provider=provider,
ticket=""
)
self.assertIsNone(user._attributs)
self.assertIsNone(user.attributs)
示例11: debug
# 需要导入模块: import django [as 别名]
# 或者: from django import utils [as 别名]
def debug(key, value):
from django.utils.termcolors import colorize
if value:
sys.stdout.write(colorize(key, fg='green'))
sys.stdout.write(": ")
sys.stdout.write(colorize(repr(value), fg='white'))
sys.stdout.write("\n")
示例12: statistics_work
# 需要导入模块: import django [as 别名]
# 或者: from django import utils [as 别名]
def statistics_work():
connect.delete('WORK')
work_dist = dict()
import django
now = django.utils.timezone.now().date()
for i in range(6, -1, -1):
start_day = now - datetime.timedelta(days=i)
end_day = now - datetime.timedelta(days=i-1)
weekday = start_day.weekday()
work_dist[week_list[int(weekday)]] = Push_Mission.objects.filter(
create_time__gt=start_day, create_time__lt=end_day
).count()
for key, value in work_dist.items():
connect.hset('WORK', key, value)
示例13: pytest_configure
# 需要导入模块: import django [as 别名]
# 或者: from django import utils [as 别名]
def pytest_configure(config):
deprecation = config.getoption('deprecation')
only_wagtail = r'^wagtail(\.|$)'
if deprecation == 'all':
# Show all deprecation warnings from all packages
warnings.simplefilter('default', DeprecationWarning)
warnings.simplefilter('default', PendingDeprecationWarning)
elif deprecation == 'pending':
# Show all deprecation warnings from wagtail
warnings.filterwarnings('default', category=DeprecationWarning, module=only_wagtail)
warnings.filterwarnings('default', category=PendingDeprecationWarning, module=only_wagtail)
elif deprecation == 'imminent':
# Show only imminent deprecation warnings from wagtail
warnings.filterwarnings('default', category=DeprecationWarning, module=only_wagtail)
elif deprecation == 'none':
# Deprecation warnings are ignored by default
pass
if config.getoption('postgres'):
os.environ['DATABASE_ENGINE'] = 'django.db.backends.postgresql'
# Setup django after processing the pytest arguments so that the env
# variables are available in the settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'wagtail.tests.settings')
django.setup()
# Activate a language: This affects HTTP header HTTP_ACCEPT_LANGUAGE sent by
# the Django test client.
from django.utils import translation
translation.activate("en")
from wagtail.tests.settings import MEDIA_ROOT, STATIC_ROOT
shutil.rmtree(STATIC_ROOT, ignore_errors=True)
shutil.rmtree(MEDIA_ROOT, ignore_errors=True)
示例14: execute
# 需要导入模块: import django [as 别名]
# 或者: from django import utils [as 别名]
def execute(self, *args, **options):
"""
Try to execute this command, performing model validation if
needed (as controlled by the attribute
``self.requires_model_validation``, except if force-skipped).
"""
# Switch to English, because django-admin.py creates database content
# like permissions, and those shouldn't contain any translations.
# But only do this if we can assume we have a working settings file,
# because django.utils.translation requires settings.
saved_lang = None
self.stdout = OutputWrapper(options.get('stdout', sys.stdout))
self.stderr = OutputWrapper(options.get('stderr', sys.stderr), self.style.ERROR)
if self.can_import_settings:
from django.utils import translation
saved_lang = translation.get_language()
translation.activate('en-us')
try:
if self.requires_model_validation and not options.get('skip_validation'):
self.validate()
output = self.handle(*args, **options)
if output:
if self.output_transaction:
# This needs to be imported here, because it relies on
# settings.
from django.db import connections, DEFAULT_DB_ALIAS
connection = connections[options.get('database', DEFAULT_DB_ALIAS)]
if connection.ops.start_transaction_sql():
self.stdout.write(self.style.SQL_KEYWORD(connection.ops.start_transaction_sql()))
self.stdout.write(output)
if self.output_transaction:
self.stdout.write('\n' + self.style.SQL_KEYWORD("COMMIT;"))
finally:
if saved_lang is not None:
translation.activate(saved_lang)
示例15: get_latest_script
# 需要导入模块: import django [as 别名]
# 或者: from django import utils [as 别名]
def get_latest_script(script_version):
"""Downloads the latest script version to the local storage.
:param script_version: :py:class:`~wooey.models.core.ScriptVersion`
:return: boolean
Returns true if a new version was downloaded.
"""
script_path = script_version.script_path
local_storage = utils.get_storage(local=True)
script_exists = local_storage.exists(script_path.name)
if not script_exists:
local_storage.save(script_path.name, script_path.file)
return True
else:
# If script exists, make sure the version is valid, otherwise fetch a new one
script_contents = local_storage.open(script_path.name).read()
script_checksum = utils.get_checksum(buff=script_contents)
if script_checksum != script_version.checksum:
tf = tempfile.TemporaryFile()
with tf:
tf.write(script_contents)
tf.seek(0)
local_storage.delete(script_path.name)
local_storage.save(script_path.name, tf)
return True
return False