PageRenderTime 54ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/Django-1.4.3/build/lib.linux-i686-2.7/django/core/validators.py

https://bitbucket.org/ducopdep/tiny_blog
Python | 252 lines | 219 code | 22 blank | 11 comment | 20 complexity | 1a00e3f938e504e8fa39170746ec21b0 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. import platform
  2. import re
  3. import urllib
  4. import urllib2
  5. import urlparse
  6. from django.core.exceptions import ValidationError
  7. from django.utils.translation import ugettext_lazy as _
  8. from django.utils.encoding import smart_unicode
  9. from django.utils.ipv6 import is_valid_ipv6_address
  10. # These values, if given to validate(), will trigger the self.required check.
  11. EMPTY_VALUES = (None, '', [], (), {})
  12. try:
  13. from django.conf import settings
  14. URL_VALIDATOR_USER_AGENT = settings.URL_VALIDATOR_USER_AGENT
  15. except ImportError:
  16. # It's OK if Django settings aren't configured.
  17. URL_VALIDATOR_USER_AGENT = 'Django (http://www.djangoproject.com/)'
  18. class RegexValidator(object):
  19. regex = ''
  20. message = _(u'Enter a valid value.')
  21. code = 'invalid'
  22. def __init__(self, regex=None, message=None, code=None):
  23. if regex is not None:
  24. self.regex = regex
  25. if message is not None:
  26. self.message = message
  27. if code is not None:
  28. self.code = code
  29. # Compile the regex if it was not passed pre-compiled.
  30. if isinstance(self.regex, basestring):
  31. self.regex = re.compile(self.regex)
  32. def __call__(self, value):
  33. """
  34. Validates that the input matches the regular expression.
  35. """
  36. if not self.regex.search(smart_unicode(value)):
  37. raise ValidationError(self.message, code=self.code)
  38. class URLValidator(RegexValidator):
  39. regex = re.compile(
  40. r'^(?:http|ftp)s?://' # http:// or https://
  41. r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
  42. r'localhost|' #localhost...
  43. r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
  44. r'(?::\d+)?' # optional port
  45. r'(?:/?|[/?]\S+)$', re.IGNORECASE)
  46. def __init__(self, verify_exists=False,
  47. validator_user_agent=URL_VALIDATOR_USER_AGENT):
  48. super(URLValidator, self).__init__()
  49. self.verify_exists = verify_exists
  50. self.user_agent = validator_user_agent
  51. def __call__(self, value):
  52. try:
  53. super(URLValidator, self).__call__(value)
  54. except ValidationError, e:
  55. # Trivial case failed. Try for possible IDN domain
  56. if value:
  57. value = smart_unicode(value)
  58. scheme, netloc, path, query, fragment = urlparse.urlsplit(value)
  59. try:
  60. netloc = netloc.encode('idna') # IDN -> ACE
  61. except UnicodeError: # invalid domain part
  62. raise e
  63. url = urlparse.urlunsplit((scheme, netloc, path, query, fragment))
  64. super(URLValidator, self).__call__(url)
  65. else:
  66. raise
  67. else:
  68. url = value
  69. if self.verify_exists:
  70. import warnings
  71. warnings.warn(
  72. "The URLField verify_exists argument has intractable security "
  73. "and performance issues. Accordingly, it has been deprecated.",
  74. DeprecationWarning
  75. )
  76. headers = {
  77. "Accept": "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5",
  78. "Accept-Language": "en-us,en;q=0.5",
  79. "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.7",
  80. "Connection": "close",
  81. "User-Agent": self.user_agent,
  82. }
  83. url = url.encode('utf-8')
  84. # Quote characters from the unreserved set, refs #16812
  85. url = urllib.quote(url, "!*'();:@&=+$,/?#[]")
  86. broken_error = ValidationError(
  87. _(u'This URL appears to be a broken link.'), code='invalid_link')
  88. try:
  89. req = urllib2.Request(url, None, headers)
  90. req.get_method = lambda: 'HEAD'
  91. #Create an opener that does not support local file access
  92. opener = urllib2.OpenerDirector()
  93. #Don't follow redirects, but don't treat them as errors either
  94. error_nop = lambda *args, **kwargs: True
  95. http_error_processor = urllib2.HTTPErrorProcessor()
  96. http_error_processor.http_error_301 = error_nop
  97. http_error_processor.http_error_302 = error_nop
  98. http_error_processor.http_error_307 = error_nop
  99. handlers = [urllib2.UnknownHandler(),
  100. urllib2.HTTPHandler(),
  101. urllib2.HTTPDefaultErrorHandler(),
  102. urllib2.FTPHandler(),
  103. http_error_processor]
  104. try:
  105. import ssl
  106. except ImportError:
  107. # Python isn't compiled with SSL support
  108. pass
  109. else:
  110. handlers.append(urllib2.HTTPSHandler())
  111. map(opener.add_handler, handlers)
  112. if platform.python_version_tuple() >= (2, 6):
  113. opener.open(req, timeout=10)
  114. else:
  115. opener.open(req)
  116. except ValueError:
  117. raise ValidationError(_(u'Enter a valid URL.'), code='invalid')
  118. except: # urllib2.URLError, httplib.InvalidURL, etc.
  119. raise broken_error
  120. def validate_integer(value):
  121. try:
  122. int(value)
  123. except (ValueError, TypeError):
  124. raise ValidationError('')
  125. class EmailValidator(RegexValidator):
  126. def __call__(self, value):
  127. try:
  128. super(EmailValidator, self).__call__(value)
  129. except ValidationError, e:
  130. # Trivial case failed. Try for possible IDN domain-part
  131. if value and u'@' in value:
  132. parts = value.split(u'@')
  133. try:
  134. parts[-1] = parts[-1].encode('idna')
  135. except UnicodeError:
  136. raise e
  137. super(EmailValidator, self).__call__(u'@'.join(parts))
  138. else:
  139. raise
  140. email_re = re.compile(
  141. r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom
  142. # quoted-string, see also http://tools.ietf.org/html/rfc2822#section-3.2.5
  143. r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"'
  144. r')@((?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$)' # domain
  145. r'|\[(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\]$', re.IGNORECASE) # literal form, ipv4 address (SMTP 4.1.3)
  146. validate_email = EmailValidator(email_re, _(u'Enter a valid e-mail address.'), 'invalid')
  147. slug_re = re.compile(r'^[-\w]+$')
  148. validate_slug = RegexValidator(slug_re, _(u"Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."), 'invalid')
  149. ipv4_re = re.compile(r'^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$')
  150. validate_ipv4_address = RegexValidator(ipv4_re, _(u'Enter a valid IPv4 address.'), 'invalid')
  151. def validate_ipv6_address(value):
  152. if not is_valid_ipv6_address(value):
  153. raise ValidationError(_(u'Enter a valid IPv6 address.'), code='invalid')
  154. def validate_ipv46_address(value):
  155. try:
  156. validate_ipv4_address(value)
  157. except ValidationError:
  158. try:
  159. validate_ipv6_address(value)
  160. except ValidationError:
  161. raise ValidationError(_(u'Enter a valid IPv4 or IPv6 address.'), code='invalid')
  162. ip_address_validator_map = {
  163. 'both': ([validate_ipv46_address], _('Enter a valid IPv4 or IPv6 address.')),
  164. 'ipv4': ([validate_ipv4_address], _('Enter a valid IPv4 address.')),
  165. 'ipv6': ([validate_ipv6_address], _('Enter a valid IPv6 address.')),
  166. }
  167. def ip_address_validators(protocol, unpack_ipv4):
  168. """
  169. Depending on the given parameters returns the appropriate validators for
  170. the GenericIPAddressField.
  171. This code is here, because it is exactly the same for the model and the form field.
  172. """
  173. if protocol != 'both' and unpack_ipv4:
  174. raise ValueError(
  175. "You can only use `unpack_ipv4` if `protocol` is set to 'both'")
  176. try:
  177. return ip_address_validator_map[protocol.lower()]
  178. except KeyError:
  179. raise ValueError("The protocol '%s' is unknown. Supported: %s"
  180. % (protocol, ip_address_validator_map.keys()))
  181. comma_separated_int_list_re = re.compile('^[\d,]+$')
  182. validate_comma_separated_integer_list = RegexValidator(comma_separated_int_list_re, _(u'Enter only digits separated by commas.'), 'invalid')
  183. class BaseValidator(object):
  184. compare = lambda self, a, b: a is not b
  185. clean = lambda self, x: x
  186. message = _(u'Ensure this value is %(limit_value)s (it is %(show_value)s).')
  187. code = 'limit_value'
  188. def __init__(self, limit_value):
  189. self.limit_value = limit_value
  190. def __call__(self, value):
  191. cleaned = self.clean(value)
  192. params = {'limit_value': self.limit_value, 'show_value': cleaned}
  193. if self.compare(cleaned, self.limit_value):
  194. raise ValidationError(
  195. self.message % params,
  196. code=self.code,
  197. params=params,
  198. )
  199. class MaxValueValidator(BaseValidator):
  200. compare = lambda self, a, b: a > b
  201. message = _(u'Ensure this value is less than or equal to %(limit_value)s.')
  202. code = 'max_value'
  203. class MinValueValidator(BaseValidator):
  204. compare = lambda self, a, b: a < b
  205. message = _(u'Ensure this value is greater than or equal to %(limit_value)s.')
  206. code = 'min_value'
  207. class MinLengthValidator(BaseValidator):
  208. compare = lambda self, a, b: a < b
  209. clean = lambda self, x: len(x)
  210. message = _(u'Ensure this value has at least %(limit_value)d characters (it has %(show_value)d).')
  211. code = 'min_length'
  212. class MaxLengthValidator(BaseValidator):
  213. compare = lambda self, a, b: a > b
  214. clean = lambda self, x: len(x)
  215. message = _(u'Ensure this value has at most %(limit_value)d characters (it has %(show_value)d).')
  216. code = 'max_length'