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

/python/google/appengine/_internal/django/core/validators.py

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