PageRenderTime 1ms CodeModel.GetById 31ms app.highlight 13ms RepoModel.GetById 1ms app.codeStats 0ms

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

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