def __init__(self, controller): defaults = dict( query_factory=default_query_factory, create_factory=default_create_factory, title=inflector.titleize(controller.proper_name), plural=inflector.underscore(controller.name), singular=inflector.underscore( inflector.singularize(controller.name)), ModelForm=model_form(controller.meta.Model), display_properties=sorted([ name for name, property in controller.meta.Model._properties.items() ]), redirect=controller.uri(action='list') if controller.uri_exists( action='list') else None, form_action=None, form_encoding='application/x-www-form-urlencoded', flash_messages=True, layouts={ None: 'layouts/default.html', 'admin': 'layouts/admin.html' }) for k, v in defaults.iteritems(): if not hasattr(self, k): setattr(self, k, v)
def __init__(self, *args, **kwargs): super(Controller, self).__init__(*args, **kwargs) self.name = inflector.underscore(self.__class__.__name__) self.proper_name = self.__class__.__name__ self.util = self.Util(weakref.proxy(self)) self.route = None
def canonical_parts_from_method(controller, method): """ Returns the canonical parts (prefix, controller, action, named arguments) from a controller's method """ method_name, method_args = get_true_name_and_argspec(method) method_class = controller method_class_name = inflector.underscore(method_class.__name__) prefix = None if hasattr(method_class, 'Meta'): prefixes = method_class.Meta.prefixes else: prefixes = method_class.prefixes for tprefix in prefixes: if method_name.startswith(tprefix + '_'): prefix = tprefix method_name = method_name.replace(prefix + '_', '') return { 'prefix': prefix, 'controller': method_class_name, 'action': method_name, 'args': method_args.args[1:] # exclude self }
def _build_routes(cls, router): """ Called in the main app router to get all of this controller's routes. Override to add custom/additional routes. """ # Route the rest methods router.add(routing.build_scaffold_routes_for_controller(cls)) for prefix in cls.Meta.prefixes: router.add( routing.build_scaffold_routes_for_controller(cls, prefix)) # Auto route the remaining methods for route in routing.build_routes_for_controller(cls): vars = re.findall(r'\[(\w+)\]', route.template) if vars: action = route.handler_method split = action.split('_') prefixed = split[0] in cls.Meta.prefixes controller_data = { 'prefix': split[0] if prefixed else None, 'controller': inflector.underscore(cls.__name__), 'action': '_'.join(split[1:]) if prefixed else action, } for i in vars: value = controller_data.get(i) if not value: continue route.template = route.template.replace( '[' + i + ']', value) router.add(route) events.fire('controller_build_routes', cls=cls, router=router)
def _build_routes(cls, router): """ Called in the main app router to get all of this controller's routes. Override to add custom/additional routes. """ # Route the rest methods router.add(routing.build_scaffold_routes_for_controller(cls)) for prefix in cls.Meta.prefixes: router.add(routing.build_scaffold_routes_for_controller(cls, prefix)) # Auto route the remaining methods for route in routing.build_routes_for_controller(cls): vars = re.findall(r'\[(\w+)\]', route.template) if vars: action = route.handler_method split = action.split('_') prefixed = split[0] in cls.Meta.prefixes controller_data = { 'prefix': split[0] if prefixed else None, 'controller': inflector.underscore(cls.__name__), 'action': '_'.join(split[1:]) if prefixed else action, } for i in vars: value = controller_data.get(i) if not value: continue route.template = route.template.replace('['+i+']', value) router.add(route) events.fire('controller_build_routes', cls=cls, router=router)
def add_properties(s, cls): if not s.Mixin in cls.__bases__: cls.__bases__ += (s.Mixin, ) if not hasattr(cls, 'Model'): import_form_base = '.'.join(cls.__module__.split('.')[:-2]) # Attempt to import the model automatically model_name = inflector.singularize(cls.__name__) try: module = __import__( '%s.models.%s' % (import_form_base, inflector.underscore(model_name)), fromlist=['*']) setattr(cls, 'Model', getattr(module, model_name)) except (ImportError, AttributeError): raise RuntimeError( "Scaffold coudn't automatically determine a model class for handler %s, please assign it a Model class variable." % cls.__name__) if cls.ModelForm == None: cls.ModelForm = model_form(cls.Model) # self.scaffold.method methods = inspect.getmembers(s.Handler, predicate=inspect.ismethod) for n, f in methods: cls.scaffold[n] = f.__func__
def __init__(self, controller): defaults = dict( title=inflector.titleize(controller.proper_name), plural=inflector.underscore(controller.name), singular=inflector.underscore(inflector.singularize(controller.name)), ModelForm=model_form(controller.meta.Model), display_properties=[name for name, property in controller.meta.Model._properties.items()], redirect=controller.uri(action="list") if controller.uri_exists(action="list") else None, form_action=None, form_encoding="application/x-www-form-urlencoded", flash_messages=True, ) for k, v in defaults.iteritems(): if not hasattr(self, k): setattr(self, k, v)
def _load_model(controller): import_form_base = '.'.join(controller.__module__.split('.')[:-2]) # Attempt to import the model automatically model_name = inflector.singularize(controller.__class__.__name__) try: module = __import__('%s.models.%s' % (import_form_base, inflector.underscore(model_name)), fromlist=['*']) setattr(controller.Meta, 'Model', getattr(module, model_name)) except (ImportError, AttributeError): raise RuntimeError("Scaffold coudn't automatically determine a model class for controller %s, please assign it a Meta.Model class variable." % controller.__class__.__name__)
def render_template_listener(name, context, env): admin_links = {} for x in admin_handlers: try: admin_links[x.__name__] = webapp2.uri_for( 'admin-' + inflector.underscore(x.__name__) + '-list') except: pass context.update({'autoadmin': {'links': admin_links}})
def __init__(self, controller): defaults = dict( query_factory=default_query_factory, create_factory=default_create_factory, title=inflector.titleize(controller.proper_name), plural=inflector.underscore(controller.name), singular=inflector.underscore(inflector.singularize(controller.name)), ModelForm=model_form(controller.meta.Model), display_properties=sorted([name for name, property in controller.meta.Model._properties.items()]), redirect=controller.uri(action="list") if controller.uri_exists(action="list") else None, form_action=None, form_encoding="application/x-www-form-urlencoded", flash_messages=True, layouts={None: "layouts/default.html", "admin": "layouts/admin.html"}, ) for k, v in defaults.iteritems(): if not hasattr(self, k): setattr(self, k, v)
def __init__(self, controller): defaults = dict( title=inflector.titleize(controller.proper_name), plural=inflector.underscore(controller.name), singular=inflector.underscore( inflector.singularize(controller.name)), ModelForm=model_form(controller.meta.Model), display_properties=[ name for name, property in controller.meta.Model._properties.items() ], redirect=controller.uri(action='list') if controller.uri_exists( action='list') else None, form_action=None, form_encoding='application/x-www-form-urlencoded', flash_messages=True) for k, v in defaults.iteritems(): if not hasattr(self, k): setattr(self, k, v)
def render_template_listener(name, context, env): admin_links = {} for x in admin_handlers: try: admin_links[x.__name__] = webapp2.uri_for('admin-' + inflector.underscore(x.__name__) + '-list') except: pass context.update({ 'autoadmin': { 'links': admin_links } })
def _build_components(self): self.events.before_build_components(controller=self) if hasattr(self.Meta, 'components'): component_classes = self.Meta.components self.components = Bunch() for cls in component_classes: if hasattr(cls, 'name'): name = cls.name else: name = inflector.underscore(cls.__name__) self.components[name] = cls(weakref.proxy(self)) else: self.components = Bunch() self.events.after_build_components(controller=self)
def add_properties(s, cls): if not s.Mixin in cls.__bases__: cls.__bases__ += (s.Mixin,) if not hasattr(cls, 'Model'): import_form_base = '.'.join(cls.__module__.split('.')[:-2]) # Attempt to import the model automatically model_name = inflector.singularize(cls.__name__) try: module = __import__('%s.models.%s' % (import_form_base, inflector.underscore(model_name)), fromlist=['*']) setattr(cls, 'Model', getattr(module, model_name)) except (ImportError, AttributeError): raise RuntimeError("Scaffold coudn't automatically determine a model class for handler %s, please assign it a Model class variable." % cls.__name__) if cls.ModelForm == None: cls.ModelForm = model_form(cls.Model) # self.scaffold.method methods = inspect.getmembers(s.Handler, predicate=inspect.ismethod) for n, f in methods: cls.scaffold[n] = f.__func__
def canonical_parts_from_method(method): """ Returns the canonical parts (prefix, handler, action, named arguments) from a handler's method """ method_name = method.__name__ method_class = method.im_class method_class_name = inflector.underscore(method_class.__name__) prefix = None for tprefix in method_class.prefixes: if method_name.startswith(tprefix + '_'): prefix = tprefix method_name = method_name.replace(prefix + '_', '') args = inspect.getargspec(method).args[1:] return { 'prefix': prefix, 'handler': method_class_name, 'action': method_name, 'args': args }
def build_scaffold_routes_for_controller(controllercls, prefix_name=None): """ Automatically sets up a restful routing interface for a controller that has any of the rest methods (list, view, add, edit, delete) either without or with a prefix. Note that these aren't true rest routes, some more wizardry has to be done for that. The routes generated are: controller:list : /controller controller:view : /controller/:id controller:add : /controller/add controller:edit : /controller/:id/edit controller:delete : /controller/:id/delete prefixes just add to the beginning of the name and uri, for example: admin:controller:edit: /admin/controller/:id/edit """ if (hasattr(controllercls, 'name')): name = controllercls.name name = inflector.underscore(controllercls.__name__) prefix_string = '' if prefix_name: prefix_string = prefix_name + '_' top = [] path = [] id = [] # GET /controller -> controller::list if hasattr(controllercls, prefix_string + 'list'): top.append( Route('/' + name, controllercls, 'list', handler_method=prefix_string + 'list', methods=['HEAD', 'GET'])) # GET /controller/:urlsafe -> controller::view if hasattr(controllercls, prefix_string + 'view'): path.append( Route('/:<key>', controllercls, 'view', handler_method=prefix_string + 'view', methods=['HEAD', 'GET'])) # GET/POST /controller/add -> controller::add # POST /controller -> controller::add if hasattr(controllercls, prefix_string + 'add'): path.append( Route('/add', controllercls, 'add', handler_method=prefix_string + 'add', methods=['GET', 'POST'])) top.append( Route('/' + name, controllercls, 'add:rest', handler_method=prefix_string + 'add', methods=['POST'])) # GET/POST /controller/:urlsafe/edit -> controller::edit # PUT /controller/:urlsafe -> controller::edit if hasattr(controllercls, prefix_string + 'edit'): id.append( Route('/edit', controllercls, 'edit', handler_method=prefix_string + 'edit', methods=['GET', 'POST'])) path.append( Route('/:<key>', controllercls, 'edit:rest', handler_method=prefix_string + 'edit', methods=['PUT', 'POST'])) # GET /controller/:urlsafe/delete -> controller::delete # DELETE /controller/:urlsafe -> controller::d if hasattr(controllercls, prefix_string + 'delete'): id.append( Route('/delete', controllercls, 'delete', handler_method=prefix_string + 'delete')) path.append( Route('/:<key>', controllercls, 'delete:rest', handler_method=prefix_string + 'delete', methods=["DELETE"])) top_route = routes.NamePrefixRoute( name + ':', top + [ routes.PathPrefixRoute( '/' + name, path + [routes.PathPrefixRoute('/:<key>', id)]) ]) if prefix_name: prefix_route = routes.NamePrefixRoute( prefix_name + ':', [routes.PathPrefixRoute('/' + prefix_name, [top_route])]) return prefix_route return top_route
def build_scaffold_routes_for_handler(handlercls, prefix_name=None): """ Automatically sets up a restful routing interface for a handler that has any of the rest methods (list, view, add, edit, delete) either without or with a prefix. Note that these aren't true rest routes, some more wizardry has to be done for that. The routes generated are: handler-list : /handler handler-view : /handler/:id handler-add : /handler/add handler-edit : /handler/:id/edit handler-delete : /handler/:id/delete prefixes just add to the beginning of the name and uri, for example: admin-handler-edit: /admin/handler/:id/edit """ if(hasattr(handlercls, 'name')): name = handlercls.name name = inflector.underscore(handlercls.__name__) prefix_string = '' if not prefix_name == None: prefix_string = prefix_name + '_' top = [] path = [] id = [] # GET /handler -> Handler::list if hasattr(handlercls, prefix_string + 'list'): top.append(Route('/' + name, handlercls, 'list', handler_method=prefix_string + 'list', methods=['HEAD', 'GET'])) # GET /handler/:urlsafe -> Handler::view if hasattr(handlercls, prefix_string + 'view'): path.append(Route('/<id:%s>' % id_regex, handlercls, 'view', handler_method=prefix_string + 'view', methods=['HEAD', 'GET'])) # GET/POST /handler/add -> Handler::add # POST /handler -> Handler::add if hasattr(handlercls, prefix_string + 'add'): path.append(Route('/add', handlercls, 'add', handler_method=prefix_string + 'add', methods=['GET', 'POST'])) top.append(Route('/' + name, handlercls, 'add-rest', handler_method=prefix_string + 'add', methods=['POST'])) # GET/POST /handler/:urlsafe/edit -> Handler::edit # PUT /handler/:urlsafe -> Handler::edit if hasattr(handlercls, prefix_string + 'edit'): id.append(Route('/edit', handlercls, 'edit', handler_method=prefix_string + 'edit', methods=['GET', 'POST'])) path.append(Route('/<id:%s>' % id_regex, handlercls, 'edit-rest', handler_method=prefix_string + 'edit', methods=['PUT', 'POST'])) # GET /handler/:urlsafe/delete -> Handler::delete # DELETE /handler/:urlsafe -> Handler::d if hasattr(handlercls, prefix_string + 'delete'): id.append(Route('/delete', handlercls, 'delete', handler_method=prefix_string + 'delete')) path.append(Route('/<id:%s>' % id_regex, handlercls, 'delete-rest', handler_method=prefix_string + 'delete', methods=["DELETE"])) top_route = routes.NamePrefixRoute(name + '-', top + [ routes.PathPrefixRoute('/' + name, path + [ routes.PathPrefixRoute('/<id:%s>' % id_regex, id) ]) ]) if not prefix_name == None: prefix_route = routes.NamePrefixRoute(prefix_name + '-', [ routes.PathPrefixRoute('/' + prefix_name, [top_route]) ]) return prefix_route return top_route