Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Merge pull request #1854 from rayashmanjr/master

Correct flake8 E302 violations
  • Loading branch information...
commit 393cdbfaa2d47c85f6764e80600de48f26f43327 2 parents 3bc0d46 + e459893
Alex Gaynor authored November 02, 2013
3  django/test/testcases.py
@@ -61,9 +61,11 @@ def to_list(value):
61 61
 real_leave_transaction_management = transaction.leave_transaction_management
62 62
 real_abort = transaction.abort
63 63
 
  64
+
64 65
 def nop(*args, **kwargs):
65 66
     return
66 67
 
  68
+
67 69
 def disable_transaction_methods():
68 70
     transaction.commit = nop
69 71
     transaction.rollback = nop
@@ -71,6 +73,7 @@ def disable_transaction_methods():
71 73
     transaction.leave_transaction_management = nop
72 74
     transaction.abort = nop
73 75
 
  76
+
74 77
 def restore_transaction_methods():
75 78
     transaction.commit = real_commit
76 79
     transaction.rollback = real_rollback
1  django/utils/_os.py
@@ -53,6 +53,7 @@ def npath(path):
53 53
         return path.encode(fs_encoding)
54 54
     return path
55 55
 
  56
+
56 57
 def safe_join(base, *paths):
57 58
     """
58 59
     Joins one or more path components to the base path component intelligently.
8  django/utils/autoreload.py
@@ -119,6 +119,7 @@ def gen_filenames():
119 119
         if os.path.exists(filename):
120 120
             yield filename
121 121
 
  122
+
122 123
 def inotify_code_changed():
123 124
     """
124 125
     Checks for changed code using inotify. After being called
@@ -149,6 +150,7 @@ def update_watch(sender=None, **kwargs):
149 150
     # If we are here the code must have changed.
150 151
     return True
151 152
 
  153
+
152 154
 def kqueue_code_changed():
153 155
     """
154 156
     Checks for changed code using kqueue. After being called
@@ -193,6 +195,7 @@ def kqueue_code_changed():
193 195
 
194 196
     return True
195 197
 
  198
+
196 199
 def code_changed():
197 200
     global _mtimes, _win
198 201
     for filename in gen_filenames():
@@ -212,6 +215,7 @@ def code_changed():
212 215
             return True
213 216
     return False
214 217
 
  218
+
215 219
 def check_errors(fn):
216 220
     def wrapper(*args, **kwargs):
217 221
         try:
@@ -233,6 +237,7 @@ def wrapper(*args, **kwargs):
233 237
 
234 238
     return wrapper
235 239
 
  240
+
236 241
 def ensure_echo_on():
237 242
     if termios:
238 243
         fd = sys.stdin
@@ -248,6 +253,7 @@ def ensure_echo_on():
248 253
                 if old_handler is not None:
249 254
                     signal.signal(signal.SIGTTOU, old_handler)
250 255
 
  256
+
251 257
 def reloader_thread():
252 258
     ensure_echo_on()
253 259
     if USE_INOTIFY:
@@ -273,6 +279,7 @@ def restart_with_reloader():
273 279
         if exit_code != 3:
274 280
             return exit_code
275 281
 
  282
+
276 283
 def python_reloader(main_func, args, kwargs):
277 284
     if os.environ.get("RUN_MAIN") == "true":
278 285
         thread.start_new_thread(main_func, args, kwargs)
@@ -290,6 +297,7 @@ def python_reloader(main_func, args, kwargs):
290 297
         except KeyboardInterrupt:
291 298
             pass
292 299
 
  300
+
293 301
 def jython_reloader(main_func, args, kwargs):
294 302
     from _systemrestart import SystemRestart
295 303
     thread.start_new_thread(main_func, args)
12  django/utils/cache.py
@@ -31,6 +31,7 @@
31 31
 
32 32
 cc_delim_re = re.compile(r'\s*,\s*')
33 33
 
  34
+
34 35
 def patch_cache_control(response, **kwargs):
35 36
     """
36 37
     This function patches the Cache-Control header by adding all
@@ -79,6 +80,7 @@ def dictvalue(t):
79 80
     cc = ', '.join(dictvalue(el) for el in cc.items())
80 81
     response['Cache-Control'] = cc
81 82
 
  83
+
82 84
 def get_max_age(response):
83 85
     """
84 86
     Returns the max-age from the response Cache-Control header as an integer
@@ -94,11 +96,13 @@ def get_max_age(response):
94 96
         except (ValueError, TypeError):
95 97
             pass
96 98
 
  99
+
97 100
 def _set_response_etag(response):
98 101
     if not response.streaming:
99 102
         response['ETag'] = '"%s"' % hashlib.md5(response.content).hexdigest()
100 103
     return response
101 104
 
  105
+
102 106
 def patch_response_headers(response, cache_timeout=None):
103 107
     """
104 108
     Adds some useful headers to the given HttpResponse object:
@@ -124,12 +128,14 @@ def patch_response_headers(response, cache_timeout=None):
124 128
         response['Expires'] = http_date(time.time() + cache_timeout)
125 129
     patch_cache_control(response, max_age=cache_timeout)
126 130
 
  131
+
127 132
 def add_never_cache_headers(response):
128 133
     """
129 134
     Adds headers to a response to indicate that a page should never be cached.
130 135
     """
131 136
     patch_response_headers(response, cache_timeout=-1)
132 137
 
  138
+
133 139
 def patch_vary_headers(response, newheaders):
134 140
     """
135 141
     Adds (or updates) the "Vary" header in the given HttpResponse object.
@@ -149,6 +155,7 @@ def patch_vary_headers(response, newheaders):
149 155
                           if newheader.lower() not in existing_headers]
150 156
     response['Vary'] = ', '.join(vary_headers + additional_headers)
151 157
 
  158
+
152 159
 def has_vary_header(response, header_query):
153 160
     """
154 161
     Checks to see if the response has a given header name in its Vary header.
@@ -159,6 +166,7 @@ def has_vary_header(response, header_query):
159 166
     existing_headers = set(header.lower() for header in vary_headers)
160 167
     return header_query.lower() in existing_headers
161 168
 
  169
+
162 170
 def _i18n_cache_key_suffix(request, cache_key):
163 171
     """If necessary, adds the current locale or time zone to the cache key."""
164 172
     if settings.USE_I18N or settings.USE_L10N:
@@ -175,6 +183,7 @@ def _i18n_cache_key_suffix(request, cache_key):
175 183
         cache_key += '.%s' % tz_name.encode('ascii', 'ignore').decode('ascii').replace(' ', '_')
176 184
     return cache_key
177 185
 
  186
+
178 187
 def _generate_cache_key(request, method, headerlist, key_prefix):
179 188
     """Returns a cache key from the headers given in the header list."""
180 189
     ctx = hashlib.md5()
@@ -187,6 +196,7 @@ def _generate_cache_key(request, method, headerlist, key_prefix):
187 196
         key_prefix, method, path.hexdigest(), ctx.hexdigest())
188 197
     return _i18n_cache_key_suffix(request, cache_key)
189 198
 
  199
+
190 200
 def _generate_cache_header_key(key_prefix, request):
191 201
     """Returns a cache key for the header cache."""
192 202
     path = hashlib.md5(force_bytes(iri_to_uri(request.get_full_path())))
@@ -194,6 +204,7 @@ def _generate_cache_header_key(key_prefix, request):
194 204
         key_prefix, path.hexdigest())
195 205
     return _i18n_cache_key_suffix(request, cache_key)
196 206
 
  207
+
197 208
 def get_cache_key(request, key_prefix=None, method='GET', cache=None):
198 209
     """
199 210
     Returns a cache key based on the request path and query. It can be used
@@ -215,6 +226,7 @@ def get_cache_key(request, key_prefix=None, method='GET', cache=None):
215 226
     else:
216 227
         return None
217 228
 
  229
+
218 230
 def learn_cache_key(request, response, cache_timeout=None, key_prefix=None, cache=None):
219 231
     """
220 232
     Learns what headers to take into account for some request path from the
6  django/utils/datastructures.py
@@ -3,6 +3,7 @@
3 3
 from collections import OrderedDict
4 4
 from django.utils import six
5 5
 
  6
+
6 7
 class MergeDict(object):
7 8
     """
8 9
     A simple class for creating new "virtual" dictionaries that actually look
@@ -117,6 +118,7 @@ def __repr__(self):
117 118
         dictreprs = ', '.join(repr(d) for d in self.dicts)
118 119
         return '%s(%s)' % (self.__class__.__name__, dictreprs)
119 120
 
  121
+
120 122
 class SortedDict(dict):
121 123
     """
122 124
     A dictionary that keeps its keys in the order in which they're inserted.
@@ -239,6 +241,7 @@ def clear(self):
239 241
         super(SortedDict, self).clear()
240 242
         self.keyOrder = []
241 243
 
  244
+
242 245
 class OrderedSet(object):
243 246
     """
244 247
     A set which keeps the ordering of the inserted items.
@@ -269,9 +272,11 @@ def __contains__(self, item):
269 272
     def __nonzero__(self):
270 273
         return bool(self.dict)
271 274
 
  275
+
272 276
 class MultiValueDictKeyError(KeyError):
273 277
     pass
274 278
 
  279
+
275 280
 class MultiValueDict(dict):
276 281
     """
277 282
     A subclass of dictionary customized to handle multiple values for the
@@ -504,6 +509,7 @@ def complain(self, *wargs, **kwargs):
504 509
     sort = complain
505 510
     reverse = complain
506 511
 
  512
+
507 513
 class DictWrapper(dict):
508 514
     """
509 515
     Wraps accesses to a dictionary so that certain values (those starting with
2  django/utils/dateformat.py
@@ -26,6 +26,7 @@
26 26
 re_formatchars = re.compile(r'(?<!\\)([aAbBcdDeEfFgGhHiIjlLmMnNoOPrsStTUuwWyYzZ])')
27 27
 re_escaped = re.compile(r'\\(.)')
28 28
 
  29
+
29 30
 class Formatter(object):
30 31
     def format(self, formatstr):
31 32
         pieces = []
@@ -36,6 +37,7 @@ def format(self, formatstr):
36 37
                 pieces.append(re_escaped.sub(r'\1', piece))
37 38
         return ''.join(pieces)
38 39
 
  40
+
39 41
 class TimeFormat(Formatter):
40 42
 
41 43
     def __init__(self, obj):
2  django/utils/dateparse.py
@@ -39,6 +39,7 @@ def parse_date(value):
39 39
         kw = dict((k, int(v)) for k, v in six.iteritems(match.groupdict()))
40 40
         return datetime.date(**kw)
41 41
 
  42
+
42 43
 def parse_time(value):
43 44
     """Parses a string and return a datetime.time.
44 45
 
@@ -56,6 +57,7 @@ def parse_time(value):
56 57
         kw = dict((k, int(v)) for k, v in six.iteritems(kw) if v is not None)
57 58
         return datetime.time(**kw)
58 59
 
  60
+
59 61
 def parse_datetime(value):
60 62
     """Parses a string and return a datetime.datetime.
61 63
 
4  django/utils/datetime_safe.py
@@ -30,10 +30,12 @@ def combine(cls, date, time):
30 30
     def date(self):
31 31
         return date(self.year, self.month, self.day)
32 32
 
  33
+
33 34
 def new_date(d):
34 35
     "Generate a safe date from a datetime.date object."
35 36
     return date(d.year, d.month, d.day)
36 37
 
  38
+
37 39
 def new_datetime(d):
38 40
     """
39 41
     Generate a safe datetime from a datetime.date or datetime.datetime object.
@@ -47,6 +49,7 @@ def new_datetime(d):
47 49
 # Allowed if there's an even number of "%"s because they are escaped.
48 50
 _illegal_formatting = re.compile(r"((^|[^%])(%%)*%[sy])")
49 51
 
  52
+
50 53
 def _findall(text, substr):
51 54
     # Also finds overlaps
52 55
     sites = []
@@ -59,6 +62,7 @@ def _findall(text, substr):
59 62
         i = j + 1
60 63
     return sites
61 64
 
  65
+
62 66
 def strftime(dt, fmt):
63 67
     if dt.year >= 1900:
64 68
         return super(type(dt), dt).strftime(fmt)
7  django/utils/dictconfig.py
@@ -32,6 +32,7 @@
32 32
 
33 33
 IDENTIFIER = re.compile('^[a-z_][a-z0-9_]*$', re.I)
34 34
 
  35
+
35 36
 def valid_ident(s):
36 37
     m = IDENTIFIER.match(s)
37 38
     if not m:
@@ -65,6 +66,7 @@ def _checkLevel(level):
65 66
 # Each wrapper should have a configurator attribute holding the actual
66 67
 # configurator to use for conversion.
67 68
 
  69
+
68 70
 class ConvertingDict(dict):
69 71
     """A converting dictionary wrapper."""
70 72
 
@@ -102,6 +104,7 @@ def pop(self, key, default=None):
102 104
                 result.key = key
103 105
         return result
104 106
 
  107
+
105 108
 class ConvertingList(list):
106 109
     """A converting list wrapper."""
107 110
     def __getitem__(self, key):
@@ -125,6 +128,7 @@ def pop(self, idx=-1):
125 128
                 result.parent = self
126 129
         return result
127 130
 
  131
+
128 132
 class ConvertingTuple(tuple):
129 133
     """A converting tuple wrapper."""
130 134
     def __getitem__(self, key):
@@ -137,6 +141,7 @@ def __getitem__(self, key):
137 141
                 result.key = key
138 142
         return result
139 143
 
  144
+
140 145
 class BaseConfigurator(object):
141 146
     """
142 147
     The configurator base class which defines some useful defaults.
@@ -270,6 +275,7 @@ def as_tuple(self, value):
270 275
             value = tuple(value)
271 276
         return value
272 277
 
  278
+
273 279
 class DictConfigurator(BaseConfigurator):
274 280
     """
275 281
     Configure logging using a dictionary-like object to describe the
@@ -555,6 +561,7 @@ def configure_root(self, config, incremental=False):
555 561
 
556 562
 dictConfigClass = DictConfigurator
557 563
 
  564
+
558 565
 def dictConfig(config):
559 566
     """Configure logging using a dictionary."""
560 567
     dictConfigClass(config).configure()
7  django/utils/encoding.py
@@ -38,6 +38,7 @@ def python_2_unicode_compatible(klass):
38 38
         klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
39 39
     return klass
40 40
 
  41
+
41 42
 def smart_text(s, encoding='utf-8', strings_only=False, errors='strict'):
42 43
     """
43 44
     Returns a text object representing 's' -- unicode on Python 2 and str on
@@ -50,6 +51,7 @@ def smart_text(s, encoding='utf-8', strings_only=False, errors='strict'):
50 51
         return s
51 52
     return force_text(s, encoding, strings_only, errors)
52 53
 
  54
+
53 55
 def is_protected_type(obj):
54 56
     """Determine if the object instance is of a protected type.
55 57
 
@@ -59,6 +61,7 @@ def is_protected_type(obj):
59 61
     return isinstance(obj, six.integer_types + (type(None), float, Decimal,
60 62
         datetime.datetime, datetime.date, datetime.time))
61 63
 
  64
+
62 65
 def force_text(s, encoding='utf-8', strings_only=False, errors='strict'):
63 66
     """
64 67
     Similar to smart_text, except that lazy instances are resolved to
@@ -100,6 +103,7 @@ def force_text(s, encoding='utf-8', strings_only=False, errors='strict'):
100 103
                     errors) for arg in s])
101 104
     return s
102 105
 
  106
+
103 107
 def smart_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
104 108
     """
105 109
     Returns a bytestring version of 's', encoded as specified in 'encoding'.
@@ -168,6 +172,7 @@ def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
168 172
 Apply force_text in Python 3 and force_bytes in Python 2.
169 173
 """
170 174
 
  175
+
171 176
 def iri_to_uri(iri):
172 177
     """
173 178
     Convert an Internationalized Resource Identifier (IRI) portion to a URI
@@ -195,6 +200,7 @@ def iri_to_uri(iri):
195 200
         return iri
196 201
     return quote(force_bytes(iri), safe=b"/#%[]=:;$&()+,!?*@'~")
197 202
 
  203
+
198 204
 def filepath_to_uri(path):
199 205
     """Convert a file system path to a URI portion that is suitable for
200 206
     inclusion in a URL.
@@ -214,6 +220,7 @@ def filepath_to_uri(path):
214 220
     # some flexibility for hardcoding separators.
215 221
     return quote(force_bytes(path).replace(b"\\", b"/"), safe=b"/~!*()'")
216 222
 
  223
+
217 224
 def get_system_encoding():
218 225
     """
219 226
     The encoding of the default system locale but falls back to the given
8  django/utils/feedgenerator.py
@@ -54,6 +54,7 @@ def rfc2822_date(date):
54 54
     else:
55 55
         return time_str + '-0000'
56 56
 
  57
+
57 58
 def rfc3339_date(date):
58 59
     # Support datetime objects older than 1900
59 60
     date = datetime_safe.new_datetime(date)
@@ -68,6 +69,7 @@ def rfc3339_date(date):
68 69
     else:
69 70
         return time_str + 'Z'
70 71
 
  72
+
71 73
 def get_tag_uri(url, date):
72 74
     """
73 75
     Creates a TagURI.
@@ -80,6 +82,7 @@ def get_tag_uri(url, date):
80 82
         d = ',%s' % datetime_safe.new_datetime(date).strftime('%Y-%m-%d')
81 83
     return 'tag:%s%s:%s/%s' % (bits.hostname, d, bits.path, bits.fragment)
82 84
 
  85
+
83 86
 class SyndicationFeed(object):
84 87
     "Base class for all syndication feeds. Subclasses should provide write()"
85 88
     def __init__(self, title, link, description, language=None, author_email=None,
@@ -205,6 +208,7 @@ def latest_post_date(self):
205 208
 
206 209
         return latest_date or datetime.datetime.now()
207 210
 
  211
+
208 212
 class Enclosure(object):
209 213
     "Represents an RSS enclosure"
210 214
     def __init__(self, url, length, mime_type):
@@ -212,6 +216,7 @@ def __init__(self, url, length, mime_type):
212 216
         self.length, self.mime_type = length, mime_type
213 217
         self.url = iri_to_uri(url)
214 218
 
  219
+
215 220
 class RssFeed(SyndicationFeed):
216 221
     mime_type = 'application/rss+xml; charset=utf-8'
217 222
 
@@ -255,6 +260,7 @@ def add_root_elements(self, handler):
255 260
     def endChannelElement(self, handler):
256 261
         handler.endElement("channel")
257 262
 
  263
+
258 264
 class RssUserland091Feed(RssFeed):
259 265
     _version = "0.91"
260 266
 
@@ -264,6 +270,7 @@ def add_item_elements(self, handler, item):
264 270
         if item['description'] is not None:
265 271
             handler.addQuickElement("description", item['description'])
266 272
 
  273
+
267 274
 class Rss201rev2Feed(RssFeed):
268 275
     # Spec: http://blogs.law.harvard.edu/tech/rss
269 276
     _version = "2.0"
@@ -306,6 +313,7 @@ def add_item_elements(self, handler, item):
306 313
         for cat in item['categories']:
307 314
             handler.addQuickElement("category", cat)
308 315
 
  316
+
309 317
 class Atom1Feed(SyndicationFeed):
310 318
     # Spec: http://atompub.org/2005/07/11/draft-ietf-atompub-format-10.html
311 319
     mime_type = 'application/atom+xml; charset=utf-8'
10  django/utils/formats.py
@@ -30,6 +30,7 @@
30 30
     ),
31 31
 }
32 32
 
  33
+
33 34
 def reset_format_cache():
34 35
     """Clear any cached formats.
35 36
 
@@ -40,6 +41,7 @@ def reset_format_cache():
40 41
     _format_cache = {}
41 42
     _format_modules_cache = {}
42 43
 
  44
+
43 45
 def iter_format_modules(lang, format_module_path=None):
44 46
     """
45 47
     Does the heavy lifting of finding format modules.
@@ -60,6 +62,7 @@ def iter_format_modules(lang, format_module_path=None):
60 62
                 except ImportError:
61 63
                     pass
62 64
 
  65
+
63 66
 def get_format_modules(lang=None, reverse=False):
64 67
     """
65 68
     Returns a list of the format modules found
@@ -71,6 +74,7 @@ def get_format_modules(lang=None, reverse=False):
71 74
         return list(reversed(modules))
72 75
     return modules
73 76
 
  77
+
74 78
 def get_format(format_type, lang=None, use_l10n=None):
75 79
     """
76 80
     For a specific format type, returns the format for the current
@@ -110,6 +114,7 @@ def get_format(format_type, lang=None, use_l10n=None):
110 114
 
111 115
 get_format_lazy = lazy(get_format, six.text_type, list, tuple)
112 116
 
  117
+
113 118
 def date_format(value, format=None, use_l10n=None):
114 119
     """
115 120
     Formats a datetime.date or datetime.datetime object using a
@@ -120,6 +125,7 @@ def date_format(value, format=None, use_l10n=None):
120 125
     """
121 126
     return dateformat.format(value, get_format(format or 'DATE_FORMAT', use_l10n=use_l10n))
122 127
 
  128
+
123 129
 def time_format(value, format=None, use_l10n=None):
124 130
     """
125 131
     Formats a datetime.time object using a localizable format
@@ -129,6 +135,7 @@ def time_format(value, format=None, use_l10n=None):
129 135
     """
130 136
     return dateformat.time_format(value, get_format(format or 'TIME_FORMAT', use_l10n=use_l10n))
131 137
 
  138
+
132 139
 def number_format(value, decimal_pos=None, use_l10n=None, force_grouping=False):
133 140
     """
134 141
     Formats a numeric value using localization settings
@@ -149,6 +156,7 @@ def number_format(value, decimal_pos=None, use_l10n=None, force_grouping=False):
149 156
         force_grouping=force_grouping
150 157
     )
151 158
 
  159
+
152 160
 def localize(value, use_l10n=None):
153 161
     """
154 162
     Checks if value is a localizable type (date, number...) and returns it
@@ -170,6 +178,7 @@ def localize(value, use_l10n=None):
170 178
     else:
171 179
         return value
172 180
 
  181
+
173 182
 def localize_input(value, default=None):
174 183
     """
175 184
     Checks if an input value is a localizable type and returns it
@@ -190,6 +199,7 @@ def localize_input(value, default=None):
190 199
         return value.strftime(format)
191 200
     return value
192 201
 
  202
+
193 203
 def sanitize_separators(value):
194 204
     """
195 205
     Sanitizes a value according to the current decimal and
11  django/utils/html.py
@@ -72,6 +72,7 @@ def conditional_escape(text):
72 72
     else:
73 73
         return escape(text)
74 74
 
  75
+
75 76
 def format_html(format_string, *args, **kwargs):
76 77
     """
77 78
     Similar to str.format, but passes all arguments through conditional_escape,
@@ -83,6 +84,7 @@ def format_html(format_string, *args, **kwargs):
83 84
                         six.iteritems(kwargs))
84 85
     return mark_safe(format_string.format(*args_safe, **kwargs_safe))
85 86
 
  87
+
86 88
 def format_html_join(sep, format_string, args_generator):
87 89
     """
88 90
     A wrapper of format_html, for the common case of a group of arguments that
@@ -133,6 +135,7 @@ def handle_charref(self, name):
133 135
     def get_data(self):
134 136
         return ''.join(self.fed)
135 137
 
  138
+
136 139
 def strip_tags(value):
137 140
     """Returns the given HTML with all tags stripped."""
138 141
     s = MLStripper()
@@ -145,6 +148,7 @@ def strip_tags(value):
145 148
         return s.get_data()
146 149
 strip_tags = allow_lazy(strip_tags)
147 150
 
  151
+
148 152
 def remove_tags(html, tags):
149 153
     """Returns the given HTML with given tags removed."""
150 154
     tags = [re.escape(tag) for tag in tags.split()]
@@ -156,21 +160,25 @@ def remove_tags(html, tags):
156 160
     return html
157 161
 remove_tags = allow_lazy(remove_tags, six.text_type)
158 162
 
  163
+
159 164
 def strip_spaces_between_tags(value):
160 165
     """Returns the given HTML with spaces between tags removed."""
161 166
     return re.sub(r'>\s+<', '><', force_text(value))
162 167
 strip_spaces_between_tags = allow_lazy(strip_spaces_between_tags, six.text_type)
163 168
 
  169
+
164 170
 def strip_entities(value):
165 171
     """Returns the given HTML with all entities (&something;) stripped."""
166 172
     return re.sub(r'&(?:\w+|#\d+);', '', force_text(value))
167 173
 strip_entities = allow_lazy(strip_entities, six.text_type)
168 174
 
  175
+
169 176
 def fix_ampersands(value):
170 177
     """Returns the given HTML with all unencoded ampersands encoded correctly."""
171 178
     return unencoded_ampersands_re.sub('&amp;', force_text(value))
172 179
 fix_ampersands = allow_lazy(fix_ampersands, six.text_type)
173 180
 
  181
+
174 182
 def smart_urlquote(url):
175 183
     "Quotes a URL if it isn't already quoted."
176 184
     # Handle IDN before quoting.
@@ -192,6 +200,7 @@ def smart_urlquote(url):
192 200
 
193 201
     return force_text(url)
194 202
 
  203
+
195 204
 def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
196 205
     """
197 206
     Converts any URLs in text into clickable links.
@@ -269,6 +278,7 @@ def trim_url(x, limit=trim_url_limit):
269 278
     return ''.join(words)
270 279
 urlize = allow_lazy(urlize, six.text_type)
271 280
 
  281
+
272 282
 def clean_html(text):
273 283
     """
274 284
     Clean the given HTML.  Specifically, do the following:
@@ -304,6 +314,7 @@ def replace_p_tags(match):
304 314
     return text
305 315
 clean_html = allow_lazy(clean_html, six.text_type)
306 316
 
  317
+
307 318
 def avoid_wrapping(value):
308 319
     """
309 320
     Avoid text wrapping in the middle of a phrase by adding non-breaking
17  django/utils/http.py
@@ -30,6 +30,7 @@
30 30
 RFC850_DATE = re.compile(r'^\w{6,9}, %s-%s-%s %s GMT$' % (__D, __M, __Y2, __T))
31 31
 ASCTIME_DATE = re.compile(r'^\w{3} %s %s %s %s$' % (__M, __D2, __T, __Y))
32 32
 
  33
+
33 34
 def urlquote(url, safe='/'):
34 35
     """
35 36
     A version of Python's urllib.quote() function that can operate on unicode
@@ -40,6 +41,7 @@ def urlquote(url, safe='/'):
40 41
     return force_text(quote(force_str(url), force_str(safe)))
41 42
 urlquote = allow_lazy(urlquote, six.text_type)
42 43
 
  44
+
43 45
 def urlquote_plus(url, safe=''):
44 46
     """
45 47
     A version of Python's urllib.quote_plus() function that can operate on
@@ -50,6 +52,7 @@ def urlquote_plus(url, safe=''):
50 52
     return force_text(quote_plus(force_str(url), force_str(safe)))
51 53
 urlquote_plus = allow_lazy(urlquote_plus, six.text_type)
52 54
 
  55
+
53 56
 def urlunquote(quoted_url):
54 57
     """
55 58
     A wrapper for Python's urllib.unquote() function that can operate on
@@ -58,6 +61,7 @@ def urlunquote(quoted_url):
58 61
     return force_text(unquote(force_str(quoted_url)))
59 62
 urlunquote = allow_lazy(urlunquote, six.text_type)
60 63
 
  64
+
61 65
 def urlunquote_plus(quoted_url):
62 66
     """
63 67
     A wrapper for Python's urllib.unquote_plus() function that can operate on
@@ -66,6 +70,7 @@ def urlunquote_plus(quoted_url):
66 70
     return force_text(unquote_plus(force_str(quoted_url)))
67 71
 urlunquote_plus = allow_lazy(urlunquote_plus, six.text_type)
68 72
 
  73
+
69 74
 def urlencode(query, doseq=0):
70 75
     """
71 76
     A version of Python's urllib.urlencode() function that can operate on
@@ -82,6 +87,7 @@ def urlencode(query, doseq=0):
82 87
             for k, v in query],
83 88
         doseq)
84 89
 
  90
+
85 91
 def cookie_date(epoch_seconds=None):
86 92
     """
87 93
     Formats the time to ensure compatibility with Netscape's cookie standard.
@@ -95,6 +101,7 @@ def cookie_date(epoch_seconds=None):
95 101
     rfcdate = formatdate(epoch_seconds)
96 102
     return '%s-%s-%s GMT' % (rfcdate[:7], rfcdate[8:11], rfcdate[12:25])
97 103
 
  104
+
98 105
 def http_date(epoch_seconds=None):
99 106
     """
100 107
     Formats the time to match the RFC1123 date format as specified by HTTP
@@ -108,6 +115,7 @@ def http_date(epoch_seconds=None):
108 115
     """
109 116
     return formatdate(epoch_seconds, usegmt=True)
110 117
 
  118
+
111 119
 def parse_http_date(date):
112 120
     """
113 121
     Parses a date format as specified by HTTP RFC2616 section 3.3.1.
@@ -143,6 +151,7 @@ def parse_http_date(date):
143 151
     except Exception:
144 152
         six.reraise(ValueError, ValueError("%r is not a valid date" % date), sys.exc_info()[2])
145 153
 
  154
+
146 155
 def parse_http_date_safe(date):
147 156
     """
148 157
     Same as parse_http_date, but returns None if the input is invalid.
@@ -152,6 +161,7 @@ def parse_http_date_safe(date):
152 161
     except Exception:
153 162
         pass
154 163
 
  164
+
155 165
 # Base 36 functions: useful for generating compact URLs
156 166
 
157 167
 def base36_to_int(s):
@@ -171,6 +181,7 @@ def base36_to_int(s):
171 181
         raise ValueError("Base36 input too large")
172 182
     return value
173 183
 
  184
+
174 185
 def int_to_base36(i):
175 186
     """
176 187
     Converts an integer to a base36 string
@@ -199,6 +210,7 @@ def int_to_base36(i):
199 210
         factor -= 1
200 211
     return ''.join(base36)
201 212
 
  213
+
202 214
 def urlsafe_base64_encode(s):
203 215
     """
204 216
     Encodes a bytestring in base64 for use in URLs, stripping any trailing
@@ -206,6 +218,7 @@ def urlsafe_base64_encode(s):
206 218
     """
207 219
     return base64.urlsafe_b64encode(s).rstrip(b'\n=')
208 220
 
  221
+
209 222
 def urlsafe_base64_decode(s):
210 223
     """
211 224
     Decodes a base64 encoded string, adding back any trailing equal signs that
@@ -217,6 +230,7 @@ def urlsafe_base64_decode(s):
217 230
     except (LookupError, BinasciiError) as e:
218 231
         raise ValueError(e)
219 232
 
  233
+
220 234
 def parse_etags(etag_str):
221 235
     """
222 236
     Parses a string with one or several etags passed in If-None-Match and
@@ -230,12 +244,14 @@ def parse_etags(etag_str):
230 244
     etags = [e.encode('ascii').decode('unicode_escape') for e in etags]
231 245
     return etags
232 246
 
  247
+
233 248
 def quote_etag(etag):
234 249
     """
235 250
     Wraps a string in double quotes escaping contents as necessary.
236 251
     """
237 252
     return '"%s"' % etag.replace('\\', '\\\\').replace('"', '\\"')
238 253
 
  254
+
239 255
 def same_origin(url1, url2):
240 256
     """
241 257
     Checks if two URLs are 'same-origin'
@@ -246,6 +262,7 @@ def same_origin(url1, url2):
246 262
     except ValueError:
247 263
         return False
248 264
 
  265
+
249 266
 def is_safe_url(url, host=None):
250 267
     """
251 268
     Return ``True`` if the url is a safe redirection (i.e. it doesn't point to
5  django/utils/regex_helper.py
@@ -202,6 +202,7 @@ def normalize(pattern):
202 202
 
203 203
     return list(zip(*flatten_result(result)))
204 204
 
  205
+
205 206
 def next_char(input_iter):
206 207
     """
207 208
     An iterator that yields the next character from "pattern_iter", respecting
@@ -222,6 +223,7 @@ def next_char(input_iter):
222 223
             continue
223 224
         yield representative, True
224 225
 
  226
+
225 227
 def walk_to_end(ch, input_iter):
226 228
     """
227 229
     The iterator is currently inside a capturing group. We want to walk to the
@@ -242,6 +244,7 @@ def walk_to_end(ch, input_iter):
242 244
                 return
243 245
             nesting -= 1
244 246
 
  247
+
245 248
 def get_quantifier(ch, input_iter):
246 249
     """
247 250
     Parse a quantifier from the input, where "ch" is the first character in the
@@ -278,6 +281,7 @@ def get_quantifier(ch, input_iter):
278 281
         ch = None
279 282
     return int(values[0]), ch
280 283
 
  284
+
281 285
 def contains(source, inst):
282 286
     """
283 287
     Returns True if the "source" contains an instance of "inst". False,
@@ -291,6 +295,7 @@ def contains(source, inst):
291 295
                 return True
292 296
     return False
293 297
 
  298
+
294 299
 def flatten_result(source):
295 300
     """
296 301
     Turns the given source sequence into a list of reg-exp possibilities and
5  django/utils/safestring.py
@@ -32,6 +32,7 @@ class EscapeText(six.text_type, EscapeData):
32 32
     # backwards compatibility for Python 2
33 33
     EscapeUnicode = EscapeText
34 34
 
  35
+
35 36
 class SafeData(object):
36 37
     def __html__(self):
37 38
         """
@@ -41,6 +42,7 @@ def __html__(self):
41 42
         """
42 43
         return self
43 44
 
  45
+
44 46
 class SafeBytes(bytes, SafeData):
45 47
     """
46 48
     A bytes subclass that has been specifically marked as "safe" (requires no
@@ -75,6 +77,7 @@ def _proxy_method(self, *args, **kwargs):
75 77
 
76 78
     decode = curry(_proxy_method, method=bytes.decode)
77 79
 
  80
+
78 81
 class SafeText(six.text_type, SafeData):
79 82
     """
80 83
     A unicode (Python 2) / str (Python 3) subclass that has been specifically
@@ -114,6 +117,7 @@ def _proxy_method(self, *args, **kwargs):
114 117
     # backwards compatibility for Python 2
115 118
     SafeUnicode = SafeText
116 119
 
  120
+
117 121
 def mark_safe(s):
118 122
     """
119 123
     Explicitly mark a string as safe for (HTML) output purposes. The returned
@@ -129,6 +133,7 @@ def mark_safe(s):
129 133
         return SafeText(s)
130 134
     return SafeString(str(s))
131 135
 
  136
+
132 137
 def mark_for_escaping(s):
133 138
     """
134 139
     Explicitly mark a string as requiring HTML escaping upon output. Has no
4  django/utils/six.py
@@ -428,14 +428,17 @@ def iterkeys(d, **kw):
428 428
     """Return an iterator over the keys of a dictionary."""
429 429
     return iter(getattr(d, _iterkeys)(**kw))
430 430
 
  431
+
431 432
 def itervalues(d, **kw):
432 433
     """Return an iterator over the values of a dictionary."""
433 434
     return iter(getattr(d, _itervalues)(**kw))
434 435
 
  436
+
435 437
 def iteritems(d, **kw):
436 438
     """Return an iterator over the (key, value) pairs of a dictionary."""
437 439
     return iter(getattr(d, _iteritems)(**kw))
438 440
 
  441
+
439 442
 def iterlists(d, **kw):
440 443
     """Return an iterator over the (key, [values]) pairs of a dictionary."""
441 444
     return iter(getattr(d, _iterlists)(**kw))
@@ -565,6 +568,7 @@ def with_metaclass(meta, *bases):
565 568
     """Create a base class with a metaclass."""
566 569
     return meta("NewBase", bases, {})
567 570
 
  571
+
568 572
 def add_metaclass(metaclass):
569 573
     """Class decorator for creating a class with a metaclass."""
570 574
     def wrapper(cls):
14  django/utils/text.py
@@ -209,6 +209,7 @@ def _html_words(self, length, truncate):
209 209
         # Return string
210 210
         return out
211 211
 
  212
+
212 213
 def get_valid_filename(s):
213 214
     """
214 215
     Returns the given string converted to a string that can be used for a clean
@@ -222,6 +223,7 @@ def get_valid_filename(s):
222 223
     return re.sub(r'(?u)[^-\w.]', '', s)
223 224
 get_valid_filename = allow_lazy(get_valid_filename, six.text_type)
224 225
 
  226
+
225 227
 def get_text_list(list_, last_word=ugettext_lazy('or')):
226 228
     """
227 229
     >>> get_text_list(['a', 'b', 'c', 'd'])
@@ -245,10 +247,12 @@ def get_text_list(list_, last_word=ugettext_lazy('or')):
245 247
         force_text(last_word), force_text(list_[-1]))
246 248
 get_text_list = allow_lazy(get_text_list, six.text_type)
247 249
 
  250
+
248 251
 def normalize_newlines(text):
249 252
     return force_text(re.sub(r'\r\n|\r|\n', '\n', text))
250 253
 normalize_newlines = allow_lazy(normalize_newlines, six.text_type)
251 254
 
  255
+
252 256
 def recapitalize(text):
253 257
     "Recapitalizes text, placing caps after end-of-sentence punctuation."
254 258
     text = force_text(text).lower()
@@ -257,6 +261,7 @@ def recapitalize(text):
257 261
     return text
258 262
 recapitalize = allow_lazy(recapitalize)
259 263
 
  264
+
260 265
 def phone2numeric(phone):
261 266
     "Converts a phone number with letters into its numeric equivalent."
262 267
     char2number = {'a': '2', 'b': '2', 'c': '2', 'd': '3', 'e': '3', 'f': '3',
@@ -267,6 +272,7 @@ def phone2numeric(phone):
267 272
     return ''.join(char2number.get(c, c) for c in phone.lower())
268 273
 phone2numeric = allow_lazy(phone2numeric)
269 274
 
  275
+
270 276
 # From http://www.xhaus.com/alan/python/httpcomp.html#gzip
271 277
 # Used with permission.
272 278
 def compress_string(s):
@@ -276,6 +282,7 @@ def compress_string(s):
276 282
     zfile.close()
277 283
     return zbuf.getvalue()
278 284
 
  285
+
279 286
 class StreamingBuffer(object):
280 287
     def __init__(self):
281 288
         self.vals = []
@@ -294,6 +301,7 @@ def flush(self):
294 301
     def close(self):
295 302
         return
296 303
 
  304
+
297 305
 # Like compress_string, but for iterators of strings.
298 306
 def compress_sequence(sequence):
299 307
     buf = StreamingBuffer()
@@ -309,6 +317,7 @@ def compress_sequence(sequence):
309 317
 
310 318
 ustring_re = re.compile("([\u0080-\uffff])")
311 319
 
  320
+
312 321
 def javascript_quote(s, quote_double_quotes=False):
313 322
 
314 323
     def fix(match):
@@ -340,6 +349,7 @@ def fix(match):
340 349
     ) | \S+)
341 350
 """, re.VERBOSE)
342 351
 
  352
+
343 353
 def smart_split(text):
344 354
     r"""
345 355
     Generator that splits a string by spaces, leaving quoted phrases together.
@@ -359,6 +369,7 @@ def smart_split(text):
359 369
     for bit in smart_split_re.finditer(text):
360 370
         yield bit.group(0)
361 371
 
  372
+
362 373
 def _replace_entity(match):
363 374
     text = match.group(1)
364 375
     if text[0] == '#':
@@ -379,10 +390,12 @@ def _replace_entity(match):
379 390
 
380 391
 _entity_re = re.compile(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));")
381 392
 
  393
+
382 394
 def unescape_entities(text):
383 395
     return _entity_re.sub(_replace_entity, text)
384 396
 unescape_entities = allow_lazy(unescape_entities, six.text_type)
385 397
 
  398
+
386 399
 def unescape_string_literal(s):
387 400
     r"""
388 401
     Convert quoted string literals to unquoted strings with escaped quotes and
@@ -403,6 +416,7 @@ def unescape_string_literal(s):
403 416
     return s[1:-1].replace(r'\%s' % quote, quote).replace(r'\\', '\\')
404 417
 unescape_string_literal = allow_lazy(unescape_string_literal)
405 418
 
  419
+
406 420
 def slugify(value):
407 421
     """
408 422
     Converts to lowercase, removes non-word characters (alphanumerics and
2  django/utils/timesince.py
@@ -6,6 +6,7 @@
6 6
 from django.utils.timezone import is_aware, utc
7 7
 from django.utils.translation import ugettext, ungettext_lazy
8 8
 
  9
+
9 10
 def timesince(d, now=None, reversed=False):
10 11
     """
11 12
     Takes two datetime objects and returns the time between d and now
@@ -56,6 +57,7 @@ def timesince(d, now=None, reversed=False):
56 57
             result += ugettext(', ') + avoid_wrapping(name2 % count2)
57 58
     return result
58 59
 
  60
+
59 61
 def timeuntil(d, now=None):
60 62
     """
61 63
     Like timesince, but returns a string measuring the time until
18  django/utils/timezone.py
@@ -29,6 +29,7 @@
29 29
 
30 30
 ZERO = timedelta(0)
31 31
 
  32
+
32 33
 class UTC(tzinfo):
33 34
     """
34 35
     UTC implementation taken from Python's docs.
@@ -48,6 +49,7 @@ def tzname(self, dt):
48 49
     def dst(self, dt):
49 50
         return ZERO
50 51
 
  52
+
51 53
 class FixedOffset(tzinfo):
52 54
     """
53 55
     Fixed offset in minutes east from UTC. Taken from Python's docs.
@@ -72,6 +74,7 @@ def tzname(self, dt):
72 74
     def dst(self, dt):
73 75
         return ZERO
74 76
 
  77
+
75 78
 class ReferenceLocalTimezone(tzinfo):
76 79
     """
77 80
     Local time. Taken from Python's docs.
@@ -118,6 +121,7 @@ def _isdst(self, dt):
118 121
         tt = _time.localtime(stamp)
119 122
         return tt.tm_isdst > 0
120 123
 
  124
+
121 125
 class LocalTimezone(ReferenceLocalTimezone):
122 126
     """
123 127
     Slightly improved local time implementation focusing on correctness.
@@ -143,6 +147,7 @@ def _isdst(self, dt):
143 147
 utc = pytz.utc if pytz else UTC()
144 148
 """UTC time zone as a tzinfo instance."""
145 149
 
  150
+
146 151
 def get_fixed_timezone(offset):
147 152
     """
148 153
     Returns a tzinfo instance with a fixed offset from UTC.
@@ -158,6 +163,7 @@ def get_fixed_timezone(offset):
158 163
 # wrap the expression in a function and cache the result.
159 164
 _localtime = None
160 165
 
  166
+
161 167
 def get_default_timezone():
162 168
     """
163 169
     Returns the default time zone as a tzinfo instance.
@@ -173,6 +179,7 @@ def get_default_timezone():
173 179
             _localtime = LocalTimezone()
174 180
     return _localtime
175 181
 
  182
+
176 183
 # This function exists for consistency with get_current_timezone_name
177 184
 def get_default_timezone_name():
178 185
     """
@@ -182,18 +189,21 @@ def get_default_timezone_name():
182 189
 
183 190
 _active = local()
184 191
 
  192
+
185 193
 def get_current_timezone():
186 194
     """
187 195
     Returns the currently active time zone as a tzinfo instance.
188 196
     """
189 197
     return getattr(_active, "value", get_default_timezone())
190 198
 
  199
+
191 200
 def get_current_timezone_name():
192 201
     """
193 202
     Returns the name of the currently active time zone.
194 203
     """
195 204
     return _get_timezone_name(get_current_timezone())
196 205
 
  206
+
197 207
 def _get_timezone_name(timezone):
198 208
     """
199 209
     Returns the name of ``timezone``.
@@ -210,6 +220,7 @@ def _get_timezone_name(timezone):
210 220
 # These functions don't change os.environ['TZ'] and call time.tzset()
211 221
 # because it isn't thread safe.
212 222
 
  223
+
213 224
 def activate(timezone):
214 225
     """
215 226
     Sets the time zone for the current thread.
@@ -224,6 +235,7 @@ def activate(timezone):
224 235
     else:
225 236
         raise ValueError("Invalid timezone: %r" % timezone)
226 237
 
  238
+
227 239
 def deactivate():
228 240
     """
229 241
     Unsets the time zone for the current thread.
@@ -233,6 +245,7 @@ def deactivate():
233 245
     if hasattr(_active, "value"):
234 246
         del _active.value
235 247
 
  248
+
236 249
 class override(object):
237 250
     """
238 251
     Temporarily set the time zone for the current thread.
@@ -297,6 +310,7 @@ def localtime(value, timezone=None):
297 310
         value = timezone.normalize(value)
298 311
     return value
299 312
 
  313
+
300 314
 def now():
301 315
     """
302 316
     Returns an aware or naive datetime.datetime, depending on settings.USE_TZ.
@@ -307,6 +321,7 @@ def now():
307 321
     else:
308 322
         return datetime.now()
309 323
 
  324
+
310 325
 # By design, these four functions don't perform any checks on their arguments.
311 326
 # The caller should ensure that they don't receive an invalid value like None.
312 327
 
@@ -319,6 +334,7 @@ def is_aware(value):
319 334
     """
320 335
     return value.tzinfo is not None and value.tzinfo.utcoffset(value) is not None
321 336
 
  337