示例#1
0
    def Validate(self, value, unused_key=None):
        """Validates an URL pattern."""
        if value is None:
            raise validation.MissingAttribute('url must be specified')
        if not isinstance(value, basestring):
            raise validation.ValidationError(
                'url must be a string, not \'%r\'' % type(value))

        url_holder = ParsedURL(value)
        if url_holder.host_exact:
            _ValidateMatch(_URL_HOST_EXACT_PATTERN_RE, url_holder.host,
                           'invalid host_pattern \'%s\'' % url_holder.host)

            _ValidateNotIpV4Address(url_holder.host)
        else:
            _ValidateMatch(
                _URL_HOST_SUFFIX_PATTERN_RE, url_holder.host_pattern,
                'invalid host_pattern \'%s\'' % url_holder.host_pattern)

        return value
    def EndMapping(self, top_value, mapping):
        """When leaving scope, makes sure new object is initialized.

    This method is mainly for picking up on any missing required attributes.

    Args:
      top_value: Parent of closing mapping object.
      mapping: _ObjectMapper instance that is leaving scope.
    """
        try:
            mapping.value.CheckInitialized()
        except validation.ValidationError:
            raise
        except Exception, e:
            try:
                error_str = str(e)
            except Exception:
                error_str = '<unknown>'

            raise validation.ValidationError("Invalid object:\n%s" % error_str,
                                             e)
示例#3
0
 def Validate(self, value):
     """Validates a timezone."""
     if value is None:
         return
     if not isinstance(value, basestring):
         raise TypeError('timezone must be a string, not \'%r\'' %
                         type(value))
     if pytz is None:
         return value
     try:
         pytz.timezone(value)
     except pytz.UnknownTimeZoneError:
         raise validation.ValidationError('timezone \'%s\' is unknown' %
                                          value)
     except IOError:
         return value
     except:
         unused_e, v, t = sys.exc_info()
         logging.warning('pytz raised an unexpected error: %s.\n' % (v) +
                         'Traceback:\n' + '\n'.join(traceback.format_tb(t)))
         raise
     return value
示例#4
0
  def Validate(self, value, unused_key=None):
    """Validates an URL pattern."""
    if value is None:
      raise validation.MissingAttribute('url must be specified')
    if not isinstance(value, six_subset.string_types):
      raise validation.ValidationError('url must be a string, not \'%r\'' %
                                       type(value))

    url_holder = ParsedURL(value)
    if url_holder.host_exact:
      _ValidateMatch(_URL_HOST_EXACT_PATTERN_RE, url_holder.host,
                     'invalid host_pattern \'%s\'' % url_holder.host)
      # Explicitly disallow IpV4 #.#.#.# addresses. These will match
      # _URL_HOST_EXACT_PATTERN_RE above.
      _ValidateNotIpV4Address(url_holder.host)
    else:
      _ValidateMatch(_URL_HOST_SUFFIX_PATTERN_RE, url_holder.host_pattern,
                     'invalid host_pattern \'%s\'' % url_holder.host_pattern)

    #TODO(user): validate path_pattern and lengths of both patterns.
    #                also validate hostname label lengths 63 charn max)
    return value
示例#5
0
 def Validate(self, value, key=None):
   """Validates a timezone."""
   if not isinstance(value, six_subset.string_types):
     raise TypeError('timezone must be a string, not \'%r\'' % type(value))
   if pytz is None:
     # pytz not installed, silently accept anything without validating
     return value
   try:
     pytz.timezone(value)
   except pytz.UnknownTimeZoneError:
     raise validation.ValidationError('timezone \'%s\' is unknown' % value)
   except IOError:
     # When running under dev_appserver, pytz can't open it's resource files.
     # I have no idea how to test this.
     return value
   except:
     # The yaml and validation code repeatedly re-raise exceptions that
     # consume tracebacks.
     unused_e, v, t = sys.exc_info()
     logging.warning('pytz raised an unexpected error: %s.\n' % (v) +
                     'Traceback:\n' + '\n'.join(traceback.format_tb(t)))
     raise
   return value
    def CheckInitialized(self):
        """Performs non-regex-based validation.

    Ensures that at least one url mapping is provided in the URL mappers
    Also ensures that the major version doesn't contain the string
    -dot-.

    Raises:
      MissingURLMapping when no URLMap objects are present in object.
      TooManyURLMappings when there are too many URLMap entries.
    """
        super(AppInfoExternal, self).CheckInitialized()
        if not self.handlers and not self.builtins and not self.includes:
            raise appinfo_errors.MissingURLMapping(
                'No URLMap entries found in application configuration')
        if self.handlers and len(self.handlers) > MAX_URL_MAPS:
            raise appinfo_errors.TooManyURLMappings(
                'Found more than %d URLMap entries in application configuration'
                % MAX_URL_MAPS)
        if self.version.find(ALTERNATE_HOSTNAME_SEPARATOR) != -1:
            raise validation.ValidationError(
                'App version "%s" cannot contain the string "%s"' %
                (self.version, ALTERNATE_HOSTNAME_SEPARATOR))
示例#7
0
def _ValidateMatch(regex, value, message):
    """Validate value matches regex."""
    matcher = regex.match(value)
    if not matcher:
        raise validation.ValidationError(message)
    return matcher
 def CheckInitialized(self):
     if self.direction is not None and self.mode is not None:
         raise validation.ValidationError(
             'direction and mode are mutually exclusive')
     super(Property, self).CheckInitialized()
示例#9
0
                   (value_str, key, error_str))
      raise e
    except Exception, e:
      try:
        error_str = str(e)
      except Exception:
        error_str = '<unknown>'

      try:
        value_str = str(value)
      except Exception:
        value_str = '<unknown>'

      message = ("Unable to assign value '%s' to attribute '%s':\n%s" %
                 (value_str, key, error_str))
      raise validation.ValidationError(message, e)

  def AppendTo(self, subject, value):
    """Append a value to a sequence.

    Args:
      subject: _ObjectSequence that is receiving new value.
      value: Value that is being appended to sequence.
    """
    if isinstance(value, _ObjectMapper):
      value.set_value(subject.constructor())
      subject.value.append(value.value)
    else:
      subject.value.append(value)

示例#10
0
 def CheckInitialized(self):
   if ('direction' in self._is_set and
       self.mode in ['geospatial', 'segment']):
     raise validation.ValidationError('Direction on a %s-mode '
                                      'property is not allowed.' % self.mode)
示例#11
0
    def CheckInitialized(self):
        """Performs non-regex-based validation.

    The following are verified:
      - At least one url mapping is provided in the URL mappers.
      - Number of url mappers doesn't exceed MAX_URL_MAPS.
      - Major version does not contain the string -dot-.
      - If api_endpoints are defined, an api_config stanza must be defined.
      - If the runtime is python27 and threadsafe is set, then no CGI handlers
        can be used.
      - That the version name doesn't start with BUILTIN_NAME_PREFIX

    Raises:
      MissingURLMapping: if no URLMap object is present in the object.
      TooManyURLMappings: if there are too many URLMap entries.
      MissingApiConfig: if api_endpoints exist without an api_config.
      ThreadsafeWithCgiHandler: if the runtime is python27, threadsafe is set
          and CGI handlers are specified.
    """
        super(AppInfoExternal, self).CheckInitialized()
        if not self.handlers and not self.builtins and not self.includes:
            raise appinfo_errors.MissingURLMapping(
                'No URLMap entries found in application configuration')
        if self.handlers and len(self.handlers) > MAX_URL_MAPS:
            raise appinfo_errors.TooManyURLMappings(
                'Found more than %d URLMap entries in application configuration'
                % MAX_URL_MAPS)

        if self.libraries:
            if self.runtime != 'python27':
                raise appinfo_errors.RuntimeDoesNotSupportLibraries(
                    'libraries entries are only supported by the "python27" runtime'
                )

            library_names = [library.name for library in self.libraries]
            for library_name in library_names:
                if library_names.count(library_name) > 1:
                    raise appinfo_errors.DuplicateLibrary(
                        'Duplicate library entry for %s' % library_name)

        if self.version and self.version.find(
                ALTERNATE_HOSTNAME_SEPARATOR) != -1:
            raise validation.ValidationError(
                'Version "%s" cannot contain the string "%s"' %
                (self.version, ALTERNATE_HOSTNAME_SEPARATOR))
        if self.version and self.version.startswith(BUILTIN_NAME_PREFIX):
            raise validation.ValidationError(
                ('Version "%s" cannot start with "%s" because it is a '
                 'reserved version name prefix.') %
                (self.version, BUILTIN_NAME_PREFIX))
        if self.handlers:
            api_endpoints = [
                handler.url for handler in self.handlers
                if handler.GetHandlerType() == HANDLER_API_ENDPOINT
            ]
            if api_endpoints and not self.api_config:
                raise appinfo_errors.MissingApiConfig(
                    'An api_endpoint handler was specified, but the required '
                    'api_config stanza was not configured.')
            if self.threadsafe and self.runtime == 'python27':
                for handler in self.handlers:
                    if (handler.script and (handler.script.endswith('.py')
                                            or '/' in handler.script)):
                        raise appinfo_errors.ThreadsafeWithCgiHandler(
                            'Threadsafe cannot be enabled with CGI handler: %s'
                            % handler.script)
示例#12
0
 def Validate(self, value, key):
   if not isinstance(value, int):
     raise validation.ValidationError('Value for %s is not an int' % key)
   return value
示例#13
0
    def clean(self):
        cd = self.clean_data
        if not all(cd.values()):
            raise validation.ValidationError('All fields required.')

        return cd
示例#14
0
 def CheckInitialized(self):
   if 'direction' in self._is_set and self.mode == 'geospatial':
     raise validation.ValidationError('Direction on a geospatial-mode '
                                      'property is not allowed.')