예제 #1
0
    def __call__(self, environ, start_response):
        """Called by WSGI when a request comes in."""
        request = Request(environ)
        response = Response()
        WSGIApplication.active_instance = self

        # Match the path against registered routes.
        kargs = self.mapper.match(request.path)
        if kargs is None:
            raise TypeError(
                'No routes match. Provide a fallback to avoid this.')

        # Extract the module and controller names from the route.
        try:
            module_name, class_name = kargs['controller'].split(':', 1)
        except (KeyError, ValueError):
            module_name = kargs['controller']
            class_name = module_name
        del kargs['controller']
        module_name = _CONTROLLERS_MODULE_PREFIX + '.' + module_name

        # Initialize matched controller from given module.
        try:
            __import__(module_name)
            module = sys.modules[module_name]
            controller = getattr(module, class_name)()
            controller.initialize(request, response)
        except (ImportError, AttributeError):
            logging.exception('Could not import controller %s:%s', module_name,
                              class_name)
            raise ImportError(
                'Controller %s from module %s could not be initialized.' %
                (class_name, module_name))

        # Use the action set in the route, or the HTTP method.
        if 'action' in kargs:
            action = kargs['action']
            del kargs['action']
        else:
            action = environ['REQUEST_METHOD'].lower()
            if action not in [
                    'get', 'post', 'head', 'options', 'put', 'delete', 'trace'
            ]:
                action = None

        if controller and action:
            try:
                # Execute the requested action, passing the route dictionary as
                # named parameters.
                getattr(controller, action)(**kargs)
            except error.AccessDenied, acl_e:
                logging.exception(acl_e)
                response.set_status(404)
            except Exception, e:
                # We want to catch any exception thrown by the controller and
                # pass it on to the controller's own exception handler.
                controller.handle_exception(e, self.__debug)
예제 #2
0
파일: wsgi.py 프로젝트: Circyl/MobiPerf
  def __call__(self, environ, start_response):
    """Called by WSGI when a request comes in."""
    request = Request(environ)
    response = Response()
    WSGIApplication.active_instance = self

    # Match the path against registered routes.
    kargs = self.mapper.match(request.path)
    if kargs is None:
      raise TypeError('No routes match. Provide a fallback to avoid this.')

    # Extract the module and controller names from the route.
    try:
      module_name, class_name = kargs['controller'].split(':', 1)
    except (KeyError, ValueError):
      module_name = kargs['controller']
      class_name = module_name
    del kargs['controller']
    module_name = _CONTROLLERS_MODULE_PREFIX + '.' + module_name

    # Initialize matched controller from given module.
    try:
      __import__(module_name)
      module = sys.modules[module_name]
      controller = getattr(module, class_name)()
      controller.initialize(request, response)
    except (ImportError, AttributeError):
      logging.exception('Could not import controller %s:%s',
                        module_name, class_name)
      raise ImportError('Controller %s from module %s could not be initialized.'
                        % (class_name, module_name))

    # Use the action set in the route, or the HTTP method.
    if 'action' in kargs:
      action = kargs['action']
      del kargs['action']
    else:
      action = environ['REQUEST_METHOD'].lower()
      if action not in [
          'get', 'post', 'head', 'options', 'put', 'delete', 'trace']:
        action = None

    if controller and action:
      try:
        # Execute the requested action, passing the route dictionary as
        # named parameters.
        getattr(controller, action)(**kargs)
      except error.AccessDenied, acl_e:
        logging.exception(acl_e)
        response.set_status(404)
      except Exception, e:
        # We want to catch any exception thrown by the controller and
        # pass it on to the controller's own exception handler.
        controller.handle_exception(e, self.__debug)
예제 #3
0
    def __call__(self, environ, start_response):
        """Called by WSGI when a request comes in."""

        url = URLGenerator(self.mapper, environ)
        environ['routes.url'] = url

        request = Request(environ)
        response = Response()
        WSGIApplication.active_instance = self
        # Match the path against registered routes.
        kargs = self.mapper.match(request.path)
        if kargs is None:
            raise TypeError(
                'No routes match. Provide a fallback to avoid this.')
        # Extract the module and controller names from the route.
        try:
            module_name, class_name = kargs['controller'].split(':', 1)
            del kargs['controller']
        except:
            raise TypeError(
                'Controller is not set, or not formatted in the form "my.module.name:MyControllerName".'
            )
        # Initialize matched controller from given module.
        try:
            __import__(module_name)
            module = sys.modules[module_name]
            controller = getattr(module, class_name)()
            controller.initialize(request, response)
        except:
            raise ImportError(
                'Controller %s from module %s could not be initialized.' %
                (class_name, module_name))
        # Use the action set in the route, or the HTTP method.
        if 'action' in kargs:
            action = kargs['action']
            del kargs['action']
        else:
            action = environ['REQUEST_METHOD'].lower()
            if action not in [
                    'get', 'post', 'head', 'options', 'put', 'delete', 'trace'
            ]:
                action = None
        if controller and action:
            try:
                # Execute the requested action, passing the route dictionary as
                # named parameters.
                getattr(controller, action)(**kargs)
            except Exception, e:
                controller.handle_exception(e, self.__debug)
            response.wsgi_write(start_response)
            return ['']
예제 #4
0
	def __call__(self, environ, start_response):
		"""Called by WSGI when a request comes in."""

		request = Request(environ)
		response = Response()
		
		# BidiX 2008-09-22 : try to setup a firewall at least a nop
		if banned_ip.is_banned(request.remote_addr):
			response.set_status(403)
			response.wsgi_write(start_response)
			return ['']

		WSGIApplication.active_instance = self

		handler = None
		groups = ()
		for regexp, handler_class in self._url_mapping:
			match = regexp.match(request.path)
			if match:
				handler = handler_class()
				handler.match = match	# BidiX 2008-05-22
				handler.initialize(request, response)
				groups = match.groups()
				break
		self.current_request_args = groups

		if handler:
			try:
				method = environ['REQUEST_METHOD']
				if method == 'GET':
					handler.get(*groups)
				elif method == 'POST':
					handler.post(*groups)
				elif method == 'HEAD':
					handler.head(*groups)
				elif method == 'OPTIONS':
					handler.options(*groups)
				elif method == 'PUT':
					handler.put(*groups)
				elif method == 'DELETE':
					handler.delete(*groups)
				elif method == 'TRACE':
					handler.trace(*groups)
				else:
					handler.error(501)
			except Exception, e:
				#handler.handle_exception(e, self.__debug) # BidiX 2008-05-22
				handler.handle_exception(e, True) # BidiX 2008-05-22
예제 #5
0
 def error(self, code, message = None):
     self.response.set_status(code, str(message))
     if message is None: message = Response.http_status_message(code)
     self.view['message'] = message
     self.view['code'] = code
     self.render_view('system/error.html')
     raise PageError, (code, message)
예제 #6
0
 def exec_handler(self, body=None):
     """Used by each test to execute the minimal Testhandler."""
     h = self.MyTestHandler()
     h.request = Request.blank('/test_rpc/')
     h.response = Response()
     h.request.method = 'POST'
     h.request.body = body
     h.post()
     return (h.response._Response__status[0], h.response.out.getvalue())
예제 #7
0
    def __call__(self, environ, start_response):
        """Called by WSGI when a request comes in."""

        url = URLGenerator(self.mapper, environ)
        environ['routes.url'] = url

        request = Request(environ)
        response = Response()
        WSGIApplication.active_instance = self
        # Match the path against registered routes.
        kargs = self.mapper.match(request.path)
        if kargs is None:
            raise TypeError('No routes match. Provide a fallback to avoid this.')
        # Extract the module and controller names from the route.
        try:
            module_name, class_name = kargs['controller'].split(':', 1)
            del kargs['controller']
        except:
            raise TypeError('Controller is not set, or not formatted in the form "my.module.name:MyControllerName".')
        # Initialize matched controller from given module.
        try:
            __import__(module_name)
            module = sys.modules[module_name]
            controller = getattr(module, class_name)()
            controller.initialize(request, response)
        except:
            raise ImportError('Controller %s from module %s could not be initialized.' % (class_name, module_name))
        # Use the action set in the route, or the HTTP method.
        if 'action' in kargs:
            action = kargs['action']
            del kargs['action']
        else:
            action = environ['REQUEST_METHOD'].lower()
            if action not in ['get', 'post', 'head', 'options', 'put', 'delete', 'trace']:
                action = None
        if controller and action:
            try:
                # Execute the requested action, passing the route dictionary as
                # named parameters.
                getattr(controller, action)(**kargs)
            except Exception, e:
                controller.handle_exception(e, self.__debug)
            response.wsgi_write(start_response)
            return ['']
예제 #8
0
    def __call__(self, environ, start_response):
        """Called by WSGI when a request comes in."""

        request = Request(environ)
        response = Response()

        # BidiX 2008-09-22 : try to setup a firewall at least a nop
        if banned_ip.is_banned(request.remote_addr):
            response.set_status(403)
            response.wsgi_write(start_response)
            return ['']

        WSGIApplication.active_instance = self

        handler = None
        groups = ()
        for regexp, handler_class in self._url_mapping:
            match = regexp.match(request.path)
            if match:
                handler = handler_class()
                handler.match = match  # BidiX 2008-05-22
                handler.initialize(request, response)
                groups = match.groups()
                break
        self.current_request_args = groups

        if handler:
            try:
                method = environ['REQUEST_METHOD']
                if method == 'GET':
                    handler.get(*groups)
                elif method == 'POST':
                    handler.post(*groups)
                elif method == 'HEAD':
                    handler.head(*groups)
                elif method == 'OPTIONS':
                    handler.options(*groups)
                elif method == 'PUT':
                    handler.put(*groups)
                elif method == 'DELETE':
                    handler.delete(*groups)
                elif method == 'TRACE':
                    handler.trace(*groups)
                else:
                    handler.error(501)
            except Exception, e:
                #handler.handle_exception(e, self.__debug) # BidiX 2008-05-22
                handler.handle_exception(e, True)  # BidiX 2008-05-22
예제 #9
0
def parsefunctiondoc(docstring):
    global types

    # create an ordered dictionary to hold information from the docstring
    docdict = collections.OrderedDict()

    # no docstring given
    if (docstring == None):
        docdict[ "Description" ] = "Unspecified"
        docdict[ "Arguments" ] = "Unspecified"
        docdict[ "Bindings" ] = "Unspecified"
        docdict[ "Returns" ] = "Unspecified"
        docdict[ "Errors" ] = "Unspecified"
        return docdict

    # split the docstring into lines and obtain the number of lines
    docstring = docstring.split("\n")
    docsize = len(docstring)

    # one-line docstring
    if (docsize == 1):
        docdict[ "Description" ] = docstring[0].strip()
        docdict[ "Arguments" ] = "Unspecified"
        docdict[ "Bindings" ] = "Unspecified"
        docdict[ "Returns" ] = "Unspecified"
        docdict[ "Errors" ] = "Unspecified"
        return docdict

    # obtain information about description
    docsize = docsize - 1
    description = ""
    i = 0
    while(i<docsize and (not (docstring[i].strip()).startswith("Args"))):
        description = description + str(docstring[i].strip()) + " "
        i = i + 1
    if (description.strip() == ""):
        docdict[ "Description" ] = "Unspecified"
    else:
        docdict[ "Description" ] = description.strip()
    if (i == docsize):
        docdict[ "Arguments" ] = "Unspecified"
        docdict[ "Bindings" ] = "Unspecified"
        docdict[ "Returns" ] = "Unspecified"
        docdict[ "Errors" ] = "Unspecified"
        return docdict

    # obtain information about argument(s), including queries
    arguments = []
    i = i + 1
    while(i<docsize):
        argline = docstring[i].split(":")
        if (len(argline) == 1):
            break
        elif (len(argline) == 2):
            argtype = argline[1].strip()
            if (argtype == ""):
                argtype = "Unspecified"
            argdes = "Unspecified"
        else:
            argtype = argline[1].strip()
            argdes = argline[2].strip()
            if (argdes == ""):
                argdes = "Unspecified"
        argdict = collections.OrderedDict()
        argdict[ "Name" ] = argline[0].strip()
        argdict[ "Description" ] = argdes
        argdict[ "Type" ] = argtype

        if (argdict[ "Type" ] not in types):
            types.append(argdict[ "Type" ])

        arguments.append(argdict)
        i = i + 1
    if (arguments == []):
        docdict[ "Arguments" ] = "Unspecified"
    else:
        docdict[ "Arguments" ] = arguments
    if (i == docsize):
        docdict[ "Bindings" ] = "Unspecified"
        docdict[ "Returns" ] = "Unspecified"
        docdict[ "Errors" ] = "Unspecified"
        return docdict

    # obtain information about bindings
    while(i<docsize and (not (docstring[i].strip()).startswith("Bindings"))):
        description = description + str(docstring[i].strip()) + " "
        i = i + 1
    if (i == docsize):
        docdict[ "Bindings" ] = "Unspecified"
        docdict[ "Returns" ] = "Unspecified"
        docdict[ "Errors" ] = "Unspecified"
        return docdict
    bindings = []
    i = i + 1
    while(i<docsize):
        bindline = docstring[i].split(":")
        if (len(bindline) == 1):
            break
        elif (len(bindline) == 2):
            bindtype = bindline[1].strip()
            if (bindtype == ""):
                bindtype = "Unspecified"
                binddes = "Unspecified"
                bindmode = "Unspecified"
        elif (len(bindline) == 3):
            binddes = bindline[2].strip()
            if (binddes == ""):
                binddes = "Unspecified"
                bindmode = "Unspecified"
        else:
            bindtype = bindline[1].strip()
            binddes = bindline[2].strip()
            bindmode = bindline[3].strip()
            if (bindmode == ""):
                bindmode = "Unspecified"
        binddict = collections.OrderedDict()
        binddict[ "ID" ] = bindline[0].strip() + "Binding"
        binddict[ "Mode" ] = bindmode
        binddict[ "Name" ] = bindline[0].strip()
        binddict[ "Description" ] = binddes
        binddict[ "Type" ] = bindtype

        if (binddict[ "Type" ] not in types):
            types.append(binddict[ "Type" ])

        bindings.append(binddict)
        i = i + 1
    if (bindings == []):
        docdict[ "Bindings" ] = "Unspecified"
    else:
        docdict[ "Bindings" ] = bindings
    if (i == docsize):
        docdict[ "Returns" ] = "Unspecified"
        docdict[ "Errors" ] = "Unspecified"
        return docdict
    while(i<docsize and (not (docstring[i].strip()).startswith("Returns"))):
        i = i+1
    if (i == docsize):
        docdict[ "Returns" ] = "Unspecified"
        docdict[ "Errors" ] = "Unspecified"
        return docdict

    # obtain information about return type
    returns = []
    i = i + 1
    while(i<docsize):
        retline = docstring[i].split(":")
        if (len(retline) == 1):
            break
        else:
            rettype = retline[1].strip()
            retdes = retline[2].strip()
            if (retdes == ""):
                retdes = "Unspecified"
        retdict = collections.OrderedDict()
        retdict[ "Name" ] = retline[0].strip()
        retdict[ "Description" ] = retdes
        retdict[ "Type" ] = rettype

        if (retdict[ "Type" ] not in types):
            types.append(retdict[ "Type" ])

        returns.append(retdict)
        i = i + 1
    if (returns == []):
        docdict[ "Returns" ] = "Unspecified"
    else:
        docdict[ "Returns" ] = returns
    if (i == docsize):
        docdict[ "Errors" ] = "Unspecified"
        return docdict
    while(i<docsize and (not (docstring[i].strip()).startswith("Exceptions"))):
        i = i+1
    if (i == docsize):
        docdict[ "Errors" ] = "Unspecified"
        return docdict

    # obtain information about errors, if given
    errors = []
    i = i + 1
    while(i<docsize):
        errdict = collections.OrderedDict()
        errline = docstring[i].split(":")
        if (errline[0].strip() == ''):
            break
        if (len(errline) == 1):
            errline = errline[0].strip()
            errdict[ "Status" ] = errline
            errdict[ "Cause" ] = Response.http_status_message(int(errline))
        else:
            errdict[ "Status" ] = errline[0].strip()
            errdict[ "Cause" ] = errline[1].strip()
        if (errdict[ "Cause" ] == ""):
            errdict[ "Cause" ] = Response.http_status_message(int(errdict[ "Status" ]))
        errors.append(errdict)
        i = i + 1
    docdict[ "Errors" ] = errors

    return docdict
def parsefunctiondoc(docstring):
    global types

    # create an ordered dictionary to hold information from the docstring
    docdict = collections.OrderedDict()

    # no docstring given
    if (docstring == None):
        docdict["Description"] = "Unspecified"
        docdict["Arguments"] = "Unspecified"
        docdict["Bindings"] = "Unspecified"
        docdict["Returns"] = "Unspecified"
        docdict["Errors"] = "Unspecified"
        return docdict

    # split the docstring into lines and obtain the number of lines
    docstring = docstring.split("\n")
    docsize = len(docstring)

    # one-line docstring
    if (docsize == 1):
        docdict["Description"] = docstring[0].strip()
        docdict["Arguments"] = "Unspecified"
        docdict["Bindings"] = "Unspecified"
        docdict["Returns"] = "Unspecified"
        docdict["Errors"] = "Unspecified"
        return docdict

    # obtain information about description
    docsize = docsize - 1
    description = ""
    i = 0
    while (i < docsize and (not (docstring[i].strip()).startswith("Args"))):
        description = description + str(docstring[i].strip()) + " "
        i = i + 1
    if (description.strip() == ""):
        docdict["Description"] = "Unspecified"
    else:
        docdict["Description"] = description.strip()
    if (i == docsize):
        docdict["Arguments"] = "Unspecified"
        docdict["Bindings"] = "Unspecified"
        docdict["Returns"] = "Unspecified"
        docdict["Errors"] = "Unspecified"
        return docdict

    # obtain information about argument(s), including queries
    arguments = []
    i = i + 1
    while (i < docsize):
        argline = docstring[i].split(":")
        if (len(argline) == 1):
            break
        elif (len(argline) == 2):
            argtype = argline[1].strip()
            if (argtype == ""):
                argtype = "Unspecified"
            argdes = "Unspecified"
        else:
            argtype = argline[1].strip()
            argdes = argline[2].strip()
            if (argdes == ""):
                argdes = "Unspecified"
        argdict = collections.OrderedDict()
        argdict["Name"] = argline[0].strip()
        argdict["Description"] = argdes
        argdict["Type"] = argtype

        if (argdict["Type"] not in types):
            types.append(argdict["Type"])

        arguments.append(argdict)
        i = i + 1
    if (arguments == []):
        docdict["Arguments"] = "Unspecified"
    else:
        docdict["Arguments"] = arguments
    if (i == docsize):
        docdict["Bindings"] = "Unspecified"
        docdict["Returns"] = "Unspecified"
        docdict["Errors"] = "Unspecified"
        return docdict

    # obtain information about bindings
    while (i < docsize
           and (not (docstring[i].strip()).startswith("Bindings"))):
        description = description + str(docstring[i].strip()) + " "
        i = i + 1
    if (i == docsize):
        docdict["Bindings"] = "Unspecified"
        docdict["Returns"] = "Unspecified"
        docdict["Errors"] = "Unspecified"
        return docdict
    bindings = []
    i = i + 1
    while (i < docsize):
        bindline = docstring[i].split(":")
        if (len(bindline) == 1):
            break
        elif (len(bindline) == 2):
            bindtype = bindline[1].strip()
            if (bindtype == ""):
                bindtype = "Unspecified"
                binddes = "Unspecified"
                bindmode = "Unspecified"
        elif (len(bindline) == 3):
            binddes = bindline[2].strip()
            if (binddes == ""):
                binddes = "Unspecified"
                bindmode = "Unspecified"
        else:
            bindtype = bindline[1].strip()
            binddes = bindline[2].strip()
            bindmode = bindline[3].strip()
            if (bindmode == ""):
                bindmode = "Unspecified"
        binddict = collections.OrderedDict()
        binddict["ID"] = bindline[0].strip() + "Binding"
        binddict["Mode"] = bindmode
        binddict["Name"] = bindline[0].strip()
        binddict["Description"] = binddes
        binddict["Type"] = bindtype

        if (binddict["Type"] not in types):
            types.append(binddict["Type"])

        bindings.append(binddict)
        i = i + 1
    if (bindings == []):
        docdict["Bindings"] = "Unspecified"
    else:
        docdict["Bindings"] = bindings
    if (i == docsize):
        docdict["Returns"] = "Unspecified"
        docdict["Errors"] = "Unspecified"
        return docdict
    while (i < docsize and (not (docstring[i].strip()).startswith("Returns"))):
        i = i + 1
    if (i == docsize):
        docdict["Returns"] = "Unspecified"
        docdict["Errors"] = "Unspecified"
        return docdict

    # obtain information about return type
    returns = []
    i = i + 1
    while (i < docsize):
        retline = docstring[i].split(":")
        if (len(retline) == 1):
            break
        else:
            rettype = retline[1].strip()
            retdes = retline[2].strip()
            if (retdes == ""):
                retdes = "Unspecified"
        retdict = collections.OrderedDict()
        retdict["Name"] = retline[0].strip()
        retdict["Description"] = retdes
        retdict["Type"] = rettype

        if (retdict["Type"] not in types):
            types.append(retdict["Type"])

        returns.append(retdict)
        i = i + 1
    if (returns == []):
        docdict["Returns"] = "Unspecified"
    else:
        docdict["Returns"] = returns
    if (i == docsize):
        docdict["Errors"] = "Unspecified"
        return docdict
    while (i < docsize
           and (not (docstring[i].strip()).startswith("Exceptions"))):
        i = i + 1
    if (i == docsize):
        docdict["Errors"] = "Unspecified"
        return docdict

    # obtain information about errors, if given
    errors = []
    i = i + 1
    while (i < docsize):
        errdict = collections.OrderedDict()
        errline = docstring[i].split(":")
        if (errline[0].strip() == ''):
            break
        if (len(errline) == 1):
            errline = errline[0].strip()
            errdict["Status"] = errline
            errdict["Cause"] = Response.http_status_message(int(errline))
        else:
            errdict["Status"] = errline[0].strip()
            errdict["Cause"] = errline[1].strip()
        if (errdict["Cause"] == ""):
            errdict["Cause"] = Response.http_status_message(
                int(errdict["Status"]))
        errors.append(errdict)
        i = i + 1
    docdict["Errors"] = errors

    return docdict
예제 #11
0
 def error(self, code, message=None):
     self.response.set_status(code, str(message))
     if message is None: message = Response.http_status_message(code)
     self.view['message'] = message
     self.view['code'] = code
     self.render_view('system/error.html')
예제 #12
0
 def setUp(self):
     """Set up the test with a simple TestHandler."""
     h = self.MyTestHandler()
     h.request = Request.blank('/rpc/')
     h.response = Response()
     self.handler = h
예제 #13
0
 def notfound(self, code, message = None):
     self.response.set_status(code, str(message))
     if message is None: message = Response.http_status_message(code)
     self.view['message'] = message
     self.view['code'] = code
     self.render_view('system/notfound.html')