Refs #30899 -- Moved _lazy_re_compile() to the django.utils.regex_helper.

This commit is contained in:
Hasan Ramezani 2019-10-26 15:32:40 +02:00 committed by Mariusz Felisiak
parent 6c6d24a4fe
commit c4cba148d8
2 changed files with 19 additions and 13 deletions

View File

@ -6,26 +6,14 @@ from urllib.parse import urlsplit, urlunsplit
from django.core.exceptions import ValidationError
from django.utils.deconstruct import deconstructible
from django.utils.encoding import punycode
from django.utils.functional import SimpleLazyObject
from django.utils.ipv6 import is_valid_ipv6_address
from django.utils.regex_helper import _lazy_re_compile
from django.utils.translation import gettext_lazy as _, ngettext_lazy
# These values, if given to validate(), will trigger the self.required check.
EMPTY_VALUES = (None, '', [], (), {})
def _lazy_re_compile(regex, flags=0):
"""Lazily compile a regex with flags."""
def _compile():
# Compile the regex if it was not passed pre-compiled.
if isinstance(regex, str):
return re.compile(regex, flags)
else:
assert not flags, "flags must be empty if regex is passed pre-compiled"
return regex
return SimpleLazyObject(_compile)
@deconstructible
class RegexValidator:
regex = ''

View File

@ -5,6 +5,10 @@ Used internally by Django and not intended for external use.
This is not, and is not intended to be, a complete reg-exp decompiler. It
should be good enough for a large class of URLS, however.
"""
import re
from django.utils.functional import SimpleLazyObject
# Mapping of an escape character to a representative of that class. So, e.g.,
# "\w" is replaced by "x" in a reverse URL. A value of None means to ignore
# this sequence. Any missing key is mapped to itself.
@ -331,3 +335,17 @@ def flatten_result(source):
for i in range(len(result)):
result[i] += piece
return result, result_args
def _lazy_re_compile(regex, flags=0):
"""Lazily compile a regex with flags."""
def _compile():
# Compile the regex if it was not passed pre-compiled.
if isinstance(regex, str):
return re.compile(regex, flags)
else:
assert not flags, (
'flags must be empty if regex is passed pre-compiled'
)
return regex
return SimpleLazyObject(_compile)