示例#1
0
文件: wsgiapp.py 项目: solos/pylons
    def find_controller(self, controller):
        """Locates a controller by attempting to import it then grab
        the SomeController instance from the imported module.

        Override this to change how the controller object is found once
        the URL has been resolved.

        """
        # Check to see if we've cached the class instance for this name
        if controller in self.controller_classes:
            return self.controller_classes[controller]

        # Pull the controllers class name, import controller
        full_module_name = self.package_name + '.controllers.' \
            + controller.replace('/', '.')

        # Hide the traceback here if the import fails (bad syntax and such)
        __traceback_hide__ = 'before_and_this'

        __import__(full_module_name)
        if hasattr(sys.modules[full_module_name], '__controller__'):
            mycontroller = getattr(
                sys.modules[full_module_name],
                sys.modules[full_module_name].__controller__)
        else:
            module_name = controller.split('/')[-1]
            class_name = class_name_from_module_name(module_name) + \
                'Controller'
            if self.log_debug:
                log.debug("Found controller, module: '%s', class: '%s'",
                          full_module_name, class_name)
            mycontroller = getattr(sys.modules[full_module_name], class_name)
        self.controller_classes[controller] = mycontroller
        return mycontroller
示例#2
0
  def find_controller( self, controller ):
    # Check to see if we've cached the class instance for this name
    if controller in self.controller_classes:
      return self.controller_classes[ controller ]

    self.__log.info( "Trying to find %s controller" % controller )
    controllerModule = controller.replace( "/", "." )
    for rootModule in self.__baseControllerPaths:
      fullModuleName = "%s.%s" % ( rootModule, controllerModule )

      # Hide the traceback here if the import fails (bad syntax and such)
      __traceback_hide__ = 'before_and_this'

      try:
        __import__( fullModuleName )
      except ImportError:
        self.__log.info( "Cannot import %s" % fullModuleName )
        continue
      if hasattr( sys.modules[ fullModuleName ], '__controller__' ):
        mycontroller = getattr( sys.modules[ fullModuleName ],
                                sys.modules[ fullModuleName ].__controller__ )
      else:
        moduleName = controller.split( '/' )[-1]
        className = class_name_from_module_name( moduleName ) + 'Controller'
        self.__log.debug( "Found controller, module: '%s', class: '%s', rootModule: '%s'" % ( fullModuleName,
                                                                                              className,
                                                                                              rootModule ) )
        mycontroller = getattr( sys.modules[ fullModuleName ], className )
      self.__log.info( "Imported %s controller" % fullModuleName )
      self.controller_classes[ controller ] = mycontroller
      return mycontroller
    self.__log.error( "Could not import controller %s" % controller )
    raise Exception( "Couldn't find controller %s in root modules %s" % ( controller,
                                                                          self.__baseControllerPaths ) )
示例#3
0
    def find_controller(self, controller):
        """Locates a controller by attempting to import it then grab the 
        SomeController instance from the imported module.
        
        Override this to change how the controller object is found once the URL
        has been resolved.
        """
        # Check to see if we've cached the class instance for this name
        if controller in self.controller_classes:
            return self.controller_classes[controller]

        # Pull the controllers class name, import controller
        full_module_name = self.package_name + '.controllers.' \
            + controller.replace('/', '.')

        # Hide the traceback here if the import fails (bad syntax and such)
        __traceback_hide__ = 'before_and_this'

        __import__(full_module_name)
        module_name = controller.split('/')[-1]
        class_name = class_name_from_module_name(module_name) + 'Controller'
        if self.log_debug:
            log.debug("Found controller, module: '%s', class: '%s'",
                      full_module_name, class_name)
        self.controller_classes[controller] = mycontroller = \
            getattr(sys.modules[full_module_name], class_name)
        return mycontroller
示例#4
0
def _controller_class_from_module(module, name):
    c = getattr(module, "__controller__", None)
    if c is None:
        name = name.rsplit("/", 1)[-1]
        class_name = class_name_from_module_name(name) + "Controller"
        c = getattr(module, class_name, None)
    return c
示例#5
0
    def make_middleware(self, app, config):
        # Hack it so our controllers pretend they are original ones! Buahahhaha!
        overriden_controlers = ['package', 'user', 'admin', 'group', 'organization']

        for controller in overriden_controlers:
            # Pull the controllers class name, import controller
            full_module_name = 'ckanext.danepubliczne.controllers.' \
                + controller.replace('/', '.')

            # Hide the traceback here if the import fails (bad syntax and such)
            __traceback_hide__ = 'before_and_this'

            __import__(full_module_name)
            if hasattr(sys.modules[full_module_name], '__controller__'):
                mycontroller = getattr(sys.modules[full_module_name],
                    sys.modules[full_module_name].__controller__)
            else:
                module_name = controller.split('/')[-1]
                class_name = class_name_from_module_name(module_name) + 'Controller'
                if app.log_debug:
                    log.debug("Found controller, module: '%s', class: '%s'",
                              full_module_name, class_name)
                mycontroller = getattr(sys.modules[full_module_name], class_name)

            app.controller_classes[controller] = mycontroller

        return app
示例#6
0
def _controller_class_from_module(module, name):
    c = getattr(module, '__controller__', None)
    if c is None:
        name = name.rsplit('/', 1)[-1]
        class_name = class_name_from_module_name(name) + 'Controller'
        c = getattr(module, class_name, None)
    return c
示例#7
0
    def make_middleware(self, app, config):
        # Hack it so our controllers pretend they are original ones! Buahahhaha!
        overriden_controlers = [
            'package', 'user', 'admin', 'group', 'organization', 'home'
        ]

        for controller in overriden_controlers:
            # Pull the controllers class name, import controller
            full_module_name = 'ckanext.danepubliczne.controllers.' \
                               + controller.replace('/', '.')

            # Hide the traceback here if the import fails (bad syntax and such)
            __traceback_hide__ = 'before_and_this'

            __import__(full_module_name)
            if hasattr(sys.modules[full_module_name], '__controller__'):
                mycontroller = getattr(
                    sys.modules[full_module_name],
                    sys.modules[full_module_name].__controller__)
            else:
                module_name = controller.split('/')[-1]
                class_name = class_name_from_module_name(
                    module_name) + 'Controller'
                if app.log_debug:
                    log.debug("Found controller, module: '%s', class: '%s'",
                              full_module_name, class_name)
                mycontroller = getattr(sys.modules[full_module_name],
                                       class_name)

            app.controller_classes[controller] = mycontroller

        return app
示例#8
0
def _controller_class_from_module(module, name):
    c = getattr(module, '__controller__', None)
    if c is None:
        name = name.rsplit('/', 1)[-1]
        class_name = class_name_from_module_name(name) + 'Controller'
        c = getattr(module, class_name, None)
    return c
示例#9
0
    def command(self):
        """Main command to create mapfish model"""
        try:
            fileOp = FileOp(source_dir=os.path.join(
                os.path.dirname(__file__), 'templates'))
            try:
                name, directory = fileOp.parse_path_name_args(self.args[0])
            except:
                raise BadCommand('No egg_info directory was found')

            # read layers.ini
            config = ConfigParser()
            config.read(['layers.ini'])
            # check passed layer is in layers.ini
            if not config.has_section(name):
                raise BadCommand(
                    'There is no layer named %s in layers.ini' % name)

            # get layer parameters
            singularName = config.get(name, 'singular')
            table = config.get(name, 'table')
            epsg = config.get(name, 'epsg')
            geomColName = config.get(name, 'geomcolumn')
            if config.has_option(name, 'schema'):
                schema = config.get(name, 'schema')
            else:
                schema = None

            # check the name isn't the same as the package
            basePkg = fileOp.find_dir('controllers', True)[0]
            if basePkg.lower() == name.lower():
                raise BadCommand(
                    'Your controller name should not be the same as '
                    'the package name %s' % basePkg)

            # validate the name
            name = name.replace('-', '_')
            validateName(name)

            # set template vars
            modelClass = util.class_name_from_module_name(singularName)
            modelTabObj = name + '_table'

            # setup the model
            fileOp.template_vars.update(
                {'modelClass': modelClass,
                 'modelTabObj': modelTabObj,
                 'table': table,
                 'epsg': epsg,
                 'geomColName': geomColName,
                 'basePkg': basePkg,
                 'schema': schema})
            fileOp.copy_file(template='model.py_tmpl',
                         dest=os.path.join('model', directory),
                         filename=name,
                         template_renderer=paste_script_template_renderer)

        except BadCommand, e:
            raise BadCommand('An error occurred. %s' % e)
示例#10
0
    def command(self):
        """Main command to create controller"""
        try:
            file_op = FileOp(source_dir=('pylons', 'templates'))
            try:
                name, directory = file_op.parse_path_name_args(self.args[0])
            except:
                raise BadCommand('No egg_info directory was found')

            # Check the name isn't the same as the package
            base_package = file_op.find_dir('controllers', True)[0]
            if base_package.lower() == name.lower():
                raise BadCommand(
                    'Your controller name should not be the same as '
                    'the package name %r.' % base_package)
            # Validate the name
            name = name.replace('-', '_')
            validate_name(name)

            # Determine the module's import statement
            if is_minimal_template(base_package):
                importstatement = (
                    'from %s.controllers import BaseController' % base_package)
            else:
                importstatement = ('from %s.lib.base import BaseController' %
                                   base_package)
            if defines_render(base_package):
                importstatement += ', render'

            # Setup the controller
            fullname = os.path.join(directory, name)
            controller_name = util.class_name_from_module_name(
                name.split('/')[-1])
            if not fullname.startswith(os.sep):
                fullname = os.sep + fullname
            testname = fullname.replace(os.sep, '_')[1:]

            module_dir = directory.replace('/', os.path.sep)
            check_controller_existence(base_package, module_dir, name)

            file_op.template_vars.update({
                'name': controller_name,
                'fname': os.path.join(directory, name),
                'tmpl_name': name,
                'package': base_package,
                'importstatement': importstatement
            })
            file_op.copy_file(template='controller.py_tmpl',
                              dest=os.path.join('controllers', directory),
                              filename=name,
                              template_renderer=paste_script_template_renderer)
            if not self.options.no_test:
                file_op.copy_file(
                    template='test_controller.py_tmpl',
                    dest=os.path.join('tests', 'functional'),
                    filename='test_' + testname,
                    template_renderer=paste_script_template_renderer)
        except BadCommand, e:
            raise BadCommand('An error occurred. %s' % e)
示例#11
0
    def _find_controller(self, controller):
        full_module_name = self.basePackage + controller.replace('/', '.')
        module = __import__(full_module_name, fromlist='__name__')
        module_name = controller.split('/')[-1]
        class_name = class_name_from_module_name(module_name) + 'Controller'

        controller = getattr(module, class_name)
        return controller
示例#12
0
    def command(self):
        """Main command to create controller"""
        try:
            file_op = FileOp(source_dir=('pylons', 'templates'))
            try:
                name, directory = file_op.parse_path_name_args(self.args[0])
            except:
                raise BadCommand('No egg_info directory was found')

            # Check the name isn't the same as the package
            base_package = file_op.find_dir('controllers', True)[0]
            if base_package.lower() == name.lower():
                raise BadCommand(
                    'Your controller name should not be the same as '
                    'the package name %r.' % base_package)
            # Validate the name
            name = name.replace('-', '_')
            validate_name(name)

            # Determine the module's import statement
            if is_minimal_template(base_package):
                importstatement = ('from %s.controllers import BaseController'
                                   % base_package)
            else:
                importstatement = ('from %s.lib.base import BaseController' %
                                   base_package)
            if defines_render(base_package):
                importstatement += ', render'

            # Setup the controller
            fullname = os.path.join(directory, name)
            controller_name = util.class_name_from_module_name(
                name.split('/')[-1])
            if not fullname.startswith(os.sep):
                fullname = os.sep + fullname
            testname = fullname.replace(os.sep, '_')[1:]

            module_dir = directory.replace('/', os.path.sep)
            check_controller_existence(base_package, module_dir, name)

            file_op.template_vars.update(
                {'name': controller_name,
                 'fname': os.path.join(directory, name).replace('\\', '/'),
                 'tmpl_name': name,
                 'package': base_package,
                 'importstatement': importstatement})
            file_op.copy_file(template='controller.py_tmpl',
                              dest=os.path.join('controllers', directory),
                              filename=name,
                              template_renderer=paste_script_template_renderer)
            if not self.options.no_test:
                file_op.copy_file(
                    template='test_controller.py_tmpl',
                    dest=os.path.join('tests', 'functional'),
                    filename='test_' + testname,
                    template_renderer=paste_script_template_renderer)
        except BadCommand, e:
            raise BadCommand('An error occurred. %s' % e)
示例#13
0
    def command(self):

        try:
            file_op = FileOp(source_dir=("pylons", "templates"))
            try:
                name, directory = file_op.parse_path_name_args(self.args[0])
            except:
                raise BadCommand("No egg_info directory was found")

            base_package = file_op.find_dir("controllers", True)[0]
            if base_package.lower() == name.lower():
                raise BadCommand(
                    "Your controller name should not be the same as " "the package name %r." % base_package
                )
            name = name.replace("-", "_")
            validate_name(name)

            if is_minimal_template(base_package):
                importstatement = "from %s.controllers import BaseController" % base_package
            else:
                importstatement = "from %s.lib.base import BaseController" % base_package
            if defines_render(base_package):
                importstatement += ", render"

            fullname = os.path.join(directory, name)
            controller_name = util.class_name_from_module_name(name.split("/")[-1])
            if not fullname.startswith(os.sep):
                fullname = os.sep + fullname
            testname = fullname.replace(os.sep, "_")[1:]

            module_dir = directory.replace("/", os.path.sep)
            check_controller_existence(base_package, module_dir, name)

            file_op.template_vars.update(
                {
                    "name": controller_name,
                    "fname": os.path.join(directory, name).replace("\\", "/"),
                    "tmpl_name": name,
                    "package": base_package,
                    "importstatement": importstatement,
                }
            )
            file_op.copy_file(
                template="controller.py_tmpl",
                dest=os.path.join("controllers", directory),
                filename=name,
                template_renderer=paste_script_template_renderer,
            )
            if not self.options.no_test:
                file_op.copy_file(
                    template="test_controller.py_tmpl",
                    dest=os.path.join("tests", "functional"),
                    filename="test_" + testname,
                    template_renderer=paste_script_template_renderer,
                )
        except BadCommand, e:
            raise BadCommand("An error occurred. %s" % e)
示例#14
0
    def command(self):
        try:
            file_op = FileOp(source_dir=('pylons', 'templates'))
            try:
                name, directory = file_op.parse_path_name_args(self.args[0])
            except:
                raise BadCommand('No egg_info directory was found')

            base_package = file_op.find_dir('model', True)[0]
            if base_package.lower() == name.lower():
                raise BadCommand('Your moedl name should not be the same as '
                                 'the package name %r.' % base_package)
            name = name.replace('-', '_')

            if not is_minimal_template(base_package):
                importstatement = 'from %s.model.meta import *' % base_package

            fullname = os.path.join(directory, name)
            model_name = util.class_name_from_module_name(name.split('/')[-1])
            if not fullname.startswith(os.sep):
                fullname = os.sep + fullname

            module_dir = directory.replace('/', os.path.sep)

            fields = {}
            for arg in self.args[1:]:
                field_args = arg.split(':')
                field_name = field_args[0]

                if field_args[1] != 'ForeignKey':
                    if len(field_args) == 2:
                        field_type = field_args[1]
                    elif len(field_args) == 3:
                        field_type = "%s(%s)" % (field_args[1], field_args[2])

                fields[field_name] = field_type

            file_op.template_vars.update(
                {'name': model_name,
                 'tablename': name,
                 'importstatement': importstatement,
                 'fields': fields})
            file_op.copy_file(template='model.py_tmpl',
                              dest=os.path.join('model', directory),
                              filename=name,
                              template_renderer=paste_script_template_renderer)
            model_directory = file_op.find_dir('model', True)[1]
            self.insert_into_file(os.path.join(model_directory, '__init__.py'), 'model_declaration',
                                  'from %s.model.%s import %s\n' % (base_package, name, model_name))

            self.run_command('alembic', 'revision', '--autogenerate', '-m', 'add %s model' % model_name)

        except BadCommand, e:
            raise BadCommand('An error occurred. %s' % e)
示例#15
0
    def find_controller(self, controller):
        """Locates a controller by attempting to import it then grab
        the SomeController instance from the imported module.
        
        Controller name is assumed to be a module in the controllers
        directory unless it contains a '.' or ':' which is then assumed
        to be a dotted path to the module and name of the controller
        object.
        
        Override this to change how the controller object is found once
        the URL has been resolved.
        
        """
        # If this isn't a basestring, its an object, assume that its the
        # proper instance to begin with
        if not isinstance(controller, basestring):
            return controller

        # Check to see if we've cached the class instance for this name
        if controller in self.controller_classes:
            return self.controller_classes[controller]

        # Check to see if its a dotted name
        if '.' in controller or ':' in controller:
            mycontroller = pkg_resources.EntryPoint.parse(
                'x=%s' % controller).load(False)
            self.controller_classes[controller] = mycontroller
            return mycontroller

        # Pull the controllers class name, import controller
        full_module_name = self.package_name + '.controllers.' \
            + controller.replace('/', '.')

        # Hide the traceback here if the import fails (bad syntax and such)
        __traceback_hide__ = 'before_and_this'

        __import__(full_module_name)
        if hasattr(sys.modules[full_module_name], '__controller__'):
            mycontroller = getattr(
                sys.modules[full_module_name],
                sys.modules[full_module_name].__controller__)
        else:
            module_name = controller.split('/')[-1]
            class_name = class_name_from_module_name(
                module_name) + 'Controller'
            if self.log_debug:
                log.debug("Found controller, module: '%s', class: '%s'",
                          full_module_name, class_name)
            mycontroller = getattr(sys.modules[full_module_name], class_name)
        self.controller_classes[controller] = mycontroller
        return mycontroller
示例#16
0
    def find_controller(self, controller):
        """Locates a controller by attempting to import it then grab
        the SomeController instance from the imported module.

        Controller name is assumed to be a module in the controllers
        directory unless it contains a '.' or ':' which is then assumed
        to be a dotted path to the module and name of the controller
        object.

        Override this to change how the controller object is found once
        the URL has been resolved.

        """
        # If this isn't a basestring, its an object, assume that its the
        # proper instance to begin with
        if not isinstance(controller, basestring):
            return controller

        # Check to see if we've cached the class instance for this name
        if controller in self.controller_classes:
            return self.controller_classes[controller]

        # Check to see if its a dotted name
        if '.' in controller or ':' in controller:
            mycontroller = pkg_resources.EntryPoint.parse(
                'x=%s' % controller).load(False)
            self.controller_classes[controller] = mycontroller
            return mycontroller

        # Pull the controllers class name, import controller
        full_module_name = self.package_name + '.controllers.' \
            + controller.replace('/', '.')

        # Hide the traceback here if the import fails (bad syntax and such)
        __traceback_hide__ = 'before_and_this'

        __import__(full_module_name)
        if hasattr(sys.modules[full_module_name], '__controller__'):
            mycontroller = getattr(sys.modules[full_module_name],
                sys.modules[full_module_name].__controller__)
        else:
            module_name = controller.split('/')[-1]
            class_name = class_name_from_module_name(module_name) + 'Controller'
            if self.log_debug:
                log.debug("Found controller, module: '%s', class: '%s'",
                          full_module_name, class_name)
            mycontroller = getattr(sys.modules[full_module_name], class_name)
        self.controller_classes[controller] = mycontroller
        return mycontroller
示例#17
0
    def command(self):
        """Main command to create a mapfish controller"""
        try:
            fileOp = FileOp(source_dir=os.path.join(
                os.path.dirname(__file__), 'templates'))
            try:
                name, directory = fileOp.parse_path_name_args(self.args[0])
            except:
                raise BadCommand('No egg_info directory was found')

            # read layers.ini
            config = ConfigParser()
            config.read(['layers.ini'])
            # check passed layer is in layers.ini
            if not config.has_section(name):
                raise BadCommand(
                    'There is no layer named %s in layers.ini' % name)

            # get layer parameters
            singularName = config.get(name, 'singular')
            pluralName = config.get(name, 'plural')
            epsg = config.get(name, 'epsg')
            units = config.get(name, 'units')

            # check the name isn't the same as the package
            basePkg = fileOp.find_dir('controllers', True)[0]
            if basePkg.lower() == name.lower():
                raise BadCommand(
                    'Your controller name should not be the same as '
                    'the package name %s' % basePkg)

            # validate the name
            name = name.replace('-', '_')
            validateName(name)

            # set test file name
            fullName = os.path.join(directory, name)
            if not fullName.startswith(os.sep):
                fullName = os.sep + fullName
            testName = fullName.replace(os.sep, '_')[1:]

            # set template vars
            modName = name
            fullModName = os.path.join(directory, name)
            contrClass = util.class_name_from_module_name(name)
            modelClass = util.class_name_from_module_name(singularName)
            modelTabObj = name + '_table'

            # setup the controller
            fileOp.template_vars.update(
                {'modName': modName,
                 'fullModName': fullModName,
                 'singularName': singularName,
                 'pluralName': pluralName,
                 'contrClass': contrClass,
                 'modelClass': modelClass,
                 'modelTabObj': modelTabObj,
                 'basePkg': basePkg,
                 'epsg': epsg,
                 'units': units})
            fileOp.copy_file(template='controller.py_tmpl',
                         dest=os.path.join('controllers', directory),
                         filename=name)
            if not self.options.no_test:
                fileOp.copy_file(template='test_controller.py_tmpl',
                             dest=os.path.join('tests', 'functional'),
                             filename='test_' + testName)

        except BadCommand, e:
            raise BadCommand('An error occurred. %s' % e)
示例#18
0
    def command(self):
        """Main command to create controller"""
        try:
            file_op = FileOp(source_dir=os.path.join(
                os.path.dirname(__file__), 'templates'))
            try:
                singularname, singulardirectory = \
                    file_op.parse_path_name_args(self.args[0])
                pluralname, pluraldirectory = \
                    file_op.parse_path_name_args(self.args[1])
            except:
                raise BadCommand('No egg_info directory was found')

            # Check the name isn't the same as the package
            base_package = file_op.find_dir('controllers', True)[0]
            if base_package.lower() == pluralname.lower():
                raise BadCommand(
                    'Your controller name should not be the same as '
                    'the package name %r.'% base_package)
            # Validate the name
            for name in [singularname, pluralname]:
                name = name.replace('-', '_')
                validate_name(name)

            # Determine the module's import statement
            if is_minimal_template(base_package):
                importstatement = "from %s.controllers import *" % base_package
            else:
                importstatement = "from %s.lib.base import *" % base_package

            # Setup the controller
            fullname = os.path.join(pluraldirectory, pluralname)
            controller_name = util.class_name_from_module_name(
                pluralname.split('/')[-1])
            if not fullname.startswith(os.sep):
                fullname = os.sep + fullname
            testname = fullname.replace(os.sep, '_')[1:]

            nameprefix = ''
            if pluraldirectory:
                nameprefix = pluraldirectory.replace(os.path.sep, '_') + '_'

            controller_c = ''
            if nameprefix:
                controller_c = ", controller='%s', \n\t" % \
                    '/'.join([pluraldirectory, pluralname])
                controller_c += "path_prefix='/%s', name_prefix='%s_'" % \
                    (pluraldirectory, pluraldirectory)
            command = "map.resource('%s', '%s'%s)\n" % \
                (singularname, pluralname, controller_c)

            file_op.template_vars.update(
                {'classname': controller_name,
                 'pluralname': pluralname,
                 'singularname': singularname,
                 'name': controller_name,
                 'nameprefix': nameprefix,
                 'resource_command': command.replace('\n\t', '\n%s#%s' % \
                                                         (' '*4, ' '*9)),
                 'fname': os.path.join(pluraldirectory, pluralname),
                 'importstatement': importstatement})

            resource_command = ("\nTo create the appropriate RESTful mapping, "
                                "add a map statement to your\n")
            resource_command += ("config/routing.py file near the top like "
                                 "this:\n\n")
            resource_command += command
            file_op.copy_file(template='restcontroller.py_tmpl',
                         dest=os.path.join('controllers', pluraldirectory),
                         filename=pluralname)
            if not self.options.no_test:
                file_op.copy_file(template='test_controller.py_tmpl',
                             dest=os.path.join('tests', 'functional'),
                             filename='test_'+testname)
            print resource_command
        except BadCommand, e:
            raise BadCommand('An error occurred. %s' % e)
示例#19
0
class SecretHashController(BaseController):
    def lookup(self, hash):
        c.hash = URLHash.find_by_hash(hash)
        if c.hash is None:
            abort(404, "Sorry, Invalid Hash.")

        return self.transfer(url=c.hash.url)

    # as per http://www.mail-archive.com/[email protected]/msg06643.html
    def transfer(controller=None, action=None, url=None, **kwargs):
        """usage:
        1. result = transfer(url = "/someurl/someaction")
        2. result = transfer(controller = "/controller1/sub_controller2",
    action = "test") # kwargs will pass to action.
        """

        if (url != None):
            route_map = config['routes.map']
            match_route = route_map.match(url)
            if (match_route == None):
                raise (Exception("no route matched url '%s'" % url))
            # if
            controller = match_route["controller"].replace("/", ".")
            action = match_route["action"]
            del (match_route["controller"])
            del (match_route["action"])
            kwargs.update(match_route)
        else:
            if (controller == None):
                route_map = config['routes.map']
                match_route = route_map.match("/")
                if (match_route == None):
                    raise (Exception("no route matched url '%s'" % url))
                # if
                controller = match_route["controller"].replace("/", ".")
                if (action == None):
                    action = match_route["action"]
                # if
                del (match_route["controller"])
                del (match_route["action"])
                kwargs.update(match_route)
            else:
                controller = controller.replace("/", ".")
                if (action == None):
                    action = "index"
                # if
            # if
        # if
        full_module_name = config[
            'pylons.package'] + '.controllers.' + controller
        __traceback_hide__ = 'before_and_this'
        try:
            __import__(full_module_name)
        except ImportError, e:
            raise (NotImplementedError("'%s' not found: %s" % (controller, e)))
        # try
        module_name = controller.split('.')[-1]
        class_name = class_name_from_module_name(module_name) + 'Controller'
        controller_class = getattr(sys.modules[full_module_name], class_name)
        controller_inst = controller_class()
        if (hasattr(controller_inst, action)):
            action_method = getattr(controller_inst, action, None)
            #if (not isinstance(action_method, types.MethodType)):
            #    raise(NotImplementedError("action '%s' not found in '%s'" % (action, controller)))
            # if
            if (hasattr(controller_inst, "__before__")):
                before_method = getattr(controller_inst, "__before__", None)
                #if (isinstance(before_method, types.MethodType)):
                #    before_method(action)
                # if
            # if
            action_args_name, action_args, action_kargs, action_defaults = inspect.getargspec(
                action_method)
            del (action_args_name[0])
            call_kargs = {}
            for k, v in kwargs.iteritems():
                if (k in action_args_name):
                    call_kargs[k] = v
                # if
            # for
            result = action_method(**call_kargs)
            if (hasattr(controller_inst, "__after__")):
                after_method = getattr(controller_inst, "__after__", None)
                #if (isinstance(after_method, types.MethodType)):
                #    after_method(action)
                # if
            # if
            return (result)
        else:
            raise (NotImplementedError("action '%s' not found in '%s'" %
                                       (action, controller)))
示例#20
0
    def command(self):

        try:
            file_op = FileOp(source_dir=("pylons", "templates"))
            try:
                singularname, singulardirectory = file_op.parse_path_name_args(self.args[0])
                pluralname, pluraldirectory = file_op.parse_path_name_args(self.args[1])

            except:
                raise BadCommand("No egg_info directory was found")

            base_package = file_op.find_dir("controllers", True)[0]
            if base_package.lower() == pluralname.lower():
                raise BadCommand(
                    "Your controller name should not be the same as " "the package name %r." % base_package
                )
            for name in [pluralname]:
                name = name.replace("-", "_")
                validate_name(name)

            if is_minimal_template(base_package):
                importstatement = "from %s.controllers import BaseController" % base_package
            else:
                importstatement = "from %s.lib.base import BaseController" % base_package
            if defines_render(base_package):
                importstatement += ", render"

            module_dir = pluraldirectory.replace("/", os.path.sep)
            check_controller_existence(base_package, module_dir, name)

            fullname = os.path.join(pluraldirectory, pluralname)
            controller_name = util.class_name_from_module_name(pluralname.split("/")[-1])
            if not fullname.startswith(os.sep):
                fullname = os.sep + fullname
            testname = fullname.replace(os.sep, "_")[1:]

            nameprefix = ""
            path = ""
            if pluraldirectory:
                nameprefix = pluraldirectory.replace(os.path.sep, "_") + "_"
                path = pluraldirectory + "/"

            controller_c = ""
            if nameprefix:
                controller_c = ", controller='%s', \n\t" % "/".join([pluraldirectory, pluralname])
                controller_c += "path_prefix='/%s', name_prefix='%s'" % (pluraldirectory, nameprefix)
            command = "map.resource('%s', '%s'%s)\n" % (singularname, pluralname, controller_c)

            file_op.template_vars.update(
                {
                    "classname": controller_name,
                    "pluralname": pluralname,
                    "singularname": singularname,
                    "name": controller_name,
                    "nameprefix": nameprefix,
                    "package": base_package,
                    "path": path,
                    "resource_command": command.replace("\n\t", "\n%s#%s" % (" " * 4, " " * 9)),
                    "fname": os.path.join(pluraldirectory, pluralname),
                    "importstatement": importstatement,
                }
            )

            resource_command = "\nTo create the appropriate RESTful mapping, " "add a map statement to your\n"
            resource_command += "config/routing.py file near the top like " "this:\n\n"
            resource_command += command
            file_op.copy_file(
                template="restcontroller.py_tmpl",
                dest=os.path.join("controllers", pluraldirectory),
                filename=pluralname,
                template_renderer=paste_script_template_renderer,
            )
            if not self.options.no_test:
                file_op.copy_file(
                    template="test_restcontroller.py_tmpl",
                    dest=os.path.join("tests", "functional"),
                    filename="test_" + testname,
                    template_renderer=paste_script_template_renderer,
                )
            print resource_command
        except BadCommand, e:
            raise BadCommand("An error occurred. %s" % e)
示例#21
0
    def command(self):
        """Main command to create mapfish model"""
        try:
            # read layers.ini
            config = ConfigParser()
            config.read(['layers.ini'])
            # check passed layer is in layers.ini
            sectionName = self.args[0]
            if not config.has_section(sectionName):
                raise BadCommand(
                    'There is no layer section named %s in layers.ini' % \
                    sectionName)

            # get layer parameters
            singular = config.get(sectionName, 'singular')
            plural = config.get(sectionName, 'plural')
            table = config.get(sectionName, 'table')
            epsg = config.get(sectionName, 'epsg')
            geomColName = config.get(sectionName, 'geomcolumn')
            if config.has_option(sectionName, 'schema'):
                schema = config.get(sectionName, 'schema')
            else:
                schema = None

            # get geometry type
            if not config.has_option(sectionName, 'geomtype'):
                geomtype = 'Geometry'
            else:
                raw_geomtype = config.get(sectionName, 'geomtype')
                # check if the value is valid (geometries supported by GeoAlchemy)
                valid_types = ['Geometry', 'Point', 'Curve', 'LineString', 'Polygon',
                                'MultiPoint', 'MultiLineString', 'MultiPolygon', 'GeometryCollection']
                
                if raw_geomtype in valid_types:
                    geomtype = raw_geomtype
                else:
                    raise BadCommand('Geometry type "%s" is unknown, valid values are: %s' 
                                        % (raw_geomtype, valid_types))

            fileOp = FileOp(source_dir=os.path.join(
                os.path.dirname(__file__), 'templates'))
            try:
                singularName, singularDirectory = \
                    fileOp.parse_path_name_args(singular)
                pluralName, pluralDirectory = \
                    fileOp.parse_path_name_args(plural)
            except:
                raise BadCommand('No egg_info directory was found')

            # check the name isn't the same as the package
            basePkg = fileOp.find_dir('model', True)[0]
            if basePkg.lower() == pluralName.lower():
                raise BadCommand(
                    'Your model name should not be the same as '
                    'the package name %s' % basePkg)

            # validate the name
            name = pluralName.replace('-', '_')
            validateName(name)

            # set template vars
            modelClass = util.class_name_from_module_name(singularName)

            # setup the model
            fileOp.template_vars.update(
                {'modelClass': modelClass,
                 'table': table,
                 'epsg': epsg,
                 'geomColName': geomColName,
                 'geomType': geomtype,
                 'basePkg': basePkg,
                 'schema': schema})
            fileOp.copy_file(template='model.py_tmpl',
                         dest=os.path.join('model', pluralDirectory),
                         filename=name,
                         template_renderer=paste_script_template_renderer)

        except BadCommand, e:
            raise BadCommand('An error occurred. %s' % e)
示例#22
0
    def command(self):
        """Main command to create a mapfish controller"""
        try:
            # read layers.ini
            config = ConfigParser()
            config.read(['layers.ini'])
            # check passed layer is in layers.ini
            sectionName = self.args[0]
            if not config.has_section(sectionName):
                raise BadCommand(
                    'There is no layer section named %s in layers.ini' % \
                    sectionName)

            # get layer parameters
            singular = config.get(sectionName, 'singular')
            plural = config.get(sectionName, 'plural')
            epsg = config.get(sectionName, 'epsg')

            fileOp = FileOp(source_dir=os.path.join(
                os.path.dirname(__file__), 'templates'))
            try:
                singularName, singularDirectory = \
                    fileOp.parse_path_name_args(singular)
                pluralName, pluralDirectory = \
                    fileOp.parse_path_name_args(plural)
            except Exception, e:
                raise BadCommand('No egg_info directory was found')

            # check the name isn't the same as the package
            basePkg = fileOp.find_dir('controllers', True)[0]
            if basePkg.lower() == pluralName.lower():
                raise BadCommand(
                    'Your controller name should not be the same as '
                    'the package name %s' % basePkg)

            # validate the name
            name = pluralName.replace('-', '_')
            validateName(name)

            # set test file name
            fullName = os.path.join(pluralDirectory, name)
            if not fullName.startswith(os.sep):
                fullName = os.sep + fullName
            testName = fullName.replace(os.sep, '_')[1:]

            # set template vars
            modName = name
            fullModName = os.path.join(pluralDirectory, name)
            contrClass = util.class_name_from_module_name(name)
            modelClass = util.class_name_from_module_name(singularName)

            # setup the controller
            fileOp.template_vars.update(
                {'modName': modName,
                 'fullModName': fullModName,
                 'singularName': singularName,
                 'pluralName': pluralName,
                 'contrClass': contrClass,
                 'modelClass': modelClass,
                 'basePkg': basePkg})
            fileOp.copy_file(template='controller.py_tmpl',
                         dest=os.path.join('controllers', pluralDirectory),
                         filename=name,
                         template_renderer=paste_script_template_renderer)
            if not self.options.no_test:
                fileOp.copy_file(template='test_controller.py_tmpl',
                             dest=os.path.join('tests', 'functional'),
                             filename='test_' + testName,
                             template_renderer=paste_script_template_renderer)
            
            resource_command = ("\nTo create the appropriate RESTful mapping, "
                                "add a map statement to your\n")
            resource_command += ("config/routing.py file in the CUSTOM ROUTES section "
                                 "like this:\n\n") 
            resource_command += ('map.connect("/%s/count", controller="%s", '
                                 'action="count")\n' % (pluralName, pluralName))
            resource_command += 'map.resource("%s", "%s")\n' % \
                    (singularName, pluralName)

            print resource_command
示例#23
0
    def command(self):
        """Main command to create controller"""
        try:
            file_op = FileOp(source_dir=('pylons', 'templates'))
            try:
                singularname, singulardirectory = \
                    file_op.parse_path_name_args(self.args[0])
                pluralname, pluraldirectory = \
                    file_op.parse_path_name_args(self.args[1])

            except:
                raise BadCommand('No egg_info directory was found')

            # Check the name isn't the same as the package
            base_package = file_op.find_dir('controllers', True)[0]
            if base_package.lower() == pluralname.lower():
                raise BadCommand(
                    'Your controller name should not be the same as '
                    'the package name %r.' % base_package)
            # Validate the name
            for name in [pluralname]:
                name = name.replace('-', '_')
                validate_name(name)

            # Determine the module's import statement
            if is_minimal_template(base_package):
                importstatement = ('from %s.controllers import BaseController'
                                   % base_package)
            else:
                importstatement = ('from %s.lib.base import BaseController' %
                                   base_package)
            if defines_render(base_package):
                importstatement += ', render'

            module_dir = pluraldirectory.replace('/', os.path.sep)
            check_controller_existence(base_package, module_dir, name)

            # Setup the controller
            fullname = os.path.join(pluraldirectory, pluralname)
            controller_name = util.class_name_from_module_name(
                pluralname.split('/')[-1])
            if not fullname.startswith(os.sep):
                fullname = os.sep + fullname
            testname = fullname.replace(os.sep, '_')[1:]

            nameprefix = ''
            path = ''
            if pluraldirectory:
                nameprefix = pluraldirectory.replace(os.path.sep, '_') + '_'
                path = pluraldirectory + '/'

            controller_c = ''
            if nameprefix:
                controller_c = ", controller='%s', \n\t" % \
                    '/'.join([pluraldirectory, pluralname])
                controller_c += "path_prefix='/%s', name_prefix='%s'" % \
                    (pluraldirectory, nameprefix)
            command = "map.resource('%s', '%s'%s)\n" % \
                (singularname, pluralname, controller_c)

            file_op.template_vars.update(
                {'classname': controller_name,
                 'pluralname': pluralname,
                 'singularname': singularname,
                 'name': controller_name,
                 'nameprefix': nameprefix,
                 'package': base_package,
                 'path': path,
                 'resource_command': command.replace('\n\t', '\n%s#%s' % \
                                                         (' ' * 4, ' ' * 9)),
                 'fname': os.path.join(pluraldirectory, pluralname),
                 'importstatement': importstatement})

            resource_command = ("\nTo create the appropriate RESTful mapping, "
                                "add a map statement to your\n")
            resource_command += ("config/routing.py file near the top like "
                                 "this:\n\n")
            resource_command += command
            file_op.copy_file(template='restcontroller.py_tmpl',
                              dest=os.path.join('controllers', pluraldirectory),
                              filename=pluralname,
                              template_renderer=paste_script_template_renderer)
            if not self.options.no_test:
                file_op.copy_file(
                    template='test_restcontroller.py_tmpl',
                    dest=os.path.join('tests', 'functional'),
                    filename='test_' + testname,
                    template_renderer=paste_script_template_renderer)
            print resource_command
        except BadCommand, e:
            raise BadCommand('An error occurred. %s' % e)