Beispiel #1
0
    def __init__(cls, name, bases, ns):
        try:
            if Model not in bases:
                # Allow for inheritance of the Model object
                # for use with SqlAlchemy inheritance patterns
                super(ModelMeta, cls).__init__(name, bases, ns)
                return
        except NameError:
            # if this is the Model class, then just return
            return

        # set the tablename, if it's user set, use that, otherwise use a
        # function to create one
        cls.__tablename__ = getattr(cls, "__tablename__",
                                    pluralize(camel_to_underscore(name)))
        # tableargs adds autoload to create schema reflection
        cls.__table_args__ = getattr(cls, "__table_args__", {})

        if project.schema_reflection:
            # create or update the __table_args__ attribute
            cls.__table_args__['autoload'] = True
        if project.global_table_args:
            cls.__table_args__.update(project.global_table_args)

        # check if the class has at least one primary key
        # if not, automatically generate one.
        has_primary = any([False] + [value.primary_key
                                     for value in cls.__dict__.values()
                                     if isinstance(value, Column)])
        if not has_primary:
            # treat the id as a mixin w/copy
            surrogate_pk = surrogate_pk_template.copy()
            surrogate_pk._creation_order = surrogate_pk_template._creation_order
            cls.id = surrogate_pk
        super(ModelMeta, cls).__init__(name, bases, ns)
Beispiel #2
0
        def __init__(cls, name, bases, ns):
            try:
                if Model not in bases:
                    # Allow for inheritance of the Model object
                    # for use with SqlAlchemy inheritance patterns
                    super(ModelMeta, cls).__init__(name, bases, ns)
                    return
            except NameError:
                # if this is the Model class, then just return
                return

            # set the tablename, if it's user set, use that, otherwise use a
            # function to create one
            cls.__tablename__ = getattr(cls, "__tablename__",
                                        pluralize(camel_to_underscore(name)))
            # tableargs adds autoload to create schema reflection
            cls.__table_args__ = getattr(cls, "__table_args__", {})

            if context.config.schema_reflection:
                # create or update the __table_args__ attribute
                cls.__table_args__['autoload'] = True
            if context.config.global_table_args:
                cls.__table_args__.update(context.config.global_table_args)

            # check if the class has at least one primary key
            # if not, automatically generate one.
            has_primary = any([False] + [value.primary_key
                                         for value in cls.__dict__.values()
                                         if isinstance(value, sqlalchemy.Column)])
            if not has_primary:
                # treat the id as a mixin w/copy
                surrogate_pk = surrogate_pk_template.copy()
                surrogate_pk._creation_order = surrogate_pk_template._creation_order
                cls.id = surrogate_pk
            super(ModelMeta, cls).__init__(name, bases, ns)
Beispiel #3
0
    def load(self):
        '''
        Loads controllers from app.controllers. Uses the controller name to
        define a path to controller mapping. It does some text munging to
        camel-case the module name to look up the expected classname in the
        modules. It loads all controller candidates into a mapping block to
        look up URLs against.

        Called only once at the start of a pybald application.
        '''

        controller_names = []
        for controller in my_project.app.controllers.__all__:
            controller_name = camel_to_underscore(controller)
            try:
                controller_path_name = self.controller_pattern.search(
                                                      controller_name).group(1)
            except AttributeError:
                controller_path_name = controller_name
            controller_names.append(controller_path_name)
            # self.controllers holds paths to map to modules and controller
            # names
            self.controllers[controller_path_name] = getattr(my_project.app.controllers,
                                                                    controller)

        # register the controller module names
        # with the mapper, creates the internal regular
        # expressions
        self.map.create_regs(controller_names)
Beispiel #4
0
    def load(self, controllers):
        """
        Handles walking the registry (or old-style controller module) and
        builds the lookup table for controller classes to match against.

        Does some text munging to change the camel-case class names into
        underscore-separated url like names. (HomeController to home)

        :param controllers: A controller registry

        All controller candidates are loaded into a hash to look up
        the matched "controller" urlvar against.

        The _controller suffix is removed from the module name for the url
        route mapping table (so controller="home" matches home_controller).

        against and the routes regex is initialized with a list of controller
        names.

        Called only once at the start of a pybald application.
        """

        controller_names = []
        # switch between old-style package container and registry model
        # both should work here
        if hasattr(controllers, "__all__"):
            controller_iterator = ((name, getattr(controllers, name)) for name in controllers.__all__)
        else:
            controller_iterator = ((controller.__name__, controller) for controller in controllers)
        for name, controller in controller_iterator:
            controller_name = camel_to_underscore(name)
            try:
                controller_path_name = self.controller_pattern.search(controller_name).group(1)
            except AttributeError:
                controller_path_name = controller_name
            controller_names.append(controller_path_name)
            # self.controllers holds paths to map to modules and controller
            # names
            self.controllers[controller_path_name] = controller

        # register the controller module names
        # with the mapper, creates the internal regular
        # expressions
        self.map.create_regs(controller_names)
Beispiel #5
0
    def action_wrapper(self, environ, start_response):
        req = Request(environ)
        # add any url variables as members of the controller
        for key in req.urlvars.keys():
            #Set the controller object to contain the url variables
            # parsed from the dispatcher / router
            setattr(self, key, req.urlvars[key])

        # this code defines the template id to match against
        # template path = controller name + '/' + action name (except in the case of)
        # index
        try:
            template_root_name = camel_to_underscore(
                      controller_pattern.search(self.__class__.__name__
                                           ).group(1))
        except AttributeError:
            template_root_name = ''
        self.template_id = "/".join(filter(lambda x: x != '', [template_root_name, template_name]))

        # add the pybald extension dict to the controller
        # object
        for key, value in req.environ.get('pybald.extension', {}).items():
            setattr(self, key, value)
        setattr(self, 'request', req)
        setattr(self, 'request_url', req.url)

        # Return either the controllers _pre code, whatever
        # is returned from the controller
        # or the view. So pre has precedence over
        # the return which has precedence over the view
        none_func = lambda *pargs, **kargs: None
        pre = getattr(self, '_pre', none_func)
        post = getattr(self, '_post', none_func)
        view = getattr(self, '_view', none_func)

        resp = pre(req) or method(self, req) or view()

        # if the response is currently a string
        # wrap it in a response object
        if isinstance(resp, basestring):
            resp = Response(body=resp, charset="utf-8")
        # run the controllers post code
        post(req, resp)
        return resp(environ, start_response)
Beispiel #6
0
    def load(self, controllers):
        '''
        Walks the controller registry and builds the lookup table for
        controller classes to match against.

        Does some text munging to change the camel-case class names into
        underscore-separated url like names. (HomeController to home)

        :param controllers: A controller registry, a list of all controllers
                            that will be used with this application.

        All controller candidates are loaded into a hash to look up
        the matched "controller" urlvar against.

        The _controller suffix is removed from the module name for the url
        route mapping table (so controller="home" matches home_controller).

        This method is called only once at the start of a pybald application.
        '''

        controller_names = []
        controller_iterator = ((controller.__name__, controller) for
                                   controller in controllers)
        for name, controller in controller_iterator:
            controller_name = camel_to_underscore(name)
            try:
                controller_path_name = self.controller_pattern.search(
                                                    controller_name).group(1)
            except AttributeError:
                controller_path_name = controller_name
            controller_names.append(controller_path_name)
            # self.controllers holds paths to map to modules and controller
            # names
            self.controllers[controller_path_name] = controller

        # register the controller module names
        # with the mapper, creates the internal regular
        # expressions
        self.map.create_regs(controller_names)
Beispiel #7
0
    def load(self, controllers):
        '''
        Walks the controller registry and builds the lookup table for
        controller classes to match against.

        Does some text munging to change the camel-case class names into
        underscore-separated url like names. (HomeController to home)

        :param controllers: A controller registry, a list of all controllers
                            that will be used with this application.

        All controller candidates are loaded into a hash to look up
        the matched "controller" urlvar against.

        The _controller suffix is removed from the module name for the url
        route mapping table (so controller="home" matches home_controller).

        This method is called only once at the start of a pybald application.
        '''

        controller_names = []
        controller_iterator = ((controller.__name__, controller)
                               for controller in controllers)
        for name, controller in controller_iterator:
            controller_name = camel_to_underscore(name)
            try:
                controller_path_name = self.controller_pattern.search(
                    controller_name).group(1)
            except AttributeError:
                controller_path_name = controller_name
            controller_names.append(controller_path_name)
            # self.controllers holds paths to map to modules and controller
            # names
            self.controllers[controller_path_name] = controller

        # register the controller module names
        # with the mapper, creates the internal regular
        # expressions
        self.map.create_regs(controller_names)
Beispiel #8
0
def get_template_name(instance, method_name):
    '''
    Defines the template id to match against.

    :param instance: the instance to generate a template for
    :param method_name: the method to combine with the instance class

    template path = controller name + '/' + action name, except in the case
    of index. If the template is specified as part of the processed object
    return that, short circuiting any other template name processing

    This form may removed later, considered a candidate for deprecation
    '''
    template_id = getattr(instance, 'template_id', None)
    if template_id:
        return template_id
    # build a default template name if one isn't explicitly set
    try:
        template_root_name = camel_to_underscore(
            controller_pattern.search(instance.__class__.__name__).group(1))
    except AttributeError:
        template_root_name = ''
    return "/".join(filter(None, [template_root_name, method_name]))
Beispiel #9
0
def get_template_name(instance, method_name):
    '''
    Defines the template id to match against.

    :param instance: the instance to generate a template for
    :param method_name: the method to combine with the instance class

    template path = controller name + '/' + action name, except in the case
    of index. If the template is specified as part of the processed object
    return that, short circuiting any other template name processing

    This form may removed later, considered a candidate for deprecation
    '''
    template_id = getattr(instance, 'template_id', None)
    if template_id:
        return template_id
    # build a default template name if one isn't explicitly set
    try:
        template_root_name = camel_to_underscore(
                  controller_pattern.search(instance.__class__.__name__
                                            ).group(1))
    except AttributeError:
        template_root_name = ''
    return "/".join(filter(None, [template_root_name, method_name]))