Fixed E305 flake8 warnings.

This commit is contained in:
Ramin Farajpour Cami 2016-11-12 20:41:23 +03:30 committed by Tim Graham
parent 6072de727f
commit 967be82443
114 changed files with 360 additions and 0 deletions

View File

@ -422,4 +422,5 @@ class Apps(object):
for function in self._pending_operations.pop(key, []): for function in self._pending_operations.pop(key, []):
function(model) function(model)
apps = Apps(installed_apps=None) apps = Apps(installed_apps=None)

View File

@ -184,4 +184,5 @@ class UserSettingsHolder(BaseSettings):
'cls': self.__class__.__name__, 'cls': self.__class__.__name__,
} }
settings = LazySettings() settings = LazySettings()

View File

@ -11,6 +11,7 @@ from __future__ import unicode_literals
def gettext_noop(s): def gettext_noop(s):
return s return s
#################### ####################
# CORE # # CORE #
#################### ####################

View File

@ -86,4 +86,5 @@ def delete_selected(modeladmin, request, queryset):
"admin/delete_selected_confirmation.html" "admin/delete_selected_confirmation.html"
], context) ], context)
delete_selected.short_description = ugettext_lazy("Delete selected %(verbose_name_plural)s") delete_selected.short_description = ugettext_lazy("Delete selected %(verbose_name_plural)s")

View File

@ -58,5 +58,6 @@ Compiler library and Java version 6 or later."""
else: else:
sys.stdout.write("File %s not found. Sure it exists?\n" % to_compress) sys.stdout.write("File %s not found. Sure it exists?\n" % to_compress)
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -222,6 +222,7 @@ class RelatedFieldListFilter(FieldListFilter):
'display': self.empty_value_display, 'display': self.empty_value_display,
} }
FieldListFilter.register(lambda f: f.remote_field, RelatedFieldListFilter) FieldListFilter.register(lambda f: f.remote_field, RelatedFieldListFilter)
@ -260,6 +261,7 @@ class BooleanFieldListFilter(FieldListFilter):
'display': _('Unknown'), 'display': _('Unknown'),
} }
FieldListFilter.register( FieldListFilter.register(
lambda f: isinstance(f, (models.BooleanField, models.NullBooleanField)), lambda f: isinstance(f, (models.BooleanField, models.NullBooleanField)),
BooleanFieldListFilter BooleanFieldListFilter
@ -307,6 +309,7 @@ class ChoicesFieldListFilter(FieldListFilter):
'display': none_title, 'display': none_title,
} }
FieldListFilter.register(lambda f: bool(f.choices), ChoicesFieldListFilter) FieldListFilter.register(lambda f: bool(f.choices), ChoicesFieldListFilter)
@ -376,6 +379,7 @@ class DateFieldListFilter(FieldListFilter):
'display': title, 'display': title,
} }
FieldListFilter.register( FieldListFilter.register(
lambda f: isinstance(f, models.DateField), DateFieldListFilter) lambda f: isinstance(f, models.DateField), DateFieldListFilter)
@ -434,6 +438,7 @@ class AllValuesFieldListFilter(FieldListFilter):
'display': self.empty_value_display, 'display': self.empty_value_display,
} }
FieldListFilter.register(lambda f: True, AllValuesFieldListFilter) FieldListFilter.register(lambda f: True, AllValuesFieldListFilter)

View File

@ -32,6 +32,7 @@ class ActionForm(forms.Form):
widget=forms.HiddenInput({'class': 'select-across'}), widget=forms.HiddenInput({'class': 'select-across'}),
) )
checkbox = forms.CheckboxInput({'class': 'action-select'}, lambda value: False) checkbox = forms.CheckboxInput({'class': 'action-select'}, lambda value: False)

View File

@ -70,6 +70,7 @@ def get_ul_class(radio_style):
class IncorrectLookupParameters(Exception): class IncorrectLookupParameters(Exception):
pass pass
# Defaults for formfield_overrides. ModelAdmin subclasses can change this # Defaults for formfield_overrides. ModelAdmin subclasses can change this
# by adding to ModelAdmin.formfield_overrides. # by adding to ModelAdmin.formfield_overrides.

View File

@ -501,6 +501,7 @@ class AdminSite(object):
'admin/app_index.html' 'admin/app_index.html'
], context) ], context)
# This global object represents the default admin site, for the common case. # This global object represents the default admin site, for the common case.
# You can instantiate AdminSite in your own code to create a custom admin site. # You can instantiate AdminSite in your own code to create a custom admin site.
site = AdminSite() site = AdminSite()

View File

@ -89,6 +89,7 @@ def parse_rst(text, default_reference_context, thing_being_parsed=None):
) )
return mark_safe(parts['fragment']) return mark_safe(parts['fragment'])
# #
# reST roles # reST roles
# #
@ -137,6 +138,7 @@ def default_reference_role(name, rawtext, text, lineno, inliner, options=None, c
) )
return [node], [] return [node], []
if docutils_is_available: if docutils_is_available:
docutils.parsers.rst.roles.register_canonical_role('cmsreference', default_reference_role) docutils.parsers.rst.roles.register_canonical_role('cmsreference', default_reference_role)

View File

@ -425,6 +425,7 @@ def extract_views_from_urlpatterns(urlpatterns, base='', namespace=None):
raise TypeError(_("%s does not appear to be a urlpattern object") % p) raise TypeError(_("%s does not appear to be a urlpattern object") % p)
return views return views
named_group_matcher = re.compile(r'\(\?P(<\w+>).+?\)') named_group_matcher = re.compile(r'\(\?P(<\w+>).+?\)')
non_named_group_matcher = re.compile(r'\(.*?\)') non_named_group_matcher = re.compile(r'\(.*?\)')

View File

@ -231,4 +231,5 @@ def update_session_auth_hash(request, user):
if hasattr(user, 'get_session_auth_hash') and request.user == user: if hasattr(user, 'get_session_auth_hash') and request.user == user:
request.session[HASH_SESSION_KEY] = user.get_session_auth_hash() request.session[HASH_SESSION_KEY] = user.get_session_auth_hash()
default_app_config = 'django.contrib.auth.apps.AuthConfig' default_app_config = 'django.contrib.auth.apps.AuthConfig'

View File

@ -23,6 +23,8 @@ def update_last_login(sender, user, **kwargs):
""" """
user.last_login = timezone.now() user.last_login = timezone.now()
user.save(update_fields=['last_login']) user.save(update_fields=['last_login'])
user_logged_in.connect(update_last_login) user_logged_in.connect(update_last_login)

View File

@ -88,6 +88,8 @@ def _password_validators_help_text_html(password_validators=None):
help_texts = password_validators_help_texts(password_validators) help_texts = password_validators_help_texts(password_validators)
help_items = [format_html('<li>{}</li>', help_text) for help_text in help_texts] 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 '' return '<ul>%s</ul>' % ''.join(help_items) if help_items else ''
password_validators_help_text_html = lazy(_password_validators_help_text_html, text_type) password_validators_help_text_html = lazy(_password_validators_help_text_html, text_type)

View File

@ -78,4 +78,5 @@ class PasswordResetTokenGenerator(object):
# Used for mocking in tests # Used for mocking in tests
return date.today() return date.today()
default_token_generator = PasswordResetTokenGenerator() default_token_generator = PasswordResetTokenGenerator()

View File

@ -249,6 +249,7 @@ class BaseSpatialField(Field):
else: else:
return obj return obj
for klass in gis_lookups.values(): for klass in gis_lookups.values():
BaseSpatialField.register_lookup(klass) BaseSpatialField.register_lookup(klass)

View File

@ -158,6 +158,8 @@ class OverlapsLeftLookup(GISLookup):
left of B's bounding box. left of B's bounding box.
""" """
lookup_name = 'overlaps_left' lookup_name = 'overlaps_left'
gis_lookups['overlaps_left'] = OverlapsLeftLookup gis_lookups['overlaps_left'] = OverlapsLeftLookup
@ -167,6 +169,8 @@ class OverlapsRightLookup(GISLookup):
right of B's bounding box. right of B's bounding box.
""" """
lookup_name = 'overlaps_right' lookup_name = 'overlaps_right'
gis_lookups['overlaps_right'] = OverlapsRightLookup gis_lookups['overlaps_right'] = OverlapsRightLookup
@ -176,6 +180,8 @@ class OverlapsBelowLookup(GISLookup):
B's bounding box. B's bounding box.
""" """
lookup_name = 'overlaps_below' lookup_name = 'overlaps_below'
gis_lookups['overlaps_below'] = OverlapsBelowLookup gis_lookups['overlaps_below'] = OverlapsBelowLookup
@ -185,6 +191,8 @@ class OverlapsAboveLookup(GISLookup):
B's bounding box. B's bounding box.
""" """
lookup_name = 'overlaps_above' lookup_name = 'overlaps_above'
gis_lookups['overlaps_above'] = OverlapsAboveLookup gis_lookups['overlaps_above'] = OverlapsAboveLookup
@ -194,6 +202,8 @@ class LeftLookup(GISLookup):
of B's bounding box. of B's bounding box.
""" """
lookup_name = 'left' lookup_name = 'left'
gis_lookups['left'] = LeftLookup gis_lookups['left'] = LeftLookup
@ -203,6 +213,8 @@ class RightLookup(GISLookup):
of B's bounding box. of B's bounding box.
""" """
lookup_name = 'right' lookup_name = 'right'
gis_lookups['right'] = RightLookup gis_lookups['right'] = RightLookup
@ -212,6 +224,8 @@ class StrictlyBelowLookup(GISLookup):
bounding box. bounding box.
""" """
lookup_name = 'strictly_below' lookup_name = 'strictly_below'
gis_lookups['strictly_below'] = StrictlyBelowLookup gis_lookups['strictly_below'] = StrictlyBelowLookup
@ -221,6 +235,8 @@ class StrictlyAboveLookup(GISLookup):
bounding box. bounding box.
""" """
lookup_name = 'strictly_above' lookup_name = 'strictly_above'
gis_lookups['strictly_above'] = StrictlyAboveLookup gis_lookups['strictly_above'] = StrictlyAboveLookup
@ -231,12 +247,16 @@ class SameAsLookup(GISLookup):
vertex-by-vertex, the operator returns true. vertex-by-vertex, the operator returns true.
""" """
lookup_name = 'same_as' lookup_name = 'same_as'
gis_lookups['same_as'] = SameAsLookup gis_lookups['same_as'] = SameAsLookup
class ExactLookup(SameAsLookup): class ExactLookup(SameAsLookup):
# Alias of same_as # Alias of same_as
lookup_name = 'exact' lookup_name = 'exact'
gis_lookups['exact'] = ExactLookup gis_lookups['exact'] = ExactLookup
@ -246,6 +266,8 @@ class BBContainsLookup(GISLookup):
by B's bounding box. by B's bounding box.
""" """
lookup_name = 'bbcontains' lookup_name = 'bbcontains'
gis_lookups['bbcontains'] = BBContainsLookup gis_lookups['bbcontains'] = BBContainsLookup
@ -254,6 +276,8 @@ class BBOverlapsLookup(GISLookup):
The 'bboverlaps' operator returns true if A's bounding box overlaps B's bounding box. The 'bboverlaps' operator returns true if A's bounding box overlaps B's bounding box.
""" """
lookup_name = 'bboverlaps' lookup_name = 'bboverlaps'
gis_lookups['bboverlaps'] = BBOverlapsLookup gis_lookups['bboverlaps'] = BBOverlapsLookup
@ -263,6 +287,8 @@ class ContainedLookup(GISLookup):
by B's bounding box. by B's bounding box.
""" """
lookup_name = 'contained' lookup_name = 'contained'
gis_lookups['contained'] = ContainedLookup gis_lookups['contained'] = ContainedLookup
@ -272,41 +298,57 @@ gis_lookups['contained'] = ContainedLookup
class ContainsLookup(GISLookup): class ContainsLookup(GISLookup):
lookup_name = 'contains' lookup_name = 'contains'
gis_lookups['contains'] = ContainsLookup gis_lookups['contains'] = ContainsLookup
class ContainsProperlyLookup(GISLookup): class ContainsProperlyLookup(GISLookup):
lookup_name = 'contains_properly' lookup_name = 'contains_properly'
gis_lookups['contains_properly'] = ContainsProperlyLookup gis_lookups['contains_properly'] = ContainsProperlyLookup
class CoveredByLookup(GISLookup): class CoveredByLookup(GISLookup):
lookup_name = 'coveredby' lookup_name = 'coveredby'
gis_lookups['coveredby'] = CoveredByLookup gis_lookups['coveredby'] = CoveredByLookup
class CoversLookup(GISLookup): class CoversLookup(GISLookup):
lookup_name = 'covers' lookup_name = 'covers'
gis_lookups['covers'] = CoversLookup gis_lookups['covers'] = CoversLookup
class CrossesLookup(GISLookup): class CrossesLookup(GISLookup):
lookup_name = 'crosses' lookup_name = 'crosses'
gis_lookups['crosses'] = CrossesLookup gis_lookups['crosses'] = CrossesLookup
class DisjointLookup(GISLookup): class DisjointLookup(GISLookup):
lookup_name = 'disjoint' lookup_name = 'disjoint'
gis_lookups['disjoint'] = DisjointLookup gis_lookups['disjoint'] = DisjointLookup
class EqualsLookup(GISLookup): class EqualsLookup(GISLookup):
lookup_name = 'equals' lookup_name = 'equals'
gis_lookups['equals'] = EqualsLookup gis_lookups['equals'] = EqualsLookup
class IntersectsLookup(GISLookup): class IntersectsLookup(GISLookup):
lookup_name = 'intersects' lookup_name = 'intersects'
gis_lookups['intersects'] = IntersectsLookup gis_lookups['intersects'] = IntersectsLookup
@ -322,11 +364,15 @@ class IsValidLookup(BuiltinLookup):
if not self.rhs: if not self.rhs:
sql = 'NOT ' + sql sql = 'NOT ' + sql
return sql, params return sql, params
gis_lookups['isvalid'] = IsValidLookup gis_lookups['isvalid'] = IsValidLookup
class OverlapsLookup(GISLookup): class OverlapsLookup(GISLookup):
lookup_name = 'overlaps' lookup_name = 'overlaps'
gis_lookups['overlaps'] = OverlapsLookup gis_lookups['overlaps'] = OverlapsLookup
@ -347,16 +393,22 @@ class RelateLookup(GISLookup):
if not isinstance(pattern, six.string_types) or not self.pattern_regex.match(pattern): if not isinstance(pattern, six.string_types) or not self.pattern_regex.match(pattern):
raise ValueError('Invalid intersection matrix pattern "%s".' % pattern) raise ValueError('Invalid intersection matrix pattern "%s".' % pattern)
return super(RelateLookup, self).get_db_prep_lookup(value, connection) return super(RelateLookup, self).get_db_prep_lookup(value, connection)
gis_lookups['relate'] = RelateLookup gis_lookups['relate'] = RelateLookup
class TouchesLookup(GISLookup): class TouchesLookup(GISLookup):
lookup_name = 'touches' lookup_name = 'touches'
gis_lookups['touches'] = TouchesLookup gis_lookups['touches'] = TouchesLookup
class WithinLookup(GISLookup): class WithinLookup(GISLookup):
lookup_name = 'within' lookup_name = 'within'
gis_lookups['within'] = WithinLookup gis_lookups['within'] = WithinLookup
@ -395,24 +447,34 @@ class DistanceLookupBase(GISLookup):
class DWithinLookup(DistanceLookupBase): class DWithinLookup(DistanceLookupBase):
lookup_name = 'dwithin' lookup_name = 'dwithin'
sql_template = '%(func)s(%(lhs)s, %(rhs)s, %%s)' sql_template = '%(func)s(%(lhs)s, %(rhs)s, %%s)'
gis_lookups['dwithin'] = DWithinLookup gis_lookups['dwithin'] = DWithinLookup
class DistanceGTLookup(DistanceLookupBase): class DistanceGTLookup(DistanceLookupBase):
lookup_name = 'distance_gt' lookup_name = 'distance_gt'
gis_lookups['distance_gt'] = DistanceGTLookup gis_lookups['distance_gt'] = DistanceGTLookup
class DistanceGTELookup(DistanceLookupBase): class DistanceGTELookup(DistanceLookupBase):
lookup_name = 'distance_gte' lookup_name = 'distance_gte'
gis_lookups['distance_gte'] = DistanceGTELookup gis_lookups['distance_gte'] = DistanceGTELookup
class DistanceLTLookup(DistanceLookupBase): class DistanceLTLookup(DistanceLookupBase):
lookup_name = 'distance_lt' lookup_name = 'distance_lt'
gis_lookups['distance_lt'] = DistanceLTLookup gis_lookups['distance_lt'] = DistanceLTLookup
class DistanceLTELookup(DistanceLookupBase): class DistanceLTELookup(DistanceLookupBase):
lookup_name = 'distance_lte' lookup_name = 'distance_lte'
gis_lookups['distance_lte'] = DistanceLTELookup gis_lookups['distance_lte'] = DistanceLTELookup

View File

@ -27,6 +27,7 @@ class OGRIndexError(GDALException, KeyError):
""" """
silent_variable_failure = True silent_variable_failure = True
# #### GDAL/OGR error checking codes and routine #### # #### GDAL/OGR error checking codes and routine ####
# OGR Error Codes # OGR Error Codes

View File

@ -692,6 +692,7 @@ class MultiLineString(GeometryCollection):
class MultiPolygon(GeometryCollection): class MultiPolygon(GeometryCollection):
pass pass
# Class mapping dictionary (using the OGRwkbGeometryType as the key) # Class mapping dictionary (using the OGRwkbGeometryType as the key)
GEO_CLASSES = {1: Point, GEO_CLASSES = {1: Point,
2: LineString, 2: LineString,

View File

@ -66,6 +66,7 @@ def std_call(func):
else: else:
return lgdal[func] return lgdal[func]
# #### Version-information functions. #### # #### Version-information functions. ####
# Returns GDAL library version information with the given key. # Returns GDAL library version information with the given key.
@ -83,6 +84,7 @@ def gdal_full_version():
"Returns the full GDAL version information." "Returns the full GDAL version information."
return _version_info('') return _version_info('')
version_regex = re.compile(r'^(?P<major>\d+)\.(?P<minor>\d+)(\.(?P<subminor>\d+))?') version_regex = re.compile(r'^(?P<major>\d+)\.(?P<minor>\d+)(\.(?P<subminor>\d+))?')
@ -93,6 +95,7 @@ def gdal_version_info():
raise GDALException('Could not parse GDAL version string "%s"' % ver) raise GDALException('Could not parse GDAL version string "%s"' % ver)
return {key: m.group(key) for key in ('major', 'minor', 'subminor')} return {key: m.group(key) for key in ('major', 'minor', 'subminor')}
_verinfo = gdal_version_info() _verinfo = gdal_version_info()
GDAL_MAJOR_VERSION = int(_verinfo['major']) GDAL_MAJOR_VERSION = int(_verinfo['major'])
GDAL_MINOR_VERSION = int(_verinfo['minor']) GDAL_MINOR_VERSION = int(_verinfo['minor'])
@ -106,6 +109,8 @@ CPLErrorHandler = CFUNCTYPE(None, c_int, c_int, c_char_p)
def err_handler(error_class, error_number, message): def err_handler(error_class, error_number, message):
logger.error('GDAL_ERROR %d: %s', error_number, message) logger.error('GDAL_ERROR %d: %s', error_number, message)
err_handler = CPLErrorHandler(err_handler) err_handler = CPLErrorHandler(err_handler)
@ -115,5 +120,6 @@ def function(name, args, restype):
func.restype = restype func.restype = restype
return func return func
set_error_handler = function('CPLSetErrorHandler', [CPLErrorHandler], CPLErrorHandler) set_error_handler = function('CPLSetErrorHandler', [CPLErrorHandler], CPLErrorHandler)
set_error_handler(err_handler) set_error_handler(err_handler)

View File

@ -29,6 +29,7 @@ def topology_func(f):
f.errcheck = lambda result, func, cargs: bool(result) f.errcheck = lambda result, func, cargs: bool(result)
return f return f
# ### OGR_G ctypes function prototypes ### # ### OGR_G ctypes function prototypes ###
# GeoJSON routines. # GeoJSON routines.

View File

@ -23,6 +23,7 @@ def units_func(f):
""" """
return double_output(f, [c_void_p, POINTER(c_char_p)], strarg=True) return double_output(f, [c_void_p, POINTER(c_char_p)], strarg=True)
# Creation & destruction. # Creation & destruction.
clone_srs = srs_output(std_call('OSRClone'), [c_void_p]) clone_srs = srs_output(std_call('OSRClone'), [c_void_p])
new_srs = srs_output(std_call('OSRNewSpatialReference'), [c_char_p]) new_srs = srs_output(std_call('OSRNewSpatialReference'), [c_char_p])

View File

@ -23,6 +23,8 @@ class GeoIPRecord(Structure):
('charset', c_int), ('charset', c_int),
('continent_code', c_char_p), ('continent_code', c_char_p),
] ]
geoip_char_fields = [name for name, ctype in GeoIPRecord._fields_ if ctype is c_char_p] geoip_char_fields = [name for name, ctype in GeoIPRecord._fields_ if ctype is c_char_p]
GEOIP_DEFAULT_ENCODING = 'iso-8859-1' GEOIP_DEFAULT_ENCODING = 'iso-8859-1'
geoip_encodings = { geoip_encodings = {
@ -34,6 +36,7 @@ geoip_encodings = {
class GeoIPTag(Structure): class GeoIPTag(Structure):
pass pass
RECTYPE = POINTER(GeoIPRecord) RECTYPE = POINTER(GeoIPRecord)
DBTYPE = POINTER(GeoIPTag) DBTYPE = POINTER(GeoIPTag)
@ -79,6 +82,8 @@ def record_output(func):
func.restype = RECTYPE func.restype = RECTYPE
func.errcheck = check_record func.errcheck = check_record
return func return func
GeoIP_record_by_addr = record_output(lgeoip.GeoIP_record_by_addr) GeoIP_record_by_addr = record_output(lgeoip.GeoIP_record_by_addr)
GeoIP_record_by_name = record_output(lgeoip.GeoIP_record_by_name) GeoIP_record_by_name = record_output(lgeoip.GeoIP_record_by_name)
@ -104,6 +109,7 @@ def check_string(result, func, cargs):
s = '' s = ''
return s.decode(GEOIP_DEFAULT_ENCODING) return s.decode(GEOIP_DEFAULT_ENCODING)
GeoIP_database_info = lgeoip.GeoIP_database_info GeoIP_database_info = lgeoip.GeoIP_database_info
GeoIP_database_info.restype = geoip_char_p GeoIP_database_info.restype = geoip_char_p
GeoIP_database_info.errcheck = check_string GeoIP_database_info.errcheck = check_string
@ -119,6 +125,7 @@ def string_output(func):
func.errcheck = _err_check func.errcheck = _err_check
return func return func
GeoIP_country_code_by_addr = string_output(lgeoip.GeoIP_country_code_by_addr) GeoIP_country_code_by_addr = string_output(lgeoip.GeoIP_country_code_by_addr)
GeoIP_country_code_by_name = string_output(lgeoip.GeoIP_country_code_by_name) GeoIP_country_code_by_name = string_output(lgeoip.GeoIP_country_code_by_name)
GeoIP_country_name_by_addr = string_output(lgeoip.GeoIP_country_name_by_addr) GeoIP_country_name_by_addr = string_output(lgeoip.GeoIP_country_name_by_addr)

View File

@ -137,6 +137,7 @@ class MultiPolygon(GeometryCollection):
) )
return GEOSGeometry(capi.geos_cascaded_union(self.ptr), self.srid) return GEOSGeometry(capi.geos_cascaded_union(self.ptr), self.srid)
# Setting the allowed types here since GeometryCollection is defined before # Setting the allowed types here since GeometryCollection is defined before
# its subclasses. # its subclasses.
GeometryCollection._allowed = (Point, LineString, LinearRing, Polygon, MultiPoint, MultiLineString, MultiPolygon) GeometryCollection._allowed = (Point, LineString, LinearRing, Polygon, MultiPoint, MultiLineString, MultiPolygon)

View File

@ -83,6 +83,8 @@ def notice_h(fmt, lst):
except TypeError: except TypeError:
warn_msg = fmt warn_msg = fmt
logger.warning('GEOS_NOTICE: %s\n', warn_msg) logger.warning('GEOS_NOTICE: %s\n', warn_msg)
notice_h = NOTICEFUNC(notice_h) notice_h = NOTICEFUNC(notice_h)
ERRORFUNC = CFUNCTYPE(None, c_char_p, c_char_p) ERRORFUNC = CFUNCTYPE(None, c_char_p, c_char_p)
@ -95,6 +97,8 @@ def error_h(fmt, lst):
except TypeError: except TypeError:
err_msg = fmt err_msg = fmt
logger.error('GEOS_ERROR: %s\n', err_msg) logger.error('GEOS_ERROR: %s\n', err_msg)
error_h = ERRORFUNC(error_h) error_h = ERRORFUNC(error_h)
# #### GEOS Geometry C data structures, and utility functions. #### # #### GEOS Geometry C data structures, and utility functions. ####
@ -116,6 +120,7 @@ class GEOSCoordSeq_t(Structure):
class GEOSContextHandle_t(Structure): class GEOSContextHandle_t(Structure):
pass pass
# Pointers to opaque GEOS geometry structures. # Pointers to opaque GEOS geometry structures.
GEOM_PTR = POINTER(GEOSGeom_t) GEOM_PTR = POINTER(GEOSGeom_t)
PREPGEOM_PTR = POINTER(GEOSPrepGeom_t) PREPGEOM_PTR = POINTER(GEOSPrepGeom_t)

View File

@ -27,6 +27,7 @@ class WKBReader_st(Structure):
class WKBWriter_st(Structure): class WKBWriter_st(Structure):
pass pass
WKT_READ_PTR = POINTER(WKTReader_st) WKT_READ_PTR = POINTER(WKTReader_st)
WKT_WRITE_PTR = POINTER(WKTWriter_st) WKT_WRITE_PTR = POINTER(WKTWriter_st)
WKB_READ_PTR = POINTER(WKBReader_st) WKB_READ_PTR = POINTER(WKBReader_st)
@ -101,6 +102,7 @@ class WKBWriterGet(GEOSFuncFactory):
class WKBWriterSet(GEOSFuncFactory): class WKBWriterSet(GEOSFuncFactory):
argtypes = [WKB_WRITE_PTR, c_int] argtypes = [WKB_WRITE_PTR, c_int]
wkb_writer_get_byteorder = WKBWriterGet('GEOSWKBWriter_getByteOrder') wkb_writer_get_byteorder = WKBWriterGet('GEOSWKBWriter_getByteOrder')
wkb_writer_set_byteorder = WKBWriterSet('GEOSWKBWriter_setByteOrder') wkb_writer_set_byteorder = WKBWriterSet('GEOSWKBWriter_setByteOrder')
wkb_writer_get_outdim = WKBWriterGet('GEOSWKBWriter_getOutputDimension') wkb_writer_get_outdim = WKBWriterGet('GEOSWKBWriter_getOutputDimension')
@ -281,6 +283,7 @@ class ThreadLocalIO(threading.local):
wkb_w = None wkb_w = None
ewkb_w = None ewkb_w = None
thread_context = ThreadLocalIO() thread_context = ThreadLocalIO()

View File

@ -24,6 +24,7 @@ class GEOSContextHandle(object):
class GEOSContext(threading.local): class GEOSContext(threading.local):
handle = None handle = None
thread_context = GEOSContext() thread_context = GEOSContext()

View File

@ -55,6 +55,7 @@ def intcomma(value, use_l10n=True):
else: else:
return intcomma(new, use_l10n) return intcomma(new, use_l10n)
# A tuple of standard large number to their converters # A tuple of standard large number to their converters
intword_converters = ( intword_converters = (
(6, lambda number: ( (6, lambda number: (

View File

@ -69,6 +69,7 @@ class HStoreField(Field):
return value return value
HStoreField.register_lookup(lookups.DataContains) HStoreField.register_lookup(lookups.DataContains)
HStoreField.register_lookup(lookups.ContainedBy) HStoreField.register_lookup(lookups.ContainedBy)
HStoreField.register_lookup(lookups.HasKey) HStoreField.register_lookup(lookups.HasKey)

View File

@ -121,5 +121,7 @@ def clear_site_cache(sender, **kwargs):
del SITE_CACHE[Site.objects.using(using).get(pk=instance.pk).domain] del SITE_CACHE[Site.objects.using(using).get(pk=instance.pk).domain]
except (KeyError, Site.DoesNotExist): except (KeyError, Site.DoesNotExist):
pass pass
pre_save.connect(clear_site_cache, sender=Site) pre_save.connect(clear_site_cache, sender=Site)
pre_delete.connect(clear_site_cache, sender=Site) pre_delete.connect(clear_site_cache, sender=Site)

View File

@ -405,4 +405,5 @@ class ConfiguredStorage(LazyObject):
def _setup(self): def _setup(self):
self._wrapped = get_storage_class(settings.STATICFILES_STORAGE)() self._wrapped = get_storage_class(settings.STATICFILES_STORAGE)()
staticfiles_storage = ConfiguredStorage() staticfiles_storage = ConfiguredStorage()

View File

@ -13,6 +13,7 @@ def staticfiles_urlpatterns(prefix=None):
prefix = settings.STATIC_URL prefix = settings.STATIC_URL
return static(prefix, view=serve) return static(prefix, view=serve)
# Only append if urlpatterns are empty # Only append if urlpatterns are empty
if settings.DEBUG and not urlpatterns: if settings.DEBUG and not urlpatterns:
urlpatterns += staticfiles_urlpatterns() urlpatterns += staticfiles_urlpatterns()

View File

@ -84,6 +84,7 @@ class CacheHandler(object):
def all(self): def all(self):
return getattr(self._caches, 'caches', {}).values() return getattr(self._caches, 'caches', {}).values()
caches = CacheHandler() caches = CacheHandler()
@ -112,6 +113,7 @@ class DefaultCacheProxy(object):
def __ne__(self, other): def __ne__(self, other):
return caches[DEFAULT_CACHE_ALIAS] != other return caches[DEFAULT_CACHE_ALIAS] != other
cache = DefaultCacheProxy() cache = DefaultCacheProxy()
@ -121,4 +123,6 @@ def close_caches(**kwargs):
# cache.close is a no-op # cache.close is a no-op
for cache in caches.all(): for cache in caches.all():
cache.close() cache.close()
signals.request_finished.connect(close_caches) signals.request_finished.connect(close_caches)

View File

@ -10,6 +10,7 @@ def add_session_cookie_message(message):
"network traffic sniffers to hijack user sessions." "network traffic sniffers to hijack user sessions."
) )
W010 = Warning( W010 = Warning(
add_session_cookie_message( add_session_cookie_message(
"You have 'django.contrib.sessions' in your INSTALLED_APPS, " "You have 'django.contrib.sessions' in your INSTALLED_APPS, "

View File

@ -471,4 +471,5 @@ class DefaultStorage(LazyObject):
def _setup(self): def _setup(self):
self._wrapped = get_storage_class()() self._wrapped = get_storage_class()()
default_storage = DefaultStorage() default_storage = DefaultStorage()

View File

@ -16,4 +16,5 @@ class CachedDnsName(object):
self._fqdn = socket.getfqdn() self._fqdn = socket.getfqdn()
return self._fqdn return self._fqdn
DNS_NAME = CachedDnsName() DNS_NAME = CachedDnsName()

View File

@ -161,5 +161,6 @@ class Command(BaseCommand):
self.stdout.write(shutdown_message) self.stdout.write(shutdown_message)
sys.exit(0) sys.exit(0)
# Kept for backward compatibility # Kept for backward compatibility
BaseRunserverCommand = Command BaseRunserverCommand = Command

View File

@ -33,6 +33,7 @@ class DjangoSafeDumper(SafeDumper):
def represent_ordered_dict(self, data): def represent_ordered_dict(self, data):
return self.represent_mapping('tag:yaml.org,2002:map', data.items()) return self.represent_mapping('tag:yaml.org,2002:map', data.items())
DjangoSafeDumper.add_representer(decimal.Decimal, DjangoSafeDumper.represent_decimal) DjangoSafeDumper.add_representer(decimal.Decimal, DjangoSafeDumper.represent_decimal)
DjangoSafeDumper.add_representer(collections.OrderedDict, DjangoSafeDumper.represent_ordered_dict) DjangoSafeDumper.add_representer(collections.OrderedDict, DjangoSafeDumper.represent_ordered_dict)

View File

@ -155,6 +155,7 @@ class URLValidator(RegexValidator):
if len(urlsplit(value).netloc) > 253: if len(urlsplit(value).netloc) > 253:
raise ValidationError(self.message, code=self.code) raise ValidationError(self.message, code=self.code)
integer_validator = RegexValidator( integer_validator = RegexValidator(
_lazy_re_compile(r'^-?\d+\Z'), _lazy_re_compile(r'^-?\d+\Z'),
message=_('Enter a valid integer.'), message=_('Enter a valid integer.'),
@ -236,6 +237,7 @@ class EmailValidator(object):
(self.code == other.code) (self.code == other.code)
) )
validate_email = EmailValidator() validate_email = EmailValidator()
slug_re = _lazy_re_compile(r'^[-a-zA-Z0-9_]+\Z') slug_re = _lazy_re_compile(r'^[-a-zA-Z0-9_]+\Z')
@ -270,6 +272,7 @@ def validate_ipv46_address(value):
except ValidationError: except ValidationError:
raise ValidationError(_('Enter a valid IPv4 or IPv6 address.'), code='invalid') raise ValidationError(_('Enter a valid IPv4 or IPv6 address.'), code='invalid')
ip_address_validator_map = { ip_address_validator_map = {
'both': ([validate_ipv46_address], _('Enter a valid IPv4 or IPv6 address.')), 'both': ([validate_ipv46_address], _('Enter a valid IPv4 or IPv6 address.')),
'ipv4': ([validate_ipv4_address], _('Enter a valid IPv4 address.')), 'ipv4': ([validate_ipv4_address], _('Enter a valid IPv4 address.')),
@ -500,6 +503,7 @@ def get_available_image_extensions():
Image.init() Image.init()
return [ext.lower()[1:] for ext in Image.EXTENSION.keys()] return [ext.lower()[1:] for ext in Image.EXTENSION.keys()]
validate_image_file_extension = FileExtensionValidator( validate_image_file_extension = FileExtensionValidator(
allowed_extensions=get_available_image_extensions(), allowed_extensions=get_available_image_extensions(),
) )

View File

@ -44,6 +44,7 @@ class DefaultConnectionProxy(object):
def __ne__(self, other): def __ne__(self, other):
return connections[DEFAULT_DB_ALIAS] != other return connections[DEFAULT_DB_ALIAS] != other
connection = DefaultConnectionProxy() connection = DefaultConnectionProxy()
@ -51,6 +52,8 @@ connection = DefaultConnectionProxy()
def reset_queries(**kwargs): def reset_queries(**kwargs):
for conn in connections.all(): for conn in connections.all():
conn.queries_log.clear() conn.queries_log.clear()
signals.request_started.connect(reset_queries) signals.request_started.connect(reset_queries)
@ -59,5 +62,7 @@ signals.request_started.connect(reset_queries)
def close_old_connections(**kwargs): def close_old_connections(**kwargs):
for conn in connections.all(): for conn in connections.all():
conn.close_if_unusable_or_obsolete() conn.close_if_unusable_or_obsolete()
signals.request_started.connect(close_old_connections) signals.request_started.connect(close_old_connections)
signals.request_finished.connect(close_old_connections) signals.request_finished.connect(close_old_connections)

View File

@ -65,6 +65,7 @@ def adapt_datetime_warn_on_aware_datetime(value, conv):
value = value.astimezone(timezone.utc).replace(tzinfo=None) value = value.astimezone(timezone.utc).replace(tzinfo=None)
return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S.%f"), conv) 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 # 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 -- # 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 # and Django expects time, so we still need to override that. We also need to

View File

@ -39,6 +39,7 @@ def _setup_environment(environ):
else: else:
os.environ.update(environ) os.environ.update(environ)
_setup_environment([ _setup_environment([
# Oracle takes client-side character set encoding from the environment. # Oracle takes client-side character set encoding from the environment.
('NLS_LANG', '.AL32UTF8'), ('NLS_LANG', '.AL32UTF8'),

View File

@ -28,6 +28,7 @@ def psycopg2_version():
version = psycopg2.__version__.split(' ', 1)[0] version = psycopg2.__version__.split(' ', 1)[0]
return tuple(int(v) for v in version.split('.') if v.isdigit()) return tuple(int(v) for v in version.split('.') if v.isdigit())
PSYCOPG2_VERSION = psycopg2_version() PSYCOPG2_VERSION = psycopg2_version()
if PSYCOPG2_VERSION < (2, 4, 5): if PSYCOPG2_VERSION < (2, 4, 5):

View File

@ -64,6 +64,7 @@ def decoder(conv_func):
""" """
return lambda s: conv_func(s.decode('utf-8')) return lambda s: conv_func(s.decode('utf-8'))
Database.register_converter(str("bool"), decoder(lambda s: s == '1')) Database.register_converter(str("bool"), decoder(lambda s: s == '1'))
Database.register_converter(str("time"), decoder(parse_time)) Database.register_converter(str("time"), decoder(parse_time))
Database.register_converter(str("date"), decoder(parse_date)) Database.register_converter(str("date"), decoder(parse_date))

View File

@ -48,6 +48,7 @@ class Deferred(object):
def __str__(self): def __str__(self):
return str('<Deferred field>') return str('<Deferred field>')
DEFERRED = Deferred() DEFERRED = Deferred()
@ -1772,6 +1773,8 @@ def model_unpickle(model_id):
# Backwards compat - the model was cached directly in earlier versions. # Backwards compat - the model was cached directly in earlier versions.
model = model_id model = model_id
return model.__new__(model) return model.__new__(model)
model_unpickle.__safe_for_unpickle__ = True model_unpickle.__safe_for_unpickle__ = True

View File

@ -61,6 +61,7 @@ class Empty(object):
class NOT_PROVIDED: class NOT_PROVIDED:
pass pass
# The values to use for "blank" in SelectFields. Will be appended to the start # The values to use for "blank" in SelectFields. Will be appended to the start
# of most "choices" lists. # of most "choices" lists.
BLANK_CHOICE_DASH = [("", "---------")] BLANK_CHOICE_DASH = [("", "---------")]

View File

@ -756,6 +756,7 @@ class ForeignObject(RelatedField):
if self.remote_field.limit_choices_to: if self.remote_field.limit_choices_to:
cls._meta.related_fkey_lookups.append(self.remote_field.limit_choices_to) cls._meta.related_fkey_lookups.append(self.remote_field.limit_choices_to)
ForeignObject.register_lookup(RelatedIn) ForeignObject.register_lookup(RelatedIn)
ForeignObject.register_lookup(RelatedExact) ForeignObject.register_lookup(RelatedExact)
ForeignObject.register_lookup(RelatedLessThan) ForeignObject.register_lookup(RelatedLessThan)

View File

@ -234,6 +234,8 @@ class FieldGetDbPrepValueIterableMixin(FieldGetDbPrepValueMixin):
class Exact(FieldGetDbPrepValueMixin, BuiltinLookup): class Exact(FieldGetDbPrepValueMixin, BuiltinLookup):
lookup_name = 'exact' lookup_name = 'exact'
Field.register_lookup(Exact) Field.register_lookup(Exact)
@ -253,21 +255,29 @@ Field.register_lookup(IExact)
class GreaterThan(FieldGetDbPrepValueMixin, BuiltinLookup): class GreaterThan(FieldGetDbPrepValueMixin, BuiltinLookup):
lookup_name = 'gt' lookup_name = 'gt'
Field.register_lookup(GreaterThan) Field.register_lookup(GreaterThan)
class GreaterThanOrEqual(FieldGetDbPrepValueMixin, BuiltinLookup): class GreaterThanOrEqual(FieldGetDbPrepValueMixin, BuiltinLookup):
lookup_name = 'gte' lookup_name = 'gte'
Field.register_lookup(GreaterThanOrEqual) Field.register_lookup(GreaterThanOrEqual)
class LessThan(FieldGetDbPrepValueMixin, BuiltinLookup): class LessThan(FieldGetDbPrepValueMixin, BuiltinLookup):
lookup_name = 'lt' lookup_name = 'lt'
Field.register_lookup(LessThan) Field.register_lookup(LessThan)
class LessThanOrEqual(FieldGetDbPrepValueMixin, BuiltinLookup): class LessThanOrEqual(FieldGetDbPrepValueMixin, BuiltinLookup):
lookup_name = 'lte' lookup_name = 'lte'
Field.register_lookup(LessThanOrEqual) Field.register_lookup(LessThanOrEqual)
@ -284,11 +294,15 @@ class IntegerFieldFloatRounding(object):
class IntegerGreaterThanOrEqual(IntegerFieldFloatRounding, GreaterThanOrEqual): class IntegerGreaterThanOrEqual(IntegerFieldFloatRounding, GreaterThanOrEqual):
pass pass
IntegerField.register_lookup(IntegerGreaterThanOrEqual) IntegerField.register_lookup(IntegerGreaterThanOrEqual)
class IntegerLessThan(IntegerFieldFloatRounding, LessThan): class IntegerLessThan(IntegerFieldFloatRounding, LessThan):
pass pass
IntegerField.register_lookup(IntegerLessThan) IntegerField.register_lookup(IntegerLessThan)
@ -350,6 +364,8 @@ class In(FieldGetDbPrepValueIterableMixin, BuiltinLookup):
params.extend(sqls_params) params.extend(sqls_params)
in_clause_elements.append(')') in_clause_elements.append(')')
return ''.join(in_clause_elements), params return ''.join(in_clause_elements), params
Field.register_lookup(In) Field.register_lookup(In)
@ -381,12 +397,16 @@ class Contains(PatternLookup):
if params and not self.bilateral_transforms: if params and not self.bilateral_transforms:
params[0] = "%%%s%%" % connection.ops.prep_for_like_query(params[0]) params[0] = "%%%s%%" % connection.ops.prep_for_like_query(params[0])
return rhs, params return rhs, params
Field.register_lookup(Contains) Field.register_lookup(Contains)
class IContains(Contains): class IContains(Contains):
lookup_name = 'icontains' lookup_name = 'icontains'
prepare_rhs = False prepare_rhs = False
Field.register_lookup(IContains) Field.register_lookup(IContains)
@ -399,6 +419,8 @@ class StartsWith(PatternLookup):
if params and not self.bilateral_transforms: if params and not self.bilateral_transforms:
params[0] = "%s%%" % connection.ops.prep_for_like_query(params[0]) params[0] = "%s%%" % connection.ops.prep_for_like_query(params[0])
return rhs, params return rhs, params
Field.register_lookup(StartsWith) Field.register_lookup(StartsWith)
@ -411,6 +433,8 @@ class IStartsWith(PatternLookup):
if params and not self.bilateral_transforms: if params and not self.bilateral_transforms:
params[0] = "%s%%" % connection.ops.prep_for_like_query(params[0]) params[0] = "%s%%" % connection.ops.prep_for_like_query(params[0])
return rhs, params return rhs, params
Field.register_lookup(IStartsWith) Field.register_lookup(IStartsWith)
@ -423,6 +447,8 @@ class EndsWith(PatternLookup):
if params and not self.bilateral_transforms: if params and not self.bilateral_transforms:
params[0] = "%%%s" % connection.ops.prep_for_like_query(params[0]) params[0] = "%%%s" % connection.ops.prep_for_like_query(params[0])
return rhs, params return rhs, params
Field.register_lookup(EndsWith) Field.register_lookup(EndsWith)
@ -435,6 +461,8 @@ class IEndsWith(PatternLookup):
if params and not self.bilateral_transforms: if params and not self.bilateral_transforms:
params[0] = "%%%s" % connection.ops.prep_for_like_query(params[0]) params[0] = "%%%s" % connection.ops.prep_for_like_query(params[0])
return rhs, params return rhs, params
Field.register_lookup(IEndsWith) Field.register_lookup(IEndsWith)
@ -444,6 +472,7 @@ class Range(FieldGetDbPrepValueIterableMixin, BuiltinLookup):
def get_rhs_op(self, connection, rhs): def get_rhs_op(self, connection, rhs):
return "BETWEEN %s AND %s" % (rhs[0], rhs[1]) return "BETWEEN %s AND %s" % (rhs[0], rhs[1])
Field.register_lookup(Range) Field.register_lookup(Range)
@ -457,6 +486,8 @@ class IsNull(BuiltinLookup):
return "%s IS NULL" % sql, params return "%s IS NULL" % sql, params
else: else:
return "%s IS NOT NULL" % sql, params return "%s IS NOT NULL" % sql, params
Field.register_lookup(IsNull) Field.register_lookup(IsNull)
@ -473,6 +504,8 @@ class Search(BuiltinLookup):
rhs, rhs_params = self.process_rhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection)
sql_template = connection.ops.fulltext_search_sql(field_name=lhs) sql_template = connection.ops.fulltext_search_sql(field_name=lhs)
return sql_template, lhs_params + rhs_params return sql_template, lhs_params + rhs_params
Field.register_lookup(Search) Field.register_lookup(Search)
@ -488,11 +521,15 @@ class Regex(BuiltinLookup):
rhs, rhs_params = self.process_rhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection)
sql_template = connection.ops.regex_lookup(self.lookup_name) sql_template = connection.ops.regex_lookup(self.lookup_name)
return sql_template % (lhs, rhs), lhs_params + rhs_params return sql_template % (lhs, rhs), lhs_params + rhs_params
Field.register_lookup(Regex) Field.register_lookup(Regex)
class IRegex(Regex): class IRegex(Regex):
lookup_name = 'iregex' lookup_name = 'iregex'
Field.register_lookup(IRegex) Field.register_lookup(IRegex)

View File

@ -18,6 +18,8 @@ def _make_id(target):
if hasattr(target, '__func__'): if hasattr(target, '__func__'):
return (id(target.__self__), id(target.__func__)) return (id(target.__self__), id(target.__func__))
return id(target) return id(target)
NONE_ID = _make_id(None) NONE_ID = _make_id(None)
# A marker for caching # A marker for caching

View File

@ -37,6 +37,7 @@ class InputStreamExhausted(Exception):
""" """
pass pass
RAW = "raw" RAW = "raw"
FILE = "file" FILE = "file"
FIELD = "field" FIELD = "field"

View File

@ -1048,6 +1048,7 @@ class VariableNode(Node):
return '' return ''
return render_value_in_context(output, context) return render_value_in_context(output, context)
# Regex for token keyword arguments # Regex for token keyword arguments
kwarg_re = re.compile(r"(?:(\w+)=)?(.+)") kwarg_re = re.compile(r"(?:(\w+)=)?(.+)")

View File

@ -143,6 +143,7 @@ class EndToken(TokenBase):
def nud(self, parser): def nud(self, parser):
raise parser.error_class("Unexpected end of expression in if tag.") raise parser.error_class("Unexpected end of expression in if tag.")
EndToken = EndToken() EndToken = EndToken()

View File

@ -90,6 +90,7 @@ def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None):
return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))) return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
reverse_lazy = lazy(reverse, six.text_type) reverse_lazy = lazy(reverse, six.text_type)

View File

@ -202,6 +202,7 @@ class ZipArchive(BaseArchive):
def close(self): def close(self):
self._archive.close() self._archive.close()
extension_map = { extension_map = {
'.tar': TarArchive, '.tar': TarArchive,
'.tar.bz2': TarArchive, '.tar.bz2': TarArchive,

View File

@ -92,6 +92,7 @@ class BaseConverter(object):
x = int(x // len(to_digits)) x = int(x // len(to_digits))
return neg, res return neg, res
base2 = BaseConverter(BASE2_ALPHABET) base2 = BaseConverter(BASE2_ALPHABET)
base16 = BaseConverter(BASE16_ALPHABET) base16 = BaseConverter(BASE16_ALPHABET)
base36 = BaseConverter(BASE36_ALPHABET) base36 = BaseConverter(BASE36_ALPHABET)

View File

@ -51,6 +51,7 @@ def new_datetime(d):
kw.extend([d.hour, d.minute, d.second, d.microsecond, d.tzinfo]) kw.extend([d.hour, d.minute, d.second, d.microsecond, d.tzinfo])
return datetime(*kw) return datetime(*kw)
# This library does not support strftime's "%s" or "%y" format strings. # This library does not support strftime's "%s" or "%y" format strings.
# Allowed if there's an even number of "%"s because they are escaped. # Allowed if there's an even number of "%"s because they are escaped.
_illegal_formatting = re.compile(r"((^|[^%])(%%)*%[sy])") _illegal_formatting = re.compile(r"((^|[^%])(%%)*%[sy])")

View File

@ -122,6 +122,7 @@ class CallableBool:
def __hash__(self): def __hash__(self):
return hash(self.value) return hash(self.value)
CallableFalse = CallableBool(False) CallableFalse = CallableBool(False)
CallableTrue = CallableBool(True) CallableTrue = CallableBool(True)

View File

@ -145,6 +145,7 @@ def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
else: else:
return s.encode(encoding, errors) return s.encode(encoding, errors)
if six.PY3: if six.PY3:
smart_str = smart_text smart_str = smart_text
force_str = force_text force_str = force_text
@ -278,4 +279,5 @@ def get_system_encoding():
encoding = 'ascii' encoding = 'ascii'
return encoding return encoding
DEFAULT_LOCALE_ENCODING = get_system_encoding() DEFAULT_LOCALE_ENCODING = get_system_encoding()

View File

@ -454,6 +454,7 @@ class Atom1Feed(SyndicationFeed):
) )
return self.content_type return self.content_type
# This isolates the decision of what the system default is, so calling code can # This isolates the decision of what the system default is, so calling code can
# do "feedgenerator.DefaultFeed" instead of "feedgenerator.Rss201rev2Feed". # do "feedgenerator.DefaultFeed" instead of "feedgenerator.Rss201rev2Feed".
DefaultFeed = Rss201rev2Feed DefaultFeed = Rss201rev2Feed

View File

@ -139,6 +139,7 @@ def get_format(format_type, lang=None, use_l10n=None):
# Return the general setting by default # Return the general setting by default
return getattr(settings, format_type) return getattr(settings, format_type)
get_format_lazy = lazy(get_format, six.text_type, list, tuple) get_format_lazy = lazy(get_format, six.text_type, list, tuple)

View File

@ -228,6 +228,7 @@ def keep_lazy_text(func):
""" """
return keep_lazy(six.text_type)(func) return keep_lazy(six.text_type)(func)
empty = object() empty = object()

View File

@ -50,6 +50,7 @@ def escape(text):
.replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;') .replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;')
) )
_js_escapes = { _js_escapes = {
ord('\\'): '\\u005C', ord('\\'): '\\u005C',
ord('\''): '\\u0027', ord('\''): '\\u0027',

View File

@ -28,6 +28,7 @@ class EscapeText(six.text_type, EscapeData):
""" """
pass pass
if six.PY3: if six.PY3:
EscapeString = EscapeText EscapeString = EscapeText
else: else:
@ -109,6 +110,7 @@ class SafeText(six.text_type, SafeData):
encode = curry(_proxy_method, method=six.text_type.encode) encode = curry(_proxy_method, method=six.text_type.encode)
if six.PY3: if six.PY3:
SafeString = SafeText SafeString = SafeText
else: else:

View File

@ -69,6 +69,7 @@ def make_style(opts=(), **kwargs):
""" """
return lambda text: colorize(text, opts, **kwargs) return lambda text: colorize(text, opts, **kwargs)
NOCOLOR_PALETTE = 'nocolor' NOCOLOR_PALETTE = 'nocolor'
DARK_PALETTE = 'dark' DARK_PALETTE = 'dark'
LIGHT_PALETTE = 'light' LIGHT_PALETTE = 'light'

View File

@ -385,6 +385,7 @@ def _replace_entity(match):
except (ValueError, KeyError): except (ValueError, KeyError):
return match.group(0) return match.group(0)
_entity_re = re.compile(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));") _entity_re = re.compile(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));")
@ -445,4 +446,6 @@ def _format_lazy(format_string, *args, **kwargs):
and/or kwargs might be lazy. and/or kwargs might be lazy.
""" """
return format_string.format(*args, **kwargs) return format_string.format(*args, **kwargs)
format_lazy = lazy(_format_lazy, six.text_type) format_lazy = lazy(_format_lazy, six.text_type)

View File

@ -50,6 +50,7 @@ class FixedOffset(tzinfo):
def dst(self, dt): def dst(self, dt):
return ZERO return ZERO
utc = pytz.utc utc = pytz.utc
"""UTC time zone as a tzinfo instance.""" """UTC time zone as a tzinfo instance."""
@ -85,6 +86,7 @@ def get_default_timezone_name():
""" """
return _get_timezone_name(get_default_timezone()) return _get_timezone_name(get_default_timezone())
_active = local() _active = local()

View File

@ -63,6 +63,7 @@ class Trans(object):
setattr(self, real_name, getattr(trans, real_name)) setattr(self, real_name, getattr(trans, real_name))
return getattr(trans, real_name) return getattr(trans, real_name)
_trans = Trans() _trans = Trans()
# The Trans class is no more needed, so remove it from the namespace. # The Trans class is no more needed, so remove it from the namespace.
@ -72,6 +73,7 @@ del Trans
def gettext_noop(message): def gettext_noop(message):
return _trans.gettext_noop(message) return _trans.gettext_noop(message)
ugettext_noop = gettext_noop ugettext_noop = gettext_noop
@ -98,6 +100,7 @@ def pgettext(context, message):
def npgettext(context, singular, plural, number): def npgettext(context, singular, plural, number):
return _trans.npgettext(context, singular, plural, number) return _trans.npgettext(context, singular, plural, number)
gettext_lazy = lazy(gettext, str) gettext_lazy = lazy(gettext, str)
ugettext_lazy = lazy(ugettext, six.text_type) ugettext_lazy = lazy(ugettext, six.text_type)
pgettext_lazy = lazy(pgettext, six.text_type) pgettext_lazy = lazy(pgettext, six.text_type)
@ -231,6 +234,8 @@ def _string_concat(*strings):
'favor of django.utils.text.format_lazy().', 'favor of django.utils.text.format_lazy().',
RemovedInDjango21Warning, stacklevel=2) RemovedInDjango21Warning, stacklevel=2)
return ''.join(force_text(s) for s in strings) return ''.join(force_text(s) for s in strings)
string_concat = lazy(_string_concat, six.text_type) string_concat = lazy(_string_concat, six.text_type)
@ -255,6 +260,7 @@ def get_language_info(lang_code):
info['name_translated'] = ugettext_lazy(info['name']) info['name_translated'] = ugettext_lazy(info['name'])
return info return info
trim_whitespace_re = re.compile(r'\s*\n\s*') trim_whitespace_re = re.compile(r'\s*\n\s*')

View File

@ -10,6 +10,8 @@ def ngettext(singular, plural, number):
if number == 1: if number == 1:
return singular return singular
return plural return plural
ngettext_lazy = ngettext ngettext_lazy = ngettext
@ -55,6 +57,7 @@ def gettext(message):
def ugettext(message): def ugettext(message):
return force_text(gettext(message)) return force_text(gettext(message))
gettext_noop = gettext_lazy = _ = gettext gettext_noop = gettext_lazy = _ = gettext

View File

@ -337,6 +337,7 @@ def gettext(message):
""" """
return do_translate(message, 'gettext') return do_translate(message, 'gettext')
if six.PY3: if six.PY3:
ugettext = gettext ugettext = gettext
else: else:
@ -384,6 +385,7 @@ def ngettext(singular, plural, number):
""" """
return do_ntranslate(singular, plural, number, 'ngettext') return do_ntranslate(singular, plural, number, 'ngettext')
if six.PY3: if six.PY3:
ungettext = ngettext ungettext = ngettext
else: else:

View File

@ -525,6 +525,7 @@ def default_urlconf(request):
return HttpResponse(t.render(c), content_type='text/html') return HttpResponse(t.render(c), content_type='text/html')
# #
# Templates are embedded in the file so that we know the error handler will # Templates are embedded in the file so that we know the error handler will
# always work even if the template loader is broken. # always work even if the template loader is broken.

View File

@ -41,6 +41,7 @@ def require_http_methods(request_method_list):
return inner return inner
return decorator return decorator
require_GET = require_http_methods(["GET"]) require_GET = require_http_methods(["GET"])
require_GET.__doc__ = "Decorator to require that a view only accepts the GET method." require_GET.__doc__ = "Decorator to require that a view only accepts the GET method."

View File

@ -24,6 +24,7 @@ class EventAdmin(admin.ModelAdmin):
def has_add_permission(self, request): def has_add_permission(self, request):
return False return False
site.register(Event, EventAdmin) site.register(Event, EventAdmin)
@ -98,12 +99,14 @@ class DynamicListDisplayLinksChildAdmin(admin.ModelAdmin):
def get_list_display_links(self, request, list_display): def get_list_display_links(self, request, list_display):
return ['age'] return ['age']
site.register(Child, DynamicListDisplayChildAdmin) site.register(Child, DynamicListDisplayChildAdmin)
class NoListDisplayLinksParentAdmin(admin.ModelAdmin): class NoListDisplayLinksParentAdmin(admin.ModelAdmin):
list_display_links = None list_display_links = None
site.register(Parent, NoListDisplayLinksParentAdmin) site.register(Parent, NoListDisplayLinksParentAdmin)
@ -113,6 +116,7 @@ class SwallowAdmin(admin.ModelAdmin):
list_editable = ['load', 'speed'] list_editable = ['load', 'speed']
list_per_page = 3 list_per_page = 3
site.register(Swallow, SwallowAdmin) site.register(Swallow, SwallowAdmin)

View File

@ -22,6 +22,7 @@ class MockSuperUser(object):
def has_module_perms(self, module): def has_module_perms(self, module):
return True return True
request = MockRequest() request = MockRequest()
request.user = MockSuperUser() request.user = MockSuperUser()

View File

@ -54,6 +54,8 @@ def callable_year(dt_value):
return dt_value.year return dt_value.year
except AttributeError: except AttributeError:
return None return None
callable_year.admin_order_field = 'date' callable_year.admin_order_field = 'date'
@ -252,24 +254,32 @@ def external_mail(modeladmin, request, selected):
'from@example.com', 'from@example.com',
['to@example.com'] ['to@example.com']
).send() ).send()
external_mail.short_description = 'External mail (Another awesome action)' external_mail.short_description = 'External mail (Another awesome action)'
def redirect_to(modeladmin, request, selected): def redirect_to(modeladmin, request, selected):
from django.http import HttpResponseRedirect from django.http import HttpResponseRedirect
return HttpResponseRedirect('/some-where-else/') return HttpResponseRedirect('/some-where-else/')
redirect_to.short_description = 'Redirect to (Awesome action)' redirect_to.short_description = 'Redirect to (Awesome action)'
def download(modeladmin, request, selected): def download(modeladmin, request, selected):
buf = StringIO('This is the content of the file') buf = StringIO('This is the content of the file')
return StreamingHttpResponse(FileWrapper(buf)) return StreamingHttpResponse(FileWrapper(buf))
download.short_description = 'Download subscription' download.short_description = 'Download subscription'
def no_perm(modeladmin, request, selected): def no_perm(modeladmin, request, selected):
return HttpResponse(content='No permission to perform this action', return HttpResponse(content='No permission to perform this action',
status=403) status=403)
no_perm.short_description = 'No permission to run' no_perm.short_description = 'No permission to run'
@ -631,6 +641,8 @@ class AdminOrderedAdminMethodAdmin(admin.ModelAdmin):
def admin_ordered_callable(obj): def admin_ordered_callable(obj):
return obj.order return obj.order
admin_ordered_callable.admin_order_field = 'order' admin_ordered_callable.admin_order_field = 'order'

View File

@ -16,6 +16,7 @@ class Router(object):
db_for_write = db_for_read db_for_write = db_for_read
site = admin.AdminSite(name='test_adminsite') site = admin.AdminSite(name='test_adminsite')
site.register(Book) site.register(Book)

View File

@ -33,6 +33,7 @@ class SchoolAdmin(admin.ModelAdmin):
filter_vertical = ('students',) filter_vertical = ('students',)
filter_horizontal = ('alumni',) filter_horizontal = ('alumni',)
site = WidgetAdmin(name='widget-admin') site = WidgetAdmin(name='widget-admin')
site.register(models.User) site.register(models.User)

View File

@ -15,6 +15,7 @@ class Router(object):
db_for_write = db_for_read db_for_write = db_for_read
site = admin.AdminSite(name='test_adminsite') site = admin.AdminSite(name='test_adminsite')
site.register(User, admin_class=UserAdmin) site.register(User, admin_class=UserAdmin)

View File

@ -15,6 +15,7 @@ class CustomUserAdmin(UserAdmin):
super(CustomUserAdmin, self).log_change(request, object, message) super(CustomUserAdmin, self).log_change(request, object, message)
request.user.pk = original_pk request.user.pk = original_pk
site.register(get_user_model(), CustomUserAdmin) site.register(get_user_model(), CustomUserAdmin)
urlpatterns = [ urlpatterns = [

View File

@ -16,6 +16,7 @@ class CustomBaseModel(models.base.ModelBase):
class MyModel(six.with_metaclass(CustomBaseModel, models.Model)): class MyModel(six.with_metaclass(CustomBaseModel, models.Model)):
"""Model subclass with a custom base using six.with_metaclass.""" """Model subclass with a custom base using six.with_metaclass."""
# This is done to ensure that for Python2 only, defining metaclasses # This is done to ensure that for Python2 only, defining metaclasses
# still does not fail to create the model. # still does not fail to create the model.

View File

@ -137,12 +137,16 @@ def simple_system_check(**kwargs):
def tagged_system_check(**kwargs): def tagged_system_check(**kwargs):
tagged_system_check.kwargs = kwargs tagged_system_check.kwargs = kwargs
return [checks.Warning('System Check')] return [checks.Warning('System Check')]
tagged_system_check.tags = ['simpletag'] tagged_system_check.tags = ['simpletag']
def deployment_system_check(**kwargs): def deployment_system_check(**kwargs):
deployment_system_check.kwargs = kwargs deployment_system_check.kwargs = kwargs
return [checks.Warning('Deployment Check')] return [checks.Warning('Deployment Check')]
deployment_system_check.tags = ['deploymenttag'] deployment_system_check.tags = ['deploymenttag']

View File

@ -30,6 +30,8 @@ from django.views.decorators.vary import vary_on_cookie, vary_on_headers
def fully_decorated(request): def fully_decorated(request):
"""Expected __doc__""" """Expected __doc__"""
return HttpResponse('<html><body>dummy</body></html>') return HttpResponse('<html><body>dummy</body></html>')
fully_decorated.anything = "Expected __dict__" fully_decorated.anything = "Expected __dict__"
@ -170,6 +172,7 @@ def simple_dec(func):
return func("test:" + arg) return func("test:" + arg)
return wraps(func)(wrapper) return wraps(func)(wrapper)
simple_dec_m = method_decorator(simple_dec) simple_dec_m = method_decorator(simple_dec)
@ -180,6 +183,7 @@ def myattr_dec(func):
wrapper.myattr = True wrapper.myattr = True
return wraps(func)(wrapper) return wraps(func)(wrapper)
myattr_dec_m = method_decorator(myattr_dec) myattr_dec_m = method_decorator(myattr_dec)
@ -189,6 +193,7 @@ def myattr2_dec(func):
wrapper.myattr2 = True wrapper.myattr2 = True
return wraps(func)(wrapper) return wraps(func)(wrapper)
myattr2_dec_m = method_decorator(myattr2_dec) myattr2_dec_m = method_decorator(myattr2_dec)

View File

@ -35,6 +35,7 @@ class Callable(object):
def a(self, val, **kwargs): def a(self, val, **kwargs):
return val return val
a_signal = Signal(providing_args=["val"]) a_signal = Signal(providing_args=["val"])
b_signal = Signal(providing_args=["val"]) b_signal = Signal(providing_args=["val"])
c_signal = Signal(providing_args=["val"]) c_signal = Signal(providing_args=["val"])

View File

@ -53,6 +53,7 @@ FavoriteDrinksFormSet = formset_factory(FavoriteDrinkForm, formset=BaseFavoriteD
class SplitDateTimeForm(Form): class SplitDateTimeForm(Form):
when = SplitDateTimeField(initial=datetime.datetime.now) when = SplitDateTimeField(initial=datetime.datetime.now)
SplitDateTimeFormSet = formset_factory(SplitDateTimeForm) SplitDateTimeFormSet = formset_factory(SplitDateTimeForm)
@ -1281,6 +1282,7 @@ class ArticleForm(Form):
title = CharField() title = CharField()
pub_date = DateField() pub_date = DateField()
ArticleFormSet = formset_factory(ArticleForm) ArticleFormSet = formset_factory(ArticleForm)

View File

@ -397,6 +397,7 @@ class MockSuperUser(object):
def has_perm(self, perm): def has_perm(self, perm):
return True return True
request = MockRequest() request = MockRequest()
request.user = MockSuperUser() request.user = MockSuperUser()

View File

@ -214,4 +214,5 @@ class Related(models.Model):
def prevent_deletes(sender, instance, **kwargs): def prevent_deletes(sender, instance, **kwargs):
raise ProtectedError("Not allowed to delete.", [instance]) raise ProtectedError("Not allowed to delete.", [instance])
models.signals.pre_delete.connect(prevent_deletes, sender=Node) models.signals.pre_delete.connect(prevent_deletes, sender=Node)

View File

@ -37,6 +37,7 @@ class DoesNotExistQuerySet(QuerySet):
def get(self, *args, **kwargs): def get(self, *args, **kwargs):
raise Author.DoesNotExist raise Author.DoesNotExist
DoesNotExistBookManager = BaseManager.from_queryset(DoesNotExistQuerySet) DoesNotExistBookManager = BaseManager.from_queryset(DoesNotExistQuerySet)

View File

@ -16,6 +16,7 @@ class TestSRS:
for key, value in kwargs.items(): for key, value in kwargs.items():
setattr(self, key, value) setattr(self, key, value)
WGS84_proj = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs ' WGS84_proj = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs '
# Some Spatial Reference examples # Some Spatial Reference examples

View File

@ -60,6 +60,7 @@ class TestW3CGeo3(TestGeoRSS1):
from django.contrib.gis.geos import Polygon from django.contrib.gis.geos import Polygon
return Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))) return Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)))
# The feed dictionary to use for URLs. # The feed dictionary to use for URLs.
feed_dict = { feed_dict = {
'rss1': TestGeoRSS1, 'rss1': TestGeoRSS1,

View File

@ -65,6 +65,7 @@ def api_get_area(x):
def api_get_length(x): def api_get_length(x):
return x.length return x.length
geos_function_tests = [ geos_function_tests = [
val for name, val in vars().items() val for name, val in vars().items()
if hasattr(val, '__call__') and name.startswith('api_get_') if hasattr(val, '__call__') and name.startswith('api_get_')

View File

@ -51,6 +51,7 @@ def nextRange(length):
nextRange.start += 100 nextRange.start += 100
return range(nextRange.start, nextRange.start + length) return range(nextRange.start, nextRange.start + length)
nextRange.start = 0 nextRange.start = 0

View File

@ -277,5 +277,6 @@ def suite():
def run(verbosity=2): def run(verbosity=2):
unittest.TextTestRunner(verbosity=verbosity).run(suite()) unittest.TextTestRunner(verbosity=verbosity).run(suite())
if __name__ == "__main__": if __name__ == "__main__":
run() run()

View File

@ -45,6 +45,7 @@ class IndexTogetherSingleList(models.Model):
class Meta: class Meta:
index_together = ["headline", "pub_date"] index_together = ["headline", "pub_date"]
# Indexing a TextField on Oracle or MySQL results in index creation error. # Indexing a TextField on Oracle or MySQL results in index creation error.
if connection.vendor == 'postgresql': if connection.vendor == 'postgresql':
class IndexedArticle(models.Model): class IndexedArticle(models.Model):

View File

@ -385,6 +385,8 @@ class SettingsConfigTest(AdminScriptTestCase):
def dictConfig(config): def dictConfig(config):
dictConfig.called = True dictConfig.called = True
dictConfig.called = False dictConfig.called = False

View File

@ -218,6 +218,7 @@ class DataModel(models.Model):
class Document(models.Model): class Document(models.Model):
myfile = models.FileField(upload_to='unused', unique=True) myfile = models.FileField(upload_to='unused', unique=True)
############################################################################### ###############################################################################
# ImageField # ImageField

View File

@ -40,6 +40,7 @@ class Article(models.Model):
db_tablespace = 'tbl_tbsp' db_tablespace = 'tbl_tbsp'
managed = False managed = False
# Also set the tables for automatically created models # Also set the tables for automatically created models
Authors = Article._meta.get_field('authors').remote_field.through Authors = Article._meta.get_field('authors').remote_field.through

View File

@ -30,6 +30,7 @@ class MockSuperUser(object):
def has_perm(self, perm): def has_perm(self, perm):
return True return True
request = MockRequest() request = MockRequest()
request.user = MockSuperUser() request.user = MockSuperUser()

View File

@ -182,6 +182,7 @@ def inherited_compare(testcase, pk, klass, data):
for key, value in data.items(): for key, value in data.items():
testcase.assertEqual(value, getattr(instance, key)) testcase.assertEqual(value, getattr(instance, key))
# Define some data types. Each data type is # Define some data types. Each data type is
# actually a pair of functions; one to create # actually a pair of functions; one to create
# and one to compare objects of that type # and one to compare objects of that type

View File

@ -7,6 +7,7 @@ from .http import SimpleSitemap
class HTTPSSitemap(SimpleSitemap): class HTTPSSitemap(SimpleSitemap):
protocol = 'https' protocol = 'https'
secure_sitemaps = { secure_sitemaps = {
'simple': HTTPSSitemap, 'simple': HTTPSSitemap,
} }

View File

@ -32,6 +32,8 @@ def context_stack_length(context):
def no_params(): def no_params():
"""Expected no_params __doc__""" """Expected no_params __doc__"""
return "no_params - Expected result" return "no_params - Expected result"
no_params.anything = "Expected no_params __dict__" no_params.anything = "Expected no_params __dict__"
@ -39,6 +41,8 @@ no_params.anything = "Expected no_params __dict__"
def one_param(arg): def one_param(arg):
"""Expected one_param __doc__""" """Expected one_param __doc__"""
return "one_param - Expected result: %s" % arg return "one_param - Expected result: %s" % arg
one_param.anything = "Expected one_param __dict__" one_param.anything = "Expected one_param __dict__"
@ -46,6 +50,8 @@ one_param.anything = "Expected one_param __dict__"
def explicit_no_context(arg): def explicit_no_context(arg):
"""Expected explicit_no_context __doc__""" """Expected explicit_no_context __doc__"""
return "explicit_no_context - Expected result: %s" % arg return "explicit_no_context - Expected result: %s" % arg
explicit_no_context.anything = "Expected explicit_no_context __dict__" explicit_no_context.anything = "Expected explicit_no_context __dict__"
@ -53,6 +59,8 @@ explicit_no_context.anything = "Expected explicit_no_context __dict__"
def no_params_with_context(context): def no_params_with_context(context):
"""Expected no_params_with_context __doc__""" """Expected no_params_with_context __doc__"""
return "no_params_with_context - Expected result (context value: %s)" % context['value'] return "no_params_with_context - Expected result (context value: %s)" % context['value']
no_params_with_context.anything = "Expected no_params_with_context __dict__" no_params_with_context.anything = "Expected no_params_with_context __dict__"
@ -60,6 +68,8 @@ no_params_with_context.anything = "Expected no_params_with_context __dict__"
def params_and_context(context, arg): def params_and_context(context, arg):
"""Expected params_and_context __doc__""" """Expected params_and_context __doc__"""
return "params_and_context - Expected result (context value: %s): %s" % (context['value'], arg) return "params_and_context - Expected result (context value: %s): %s" % (context['value'], arg)
params_and_context.anything = "Expected params_and_context __dict__" params_and_context.anything = "Expected params_and_context __dict__"
@ -67,6 +77,8 @@ params_and_context.anything = "Expected params_and_context __dict__"
def simple_two_params(one, two): def simple_two_params(one, two):
"""Expected simple_two_params __doc__""" """Expected simple_two_params __doc__"""
return "simple_two_params - Expected result: %s, %s" % (one, two) return "simple_two_params - Expected result: %s, %s" % (one, two)
simple_two_params.anything = "Expected simple_two_params __dict__" simple_two_params.anything = "Expected simple_two_params __dict__"
@ -74,6 +86,8 @@ simple_two_params.anything = "Expected simple_two_params __dict__"
def simple_one_default(one, two='hi'): def simple_one_default(one, two='hi'):
"""Expected simple_one_default __doc__""" """Expected simple_one_default __doc__"""
return "simple_one_default - Expected result: %s, %s" % (one, two) return "simple_one_default - Expected result: %s, %s" % (one, two)
simple_one_default.anything = "Expected simple_one_default __dict__" simple_one_default.anything = "Expected simple_one_default __dict__"
@ -83,6 +97,8 @@ def simple_unlimited_args(one, two='hi', *args):
return "simple_unlimited_args - Expected result: %s" % ( return "simple_unlimited_args - Expected result: %s" % (
', '.join(six.text_type(arg) for arg in [one, two] + list(args)) ', '.join(six.text_type(arg) for arg in [one, two] + list(args))
) )
simple_unlimited_args.anything = "Expected simple_unlimited_args __dict__" simple_unlimited_args.anything = "Expected simple_unlimited_args __dict__"
@ -90,6 +106,8 @@ simple_unlimited_args.anything = "Expected simple_unlimited_args __dict__"
def simple_only_unlimited_args(*args): def simple_only_unlimited_args(*args):
"""Expected simple_only_unlimited_args __doc__""" """Expected simple_only_unlimited_args __doc__"""
return "simple_only_unlimited_args - Expected result: %s" % ', '.join(six.text_type(arg) for arg in args) return "simple_only_unlimited_args - Expected result: %s" % ', '.join(six.text_type(arg) for arg in args)
simple_only_unlimited_args.anything = "Expected simple_only_unlimited_args __dict__" simple_only_unlimited_args.anything = "Expected simple_only_unlimited_args __dict__"
@ -102,6 +120,8 @@ def simple_unlimited_args_kwargs(one, two='hi', *args, **kwargs):
', '.join(six.text_type(arg) for arg in [one, two] + list(args)), ', '.join(six.text_type(arg) for arg in [one, two] + list(args)),
', '.join('%s=%s' % (k, v) for (k, v) in sorted_kwarg) ', '.join('%s=%s' % (k, v) for (k, v) in sorted_kwarg)
) )
simple_unlimited_args_kwargs.anything = "Expected simple_unlimited_args_kwargs __dict__" simple_unlimited_args_kwargs.anything = "Expected simple_unlimited_args_kwargs __dict__"
@ -109,6 +129,8 @@ simple_unlimited_args_kwargs.anything = "Expected simple_unlimited_args_kwargs _
def simple_tag_without_context_parameter(arg): def simple_tag_without_context_parameter(arg):
"""Expected simple_tag_without_context_parameter __doc__""" """Expected simple_tag_without_context_parameter __doc__"""
return "Expected result" return "Expected result"
simple_tag_without_context_parameter.anything = "Expected simple_tag_without_context_parameter __dict__" simple_tag_without_context_parameter.anything = "Expected simple_tag_without_context_parameter __dict__"
@ -144,6 +166,7 @@ def use_l10n(context):
def minustwo_overridden_name(value): def minustwo_overridden_name(value):
return value - 2 return value - 2
register.simple_tag(lambda x: x - 1, name='minusone') register.simple_tag(lambda x: x - 1, name='minusone')

View File

@ -11,6 +11,8 @@ register = Library()
def inclusion_no_params(): def inclusion_no_params():
"""Expected inclusion_no_params __doc__""" """Expected inclusion_no_params __doc__"""
return {"result": "inclusion_no_params - Expected result"} return {"result": "inclusion_no_params - Expected result"}
inclusion_no_params.anything = "Expected inclusion_no_params __dict__" inclusion_no_params.anything = "Expected inclusion_no_params __dict__"
@ -18,6 +20,8 @@ inclusion_no_params.anything = "Expected inclusion_no_params __dict__"
def inclusion_no_params_from_template(): def inclusion_no_params_from_template():
"""Expected inclusion_no_params_from_template __doc__""" """Expected inclusion_no_params_from_template __doc__"""
return {"result": "inclusion_no_params_from_template - Expected result"} return {"result": "inclusion_no_params_from_template - Expected result"}
inclusion_no_params_from_template.anything = "Expected inclusion_no_params_from_template __dict__" inclusion_no_params_from_template.anything = "Expected inclusion_no_params_from_template __dict__"
@ -25,6 +29,8 @@ inclusion_no_params_from_template.anything = "Expected inclusion_no_params_from_
def inclusion_one_param(arg): def inclusion_one_param(arg):
"""Expected inclusion_one_param __doc__""" """Expected inclusion_one_param __doc__"""
return {"result": "inclusion_one_param - Expected result: %s" % arg} return {"result": "inclusion_one_param - Expected result: %s" % arg}
inclusion_one_param.anything = "Expected inclusion_one_param __dict__" inclusion_one_param.anything = "Expected inclusion_one_param __dict__"
@ -32,6 +38,8 @@ inclusion_one_param.anything = "Expected inclusion_one_param __dict__"
def inclusion_one_param_from_template(arg): def inclusion_one_param_from_template(arg):
"""Expected inclusion_one_param_from_template __doc__""" """Expected inclusion_one_param_from_template __doc__"""
return {"result": "inclusion_one_param_from_template - Expected result: %s" % arg} return {"result": "inclusion_one_param_from_template - Expected result: %s" % arg}
inclusion_one_param_from_template.anything = "Expected inclusion_one_param_from_template __dict__" inclusion_one_param_from_template.anything = "Expected inclusion_one_param_from_template __dict__"
@ -39,6 +47,8 @@ inclusion_one_param_from_template.anything = "Expected inclusion_one_param_from_
def inclusion_explicit_no_context(arg): def inclusion_explicit_no_context(arg):
"""Expected inclusion_explicit_no_context __doc__""" """Expected inclusion_explicit_no_context __doc__"""
return {"result": "inclusion_explicit_no_context - Expected result: %s" % arg} return {"result": "inclusion_explicit_no_context - Expected result: %s" % arg}
inclusion_explicit_no_context.anything = "Expected inclusion_explicit_no_context __dict__" inclusion_explicit_no_context.anything = "Expected inclusion_explicit_no_context __dict__"
@ -46,6 +56,8 @@ inclusion_explicit_no_context.anything = "Expected inclusion_explicit_no_context
def inclusion_explicit_no_context_from_template(arg): def inclusion_explicit_no_context_from_template(arg):
"""Expected inclusion_explicit_no_context_from_template __doc__""" """Expected inclusion_explicit_no_context_from_template __doc__"""
return {"result": "inclusion_explicit_no_context_from_template - Expected result: %s" % arg} return {"result": "inclusion_explicit_no_context_from_template - Expected result: %s" % arg}
inclusion_explicit_no_context_from_template.anything = "Expected inclusion_explicit_no_context_from_template __dict__" inclusion_explicit_no_context_from_template.anything = "Expected inclusion_explicit_no_context_from_template __dict__"
@ -53,6 +65,8 @@ inclusion_explicit_no_context_from_template.anything = "Expected inclusion_expli
def inclusion_no_params_with_context(context): def inclusion_no_params_with_context(context):
"""Expected inclusion_no_params_with_context __doc__""" """Expected inclusion_no_params_with_context __doc__"""
return {"result": "inclusion_no_params_with_context - Expected result (context value: %s)" % context['value']} return {"result": "inclusion_no_params_with_context - Expected result (context value: %s)" % context['value']}
inclusion_no_params_with_context.anything = "Expected inclusion_no_params_with_context __dict__" inclusion_no_params_with_context.anything = "Expected inclusion_no_params_with_context __dict__"
@ -64,6 +78,8 @@ def inclusion_no_params_with_context_from_template(context):
"inclusion_no_params_with_context_from_template - Expected result (context value: %s)" % context['value'] "inclusion_no_params_with_context_from_template - Expected result (context value: %s)" % context['value']
) )
} }
inclusion_no_params_with_context_from_template.anything = ( inclusion_no_params_with_context_from_template.anything = (
"Expected inclusion_no_params_with_context_from_template __dict__" "Expected inclusion_no_params_with_context_from_template __dict__"
) )
@ -75,6 +91,8 @@ def inclusion_params_and_context(context, arg):
return { return {
"result": "inclusion_params_and_context - Expected result (context value: %s): %s" % (context['value'], arg) "result": "inclusion_params_and_context - Expected result (context value: %s): %s" % (context['value'], arg)
} }
inclusion_params_and_context.anything = "Expected inclusion_params_and_context __dict__" inclusion_params_and_context.anything = "Expected inclusion_params_and_context __dict__"
@ -87,6 +105,8 @@ def inclusion_params_and_context_from_template(context, arg):
"(context value: %s): %s" % (context['value'], arg) "(context value: %s): %s" % (context['value'], arg)
) )
} }
inclusion_params_and_context_from_template.anything = "Expected inclusion_params_and_context_from_template __dict__" inclusion_params_and_context_from_template.anything = "Expected inclusion_params_and_context_from_template __dict__"
@ -94,6 +114,8 @@ inclusion_params_and_context_from_template.anything = "Expected inclusion_params
def inclusion_two_params(one, two): def inclusion_two_params(one, two):
"""Expected inclusion_two_params __doc__""" """Expected inclusion_two_params __doc__"""
return {"result": "inclusion_two_params - Expected result: %s, %s" % (one, two)} return {"result": "inclusion_two_params - Expected result: %s, %s" % (one, two)}
inclusion_two_params.anything = "Expected inclusion_two_params __dict__" inclusion_two_params.anything = "Expected inclusion_two_params __dict__"
@ -101,6 +123,8 @@ inclusion_two_params.anything = "Expected inclusion_two_params __dict__"
def inclusion_two_params_from_template(one, two): def inclusion_two_params_from_template(one, two):
"""Expected inclusion_two_params_from_template __doc__""" """Expected inclusion_two_params_from_template __doc__"""
return {"result": "inclusion_two_params_from_template - Expected result: %s, %s" % (one, two)} return {"result": "inclusion_two_params_from_template - Expected result: %s, %s" % (one, two)}
inclusion_two_params_from_template.anything = "Expected inclusion_two_params_from_template __dict__" inclusion_two_params_from_template.anything = "Expected inclusion_two_params_from_template __dict__"
@ -108,6 +132,8 @@ inclusion_two_params_from_template.anything = "Expected inclusion_two_params_fro
def inclusion_one_default(one, two='hi'): def inclusion_one_default(one, two='hi'):
"""Expected inclusion_one_default __doc__""" """Expected inclusion_one_default __doc__"""
return {"result": "inclusion_one_default - Expected result: %s, %s" % (one, two)} return {"result": "inclusion_one_default - Expected result: %s, %s" % (one, two)}
inclusion_one_default.anything = "Expected inclusion_one_default __dict__" inclusion_one_default.anything = "Expected inclusion_one_default __dict__"
@ -115,6 +141,8 @@ inclusion_one_default.anything = "Expected inclusion_one_default __dict__"
def inclusion_one_default_from_template(one, two='hi'): def inclusion_one_default_from_template(one, two='hi'):
"""Expected inclusion_one_default_from_template __doc__""" """Expected inclusion_one_default_from_template __doc__"""
return {"result": "inclusion_one_default_from_template - Expected result: %s, %s" % (one, two)} return {"result": "inclusion_one_default_from_template - Expected result: %s, %s" % (one, two)}
inclusion_one_default_from_template.anything = "Expected inclusion_one_default_from_template __dict__" inclusion_one_default_from_template.anything = "Expected inclusion_one_default_from_template __dict__"
@ -128,6 +156,8 @@ def inclusion_unlimited_args(one, two='hi', *args):
) )
) )
} }
inclusion_unlimited_args.anything = "Expected inclusion_unlimited_args __dict__" inclusion_unlimited_args.anything = "Expected inclusion_unlimited_args __dict__"
@ -141,6 +171,8 @@ def inclusion_unlimited_args_from_template(one, two='hi', *args):
) )
) )
} }
inclusion_unlimited_args_from_template.anything = "Expected inclusion_unlimited_args_from_template __dict__" inclusion_unlimited_args_from_template.anything = "Expected inclusion_unlimited_args_from_template __dict__"
@ -152,6 +184,8 @@ def inclusion_only_unlimited_args(*args):
', '.join(six.text_type(arg) for arg in args) ', '.join(six.text_type(arg) for arg in args)
) )
} }
inclusion_only_unlimited_args.anything = "Expected inclusion_only_unlimited_args __dict__" inclusion_only_unlimited_args.anything = "Expected inclusion_only_unlimited_args __dict__"
@ -163,6 +197,8 @@ def inclusion_only_unlimited_args_from_template(*args):
', '.join(six.text_type(arg) for arg in args) ', '.join(six.text_type(arg) for arg in args)
) )
} }
inclusion_only_unlimited_args_from_template.anything = "Expected inclusion_only_unlimited_args_from_template __dict__" inclusion_only_unlimited_args_from_template.anything = "Expected inclusion_only_unlimited_args_from_template __dict__"
@ -170,6 +206,8 @@ inclusion_only_unlimited_args_from_template.anything = "Expected inclusion_only_
def inclusion_tag_use_l10n(context): def inclusion_tag_use_l10n(context):
"""Expected inclusion_tag_use_l10n __doc__""" """Expected inclusion_tag_use_l10n __doc__"""
return {} return {}
inclusion_tag_use_l10n.anything = "Expected inclusion_tag_use_l10n __dict__" inclusion_tag_use_l10n.anything = "Expected inclusion_tag_use_l10n __dict__"
@ -182,6 +220,8 @@ def inclusion_unlimited_args_kwargs(one, two='hi', *args, **kwargs):
', '.join(six.text_type(arg) for arg in [one, two] + list(args)), ', '.join(six.text_type(arg) for arg in [one, two] + list(args)),
', '.join('%s=%s' % (k, v) for (k, v) in sorted_kwarg) ', '.join('%s=%s' % (k, v) for (k, v) in sorted_kwarg)
)} )}
inclusion_unlimited_args_kwargs.anything = "Expected inclusion_unlimited_args_kwargs __dict__" inclusion_unlimited_args_kwargs.anything = "Expected inclusion_unlimited_args_kwargs __dict__"
@ -189,6 +229,8 @@ inclusion_unlimited_args_kwargs.anything = "Expected inclusion_unlimited_args_kw
def inclusion_tag_without_context_parameter(arg): def inclusion_tag_without_context_parameter(arg):
"""Expected inclusion_tag_without_context_parameter __doc__""" """Expected inclusion_tag_without_context_parameter __doc__"""
return {} return {}
inclusion_tag_without_context_parameter.anything = "Expected inclusion_tag_without_context_parameter __dict__" inclusion_tag_without_context_parameter.anything = "Expected inclusion_tag_without_context_parameter __dict__"

Some files were not shown because too many files have changed in this diff Show More