# django.views.decorators.cache cache_page(60 * 15), cache_control(private=True), never_cache, # django.contrib.auth.decorators # Apply user_passes_test twice to check #9474 user_passes_test(lambda u: True), login_required, permission_required('change_world'), # django.contrib.admin.views.decorators staff_member_required, # django.utils.functional keep_lazy(HttpResponse), keep_lazy_text, lazy, # django.utils.safestring mark_safe, ) fully_decorated = full_decorator(fully_decorated) class DecoratorsTest(TestCase): def test_attributes(self): """ Built-in decorators set certain attributes of the wrapped function.
## of music. ## Mind: is the bliss ## of the matter. ## ###################################################################### ## This file contains django forms related to user's profiles and for ## managing trading partners. ## from cStringIO import StringIO # PYTHON3: from io import BytesIO from django import forms from django.forms import widgets from django.conf import settings from django.utils.translation import ugettext_lazy as _ try: from django.utils.functional import keep_lazy allow_lazy = lambda func, *resultclasses: keep_lazy(*resultclasses)(func) except: from django.utils.functional import allow_lazy from django.core.files.uploadhandler import FileUploadHandler from django.core.files.uploadedfile import UploadedFile format_lazy = allow_lazy(lambda x, y: x % y, unicode) class PhotographUploadHandler(FileUploadHandler): """ File upload handler to stream photograph uploads into memory. """ def handle_raw_input(self, input_data, META,
value = unicodedata.normalize('NFKC', value.strip()) value = re.sub(to_und_rgx, '_', value) value = re.sub(slugify_rgx, '-', value) value = re.sub(multi_dash_rgx, '-', value) value = re.sub(dash_und_rgx, '_', value) value = re.sub(und_dash_rgx, '_', value) value = re.sub(starting_chars_rgx, '', value) value = re.sub(ending_chars_rgx, '', value) return mark_safe(value) if DJANGO_VERSION < (1, 10): from django.utils.functional import allow_lazy default_slugify = allow_lazy(default_slugify, six.text_type, SafeText) else: from django.utils.functional import keep_lazy default_slugify = keep_lazy(six.text_type, SafeText)(default_slugify) # DJANGO BACKWARDS-COMPATIBLE PATTERNS def patterns(prefix, *args): if DJANGO_VERSION < (1, 9): from django.conf.urls import patterns as django_patterns return django_patterns(prefix, *args) elif prefix != '': raise Exception("You need to update your URLConf to be a list of URL " "objects") else: return list(args)
## of the matter. ## ###################################################################### ## This file contains django forms related to user's profiles and for ## managing trading partners. ## from cStringIO import StringIO # PYTHON3: from io import BytesIO from django import forms from django.forms import widgets from django.conf import settings from django.utils.translation import ugettext_lazy as _ try: from django.utils.functional import keep_lazy allow_lazy = lambda func, *resultclasses: keep_lazy(*resultclasses)(func) except: from django.utils.functional import allow_lazy from django.core.files.uploadhandler import FileUploadHandler from django.core.files.uploadedfile import UploadedFile format_lazy = allow_lazy(lambda x, y: x % y, unicode) class PhotographUploadHandler(FileUploadHandler): """ File upload handler to stream photograph uploads into memory. """ def handle_raw_input(self, input_data, META, content_length, boundary, encoding=None): # Check the content-length header to see if we should keep the data.
def render(self, context): strip_line_breaks = keep_lazy( six.text_type)(lambda x: x.replace('\n', '')) return strip_line_breaks(self.nodelist.render(context).strip())
except ImportError: from django.utils.importlib import import_module # Django 1.6 / py2.6 def get_function(function_path): """ import and return function from ``path.to.module.function`` argument """ try: mod_name, func_name = function_path.rsplit('.', 1) mod = import_module(mod_name) except ImportError as e: raise ImproperlyConfigured( ('Error importing module %s: "%s"' % (mod_name, e))) return getattr(mod, func_name) def keeptags(value, tags): tags = [re.escape(tag) for tag in tags.split()] def _replacer(match): if match.group(1) in tags: return match.group(0) else: return '' return re.sub(r'</?([^> ]+).*?>', _replacer, value) keeptags = keep_lazy(())(keeptags)
from django.utils import six from django.utils.functional import keep_lazy from django.utils.text import Truncator, format_lazy def string_concat(*strings): return format_lazy('{}' * len(strings), *strings) def truncate_words(s, num, end_text='...'): # truncate_words was removed in Django 1.5. truncate = end_text and ' %s' % end_text or '' return Truncator(s).words(num, truncate=truncate) truncate_words = keep_lazy(truncate_words, six.text_type) if not six.PY3: fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding() # copied from django.utils._os (not present in Django 1.4) def upath(path): """ Always return a unicode path. """ if six.PY2 and not isinstance(path, six.text_type): return path.decode(fs_encoding) return path
newval += value[init:] return newval def get_css_classes_for_app_model(inline_type): if not settings.INLINE_MEDIA_CUSTOM_SIZES.get(inline_type, False): return [] css_classes = [] custom_sizes = settings.INLINE_MEDIA_CUSTOM_SIZES[inline_type] for k in ['mini', 'small', 'medium', 'large']: v = custom_sizes.get(k, None) if v: css_classes.append('inline_%s_left' % k) css_classes.append('inline_%s_right' % k) v = custom_sizes.get('full', None) if v: css_classes.append('inline_full_left') css_classes.append('inline_full_center') css_classes.append('inline_full_right') return css_classes def remove_tags(value, tags): for tag in tags: value = re.sub(tag, ' ', value) return value _tags = keep_lazy(remove_tags)
# -*- coding: utf-8 -*- import django from django.conf import settings from django.utils.functional import keep_lazy if django.VERSION >= (1, 5): from django.contrib.auth import get_user_model AUTH_USER_MODEL = settings.AUTH_USER_MODEL get_user_model = keep_lazy(get_user_model, AUTH_USER_MODEL) get_username_field = keep_lazy(lambda: get_user_model().USERNAME_FIELD, str) else: from django.contrib.auth.models import User AUTH_USER_MODEL = 'auth.User' def get_user_model(): return User def get_username_field(): return 'username' def get_username(user): try: return user.get_username() except AttributeError: return user.username
# -*- coding: utf-8 -*- import django from django.conf import settings from django.utils.functional import keep_lazy if django.VERSION >= (1, 5): from django.contrib.auth import get_user_model AUTH_USER_MODEL = settings.AUTH_USER_MODEL get_user_model = keep_lazy(AUTH_USER_MODEL)(get_user_model) get_username_field = keep_lazy(str)( lambda: get_user_model().USERNAME_FIELD) else: from django.contrib.auth.models import User AUTH_USER_MODEL = 'auth.User' def get_user_model(): return User def get_username_field(): return 'username' def get_username(user): try: return user.get_username() except AttributeError: return user.username
# -*- coding: utf-8 -*- import six from django.utils.encoding import force_text try: from django.utils.functional import keep_lazy KEEP_LAZY = True except ImportError: from django.utils.functional import allow_lazy KEEP_LAZY = False def truncate_letters(s, num): """ truncates a string to a number of letters, similar to truncate_words """ s = force_text(s) length = int(num) if len(s) > length: s = s[:length] if not s.endswith('...'): s += '...' return s if KEEP_LAZY: truncate_letters = keep_lazy(six.text_type)(truncate_letters) else: truncate_letters = allow_lazy(truncate_letters, six.text_type)
import re import unicodedata from django.template.defaultfilters import register, stringfilter from django.utils.functional import keep_lazy from django.utils.safestring import mark_safe def slugify_symbol(value): value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii') value = re.sub('[^$`\w\s-]', '', value).strip().lower() return mark_safe(re.sub('[-\s`]+', '-', value)) slugify_symbol = keep_lazy(slugify_symbol, str) @register.filter(is_safe=True) @stringfilter def slugify(value): """ Converts to lowercase, removes non-word characters apart from '$', and converts spaces to hyphens. Also strips leading and trailing whitespace. Based on the Django version, but modified to preserve '$'. """ return slugify_symbol(value)
from django.utils.functional import keep_lazy from django.utils.text import Truncator, format_lazy def string_concat(*strings): return format_lazy('{}' * len(strings), *strings) def truncate_words(s, num, end_text='...'): # truncate_words was removed in Django 1.5. truncate = end_text and ' %s' % end_text or '' return Truncator(s).words(num, truncate=truncate) truncate_words = keep_lazy(truncate_words, str) def get_delete_permission(opts): from django.contrib.auth import get_permission_codename # noqa return '%s.%s' % (opts.app_label, get_permission_codename('delete', opts)) try: from PIL import ExifTags as PILExifTags # noqa from PIL import Image as PILImage # noqa from PIL import ImageDraw as PILImageDraw # noqa except ImportError: try: import ExifTags as PILExifTags # noqa import Image as PILImage # noqa import ImageDraw as PILImageDraw # noqa
"attrs": "".join(map(lambda x: ' %s="%s"' % x, attrs.items())), "link_text": (abbrev(m.group(), trim_url_limit) if trim_url_limit is not None else m.group()), } return url_re.sub(_repl, text) # copy from django.utils.html.strip_entities(). it was removed def strip_entities(value): """Returns the given HTML with all entities (&something;) stripped.""" return re.sub(r'&(?:\w+|#\d+);', '', force_text(value)) strip_entities = keep_lazy(strip_entities, six.text_type) # copy from bputils: beproud.utils.javascript JS_CONVERT_TYPES = { 'bool': bool, 'int': int, 'string': str, 'array': list, } # copy from bputils: beproud.utils.javascript def force_js(value, typename=None, encoder=None): """ Changes a python value to javascript for use in templates """
Usage: .. code-block:: python :linenos: >>> snakify('polls-report May 1, 2016') u'polls_report_may_1_2016' """ value = force_text(value) value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii') value = re.sub('[^\w\s-]', '', value).strip().lower() return mark_safe(re.sub('[-\s]+', '_', value)) snakify = keep_lazy(snakify, six.text_type, SafeText) def get_child(obj): """ Returns the utilized child class instance of a superclass instance. :param Model obj: Django Model instance :returns: Subclass instance or None """ try: subclass_instance_name = next( rel_obj.name for rel_obj in obj._meta.get_all_related_objects() if rel_obj.parent_link and hasattr(obj, rel_obj.name) )
# django.views.decorators.cache cache_page(60 * 15), cache_control(private=True), never_cache, # django.contrib.auth.decorators # Apply user_passes_test twice to check #9474 user_passes_test(lambda u: True), login_required, permission_required('change_world'), # django.contrib.admin.views.decorators staff_member_required, # django.utils.functional keep_lazy(HttpResponse), keep_lazy_text, lazy, # django.utils.safestring mark_safe, ) fully_decorated = full_decorator(fully_decorated) class DecoratorsTest(TestCase): def test_attributes(self): """ Built-in decorators set certain attributes of the wrapped function. """
return acos(cos_x) * earth_radius_km to_und_rgx = re.compile(r"[']") slugify_rgx = re.compile(r'[^-\w._~]', re.UNICODE) multi_dash_rgx = re.compile(r'-{2,}') dash_und_rgx = re.compile(r'[-_]_') und_dash_rgx = re.compile(r'[-_]-') starting_chars_rgx = re.compile(r'^[-._]*') ending_chars_rgx = re.compile(r'[-.]*$') def default_slugify(obj, value): value = force_text(value) value = unicodedata.normalize('NFKC', value.strip().lower()) value = re.sub(to_und_rgx, '_', value) value = re.sub(slugify_rgx, '-', value) value = re.sub(multi_dash_rgx, '-', value) value = re.sub(dash_und_rgx, '_', value) value = re.sub(und_dash_rgx, '_', value) value = re.sub(starting_chars_rgx, '', value) value = re.sub(ending_chars_rgx, '', value) return mark_safe(value) if VERSION < (1, 10): from django.utils.functional import allow_lazy default_slugify = allow_lazy(default_slugify, six.text_type, SafeText) else: from django.utils.functional import keep_lazy default_slugify = keep_lazy(six.text_type, SafeText)(default_slugify)