PageRenderTime 2889ms CodeModel.GetById 36ms RepoModel.GetById 5ms app.codeStats 1ms

/poet/trunk/pythonLibs/Django-1.3/build/lib/django/core/validators.py

https://bitbucket.org/ssaltzman/poet
Python | 190 lines | 175 code | 14 blank | 1 comment | 2 complexity | 063ce25390d569b58da01713f1cd11c7 MD5 | raw file
Possible License(s): Apache-2.0, LGPL-3.0, BSD-3-Clause
  1. import re
  2. import urllib2
  3. import urlparse
  4. from django.core.exceptions import ValidationError
  5. from django.utils.translation import ugettext_lazy as _
  6. from django.utils.encoding import smart_unicode
  7. # These values, if given to validate(), will trigger the self.required check.
  8. EMPTY_VALUES = (None, '', [], (), {})
  9. try:
  10. from django.conf import settings
  11. URL_VALIDATOR_USER_AGENT = settings.URL_VALIDATOR_USER_AGENT
  12. except ImportError:
  13. # It's OK if Django settings aren't configured.
  14. URL_VALIDATOR_USER_AGENT = 'Django (http://www.djangoproject.com/)'
  15. class RegexValidator(object):
  16. regex = ''
  17. message = _(u'Enter a valid value.')
  18. code = 'invalid'
  19. def __init__(self, regex=None, message=None, code=None):
  20. if regex is not None:
  21. self.regex = regex
  22. if message is not None:
  23. self.message = message
  24. if code is not None:
  25. self.code = code
  26. if isinstance(self.regex, basestring):
  27. self.regex = re.compile(regex)
  28. def __call__(self, value):
  29. """
  30. Validates that the input matches the regular expression.
  31. """
  32. if not self.regex.search(smart_unicode(value)):
  33. raise ValidationError(self.message, code=self.code)
  34. class HeadRequest(urllib2.Request):
  35. def get_method(self):
  36. return "HEAD"
  37. class URLValidator(RegexValidator):
  38. regex = re.compile(
  39. r'^(?:http|ftp)s?://' # http:// or https://
  40. r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
  41. r'localhost|' #localhost...
  42. r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
  43. r'(?::\d+)?' # optional port
  44. r'(?:/?|[/?]\S+)$', re.IGNORECASE)
  45. def __init__(self, verify_exists=False, validator_user_agent=URL_VALIDATOR_USER_AGENT):
  46. super(URLValidator, self).__init__()
  47. self.verify_exists = verify_exists
  48. self.user_agent = validator_user_agent
  49. def __call__(self, value):
  50. try:
  51. super(URLValidator, self).__call__(value)
  52. except ValidationError, e:
  53. # Trivial case failed. Try for possible IDN domain
  54. if value:
  55. value = smart_unicode(value)
  56. scheme, netloc, path, query, fragment = urlparse.urlsplit(value)
  57. try:
  58. netloc = netloc.encode('idna') # IDN -> ACE
  59. except UnicodeError: # invalid domain part
  60. raise e
  61. url = urlparse.urlunsplit((scheme, netloc, path, query, fragment))
  62. super(URLValidator, self).__call__(url)
  63. else:
  64. raise
  65. else:
  66. url = value
  67. if self.verify_exists:
  68. headers = {
  69. "Accept": "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5",
  70. "Accept-Language": "en-us,en;q=0.5",
  71. "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.7",
  72. "Connection": "close",
  73. "User-Agent": self.user_agent,
  74. }
  75. url = url.encode('utf-8')
  76. broken_error = ValidationError(
  77. _(u'This URL appears to be a broken link.'), code='invalid_link')
  78. try:
  79. req = HeadRequest(url, None, headers)
  80. u = urllib2.urlopen(req)
  81. except ValueError:
  82. raise ValidationError(_(u'Enter a valid URL.'), code='invalid')
  83. except urllib2.HTTPError, e:
  84. if e.code in (405, 501):
  85. # Try a GET request (HEAD refused)
  86. # See also: http://www.w3.org/Protocols/rfc2616/rfc2616.html
  87. try:
  88. req = urllib2.Request(url, None, headers)
  89. u = urllib2.urlopen(req)
  90. except:
  91. raise broken_error
  92. else:
  93. raise broken_error
  94. except: # urllib2.URLError, httplib.InvalidURL, etc.
  95. raise broken_error
  96. def validate_integer(value):
  97. try:
  98. int(value)
  99. except (ValueError, TypeError), e:
  100. raise ValidationError('')
  101. class EmailValidator(RegexValidator):
  102. def __call__(self, value):
  103. try:
  104. super(EmailValidator, self).__call__(value)
  105. except ValidationError, e:
  106. # Trivial case failed. Try for possible IDN domain-part
  107. if value and u'@' in value:
  108. parts = value.split(u'@')
  109. domain_part = parts[-1]
  110. try:
  111. parts[-1] = parts[-1].encode('idna')
  112. except UnicodeError:
  113. raise e
  114. super(EmailValidator, self).__call__(u'@'.join(parts))
  115. else:
  116. raise
  117. email_re = re.compile(
  118. r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom
  119. r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' # quoted-string
  120. r')@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$', re.IGNORECASE) # domain
  121. validate_email = EmailValidator(email_re, _(u'Enter a valid e-mail address.'), 'invalid')
  122. slug_re = re.compile(r'^[-\w]+$')
  123. validate_slug = RegexValidator(slug_re, _(u"Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."), 'invalid')
  124. 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}$')
  125. validate_ipv4_address = RegexValidator(ipv4_re, _(u'Enter a valid IPv4 address.'), 'invalid')
  126. comma_separated_int_list_re = re.compile('^[\d,]+$')
  127. validate_comma_separated_integer_list = RegexValidator(comma_separated_int_list_re, _(u'Enter only digits separated by commas.'), 'invalid')
  128. class BaseValidator(object):
  129. compare = lambda self, a, b: a is not b
  130. clean = lambda self, x: x
  131. message = _(u'Ensure this value is %(limit_value)s (it is %(show_value)s).')
  132. code = 'limit_value'
  133. def __init__(self, limit_value):
  134. self.limit_value = limit_value
  135. def __call__(self, value):
  136. cleaned = self.clean(value)
  137. params = {'limit_value': self.limit_value, 'show_value': cleaned}
  138. if self.compare(cleaned, self.limit_value):
  139. raise ValidationError(
  140. self.message % params,
  141. code=self.code,
  142. params=params,
  143. )
  144. class MaxValueValidator(BaseValidator):
  145. compare = lambda self, a, b: a > b
  146. message = _(u'Ensure this value is less than or equal to %(limit_value)s.')
  147. code = 'max_value'
  148. class MinValueValidator(BaseValidator):
  149. compare = lambda self, a, b: a < b
  150. message = _(u'Ensure this value is greater than or equal to %(limit_value)s.')
  151. code = 'min_value'
  152. class MinLengthValidator(BaseValidator):
  153. compare = lambda self, a, b: a < b
  154. clean = lambda self, x: len(x)
  155. message = _(u'Ensure this value has at least %(limit_value)d characters (it has %(show_value)d).')
  156. code = 'min_length'
  157. class MaxLengthValidator(BaseValidator):
  158. compare = lambda self, a, b: a > b
  159. clean = lambda self, x: len(x)
  160. message = _(u'Ensure this value has at most %(limit_value)d characters (it has %(show_value)d).')
  161. code = 'max_length'