def get(self): ## t is a shortcut to tipfy config t = config.config['tipfy'] context = {} ## list of middleware context['middleware'] = t['middleware'] ## Installed Apps apps = [] urls = [] handlers = [] for app_module in sorted(t['apps_installed']): try: # Load the urls module from the app and extend our rules. app_rules = import_string('%s.urls' % app_module) rules = app_rules.get_rules(app_rules) rlist = [] for r in rules: rlist.append({'handler': r.handler, 'endpoint': r.endpoint, 'url': r.rule}) urls.append(r.rule) handlers.append(r.handler) apps.append({'app': app_module, 'rules': rlist}); except ImportError: pass context['apps'] = apps context['urls'] = sorted(urls) context['handlers'] = sorted(handlers) ## TODO move the template to unders here, and append path return render_response('tipfy_console.html', **context)
def auth_user_model(self): """Returns the configured user model. :returns: A :class:`tipfy.ext.auth.model.User` class. """ return import_string(self.app.get_config(__name__, "user_model"))
def get_rules(): """Returns a list of URL rules for the application. The list can be defined entirely here or in separate ``urls.py`` files. Here we show an example of joining all rules from the ``apps_installed`` listed in config. """ rules = [ tipfy.Rule('/', endpoint='home', handler='home.HomeHandler'), tipfy.Rule('/submit', endpoint='submit', handler='submit.SubmitHandler'), tipfy.Rule('/review', endpoint='review-start', handler='review.ReviewStartHandler'), tipfy.Rule('/review/<int:id>', endpoint='review-quote', handler='review.ReviewQuoteHandler'), tipfy.Rule('/review/remind', endpoint='review-remind', handler='review.ReviewRemindHandler'), tipfy.Rule('/quote/<int:id>', endpoint='quote-view', handler='quote.QuoteViewHandler'), tipfy.Rule('/random', endpoint='random-quote', handler='random_quote.RandomQuoteHandler'), tipfy.Rule('/atom', endpoint='atom-view', handler='atom.AtomViewHandler'), ] for app_module in tipfy.get_config('tipfy', 'apps_installed'): try: # Load the urls module from the app and extend our rules. app_rules = tipfy.import_string('%s.urls' % app_module) rules.extend(app_rules.get_rules()) except ImportError: pass return rules
def load_middleware(self, classes): """Returns a dictionary of middleware instance methods for a list of classes. :param classes: A list of middleware classes. :return: A dictionary with middleware instance methods. """ res = {} for cls in classes: if isinstance(cls, basestring): id = cls else: id = cls.__module__ + '.' + cls.__name__ if id not in self.methods: if isinstance(cls, basestring): cls = import_string(cls) obj = cls() self.instances[id] = obj self.methods[id] = [getattr(obj, n, None) for n in self.names] for name, method in zip(self.names, self.methods[id]): if method: res.setdefault(name, []).append(method) for name in self.reverse_names: if name in res: res[name].reverse() return res
def auth_user_model(self): """Returns the configured user model. :returns: A :class:`tipfy.ext.auth.model.User` class. """ return import_string(self.app.get_config(__name__, 'user_model'))
def user_model(self): """Returns the configured user model. :return: A :class:`tipfy.ext.auth.model.User` class. """ return import_string(get_config(__name__, 'user_model'))
def get_rules(): """Returns a list of URL rules for the application. The list can be defined entirely here or in separate ``urls.py`` files. Here we show an example of joining all rules from the ``apps_installed`` listed in config. """ entry_points = get_config('tipfy', 'apps_entry_points') if get_config('moe', 'use_subdomain', False): kwargs = {'subdomain': '<area_name>'} else: kwargs = {'defaults': {'area_name': 'www'}} rules = [ # This is a dummy rule pointing to wiki start page. Replace it by # one pointing to a homepage handler. Rule('/', endpoint='home/index', handler='moe.wiki.handlers.WikiViewHandler', **kwargs), ] for app_module in get_config('tipfy', 'apps_installed'): try: # Get the rules from each app installed and extend our rules. app_rules = import_string('%s.urls.get_rules' % app_module)() entry_point = entry_points.get(app_module) if entry_point: # Submount using the entry point. rules.append(Submount(entry_point, app_rules)) else: # Just append the rules. rules.extend(app_rules) except ImportError: pass return rules
def get_auth_system(): """Returns the configured authentication system. :return: An instance of :class:`tipfy.ext.auth.BaseAuth`. """ global _auth_system if _auth_system is None: _auth_system = import_string(get_config(__name__, 'auth_system'))() return _auth_system
def get_url_map(self): """Returns ``werkzeug.routing.Map`` with the URL rules defined for the application. Rules are cached in production; the cache is automatically renewed on each deployment. :return: A ``werkzeug.routing.Map`` instance. """ rules = import_string('urls.get_rules')() kwargs = self.config.get('tipfy').get('url_map_kwargs') return Map(rules, **kwargs)
def get_rules(app): rules = [] for app_module in app.get_config('tipfy', 'apps_installed'): try: # Load the urls module from the app and extend our rules. app_rules = import_string('%s.urls' % app_module) rules.extend(app_rules.get_rules(app)) except ImportError: pass return rules
def get_rules(): rules = [ Rule('/', handler='apps.handlers.IndexHandler', endpoint='index'), ] for app_module in get_config('tipfy', 'apps_installed'): try: # Load the urls module from the app and extend our rules. app_rules = import_string('%s.urls' % app_module) rules.extend(app_rules.get_rules()) except ImportError: pass return rules
def get_rules(app): # http://www.tipfy.org/docs/api/tipfy.ext.taskqueue.html rules = [Rule("/_ah/queue/deferred", endpoint="tasks/deferred", handler="tipfy.ext.taskqueue:DeferredHandler")] for app_module in app.get_config("tipfy", "apps_installed"): try: # Load the urls module from the app and extend our rules. app_rules = import_string("%s.urls" % app_module) rules.extend(app_rules.get_rules(app)) except ImportError: pass return rules
def __call__(self, environ, start_response): """Called by WSGI when a request comes in.""" try: # Set local variables for a single request. local.app = self local.request = request = self.request_class(environ) # Kept here for backwards compatibility. Soon to be removed. local.response = self.response_class() self.url_adapter = self.rule = self.rule_args = None # Check requested method. method = request.method.lower() if method not in ALLOWED_METHODS: raise MethodNotAllowed() # Bind url map to the current request location. self.url_adapter = self.url_map.bind_to_environ(environ, server_name=self.config.get('tipfy', 'server_name', None), subdomain=self.config.get('tipfy', 'subdomain', None)) # Match the path against registered rules. self.rule, self.rule_args = self.url_adapter.match(request.path, return_rule=True) # Import handler set in matched rule. name = self.rule.handler if name not in self.handlers: self.handlers[name] = import_string(name) # Execute pre_dispatch_handler middleware. for hook in self.middleware.get('pre_dispatch_handler', []): response = hook() if response: break else: # Instantiate handler and dispatch request method. handler = self.handlers[name]() response = handler.dispatch(method, **self.rule_args) # Execute post_dispatch_handler middleware. for hook in self.middleware.get('post_dispatch_handler', []): response = hook(response) except RequestRedirect, e: # Execute redirects raised by the routing system or the application. response = e
def normalize_callable(spec): """Many `Tipfy`_ configurations expect a callable or optionally a string with a callable definition to be lazily imported. This function normalizes those definitions, importing the callable if necessary. :param spec: A callable or a string with a callable definition to be imported. :return: A callable. """ if isinstance(spec, basestring): spec = import_string(spec) if not callable(spec): raise ValueError('%s is not a callable.' % str(spec)) return spec
def get_rules(): """Returns a list of URL rules for the application. The list can be defined entirely here or in separate ``urls.py`` files. Here we show an example of joining all rules from the ``apps_installed`` listed in config. """ rules = [] for app_module in get_config('tipfy', 'apps_installed'): try: # Load the urls module from the app and extend our rules. app_rules = import_string('%s.urls' % app_module) rules.extend(app_rules.get_rules()) except ImportError: pass return rules
def get_config(module, key=None, default=_DEFAULT_CONFIG): """Returns a configuration value for a module. If it is not already set, loads a ``default_config`` variable from the given module, update the app config with those default values and return the value for the given key. If the key is still not available, returns the provided default value or raises an exception if no default was provided. Every `Tipfy`_ module that allows some kind of configuration sets a ``default_config`` global variable that is loaded by this function, cached and used in case the requested configuration was not defined by the user. :param module: The configured module. :param key: The config key. :return: A configuration value. """ value = local.app.config.get(module, key, _DEFAULT_CONFIG) if value not in (_DEFAULT_CONFIG, REQUIRED_CONFIG): return value if default is _DEFAULT_CONFIG: # If no default was provided, the config is required. default = REQUIRED_CONFIG if value is _DEFAULT_CONFIG: if module not in local.app.config.modules: # Update app config. If import fails or the default_config attribute # doesn't exist, an exception will be raised. local.app.config.setdefault(module, import_string( module + ':default_config')) local.app.config.modules.append(module) value = local.app.config.get(module, key, default) else: value = default if value is REQUIRED_CONFIG: raise KeyError('Module %s requires the config key "%s" to be set.' % (module, key)) return value
def get_rules(app): """Returns a list of URL rules for the application. The list can be defined entirely here or in separate ``urls.py`` files. :param app: The WSGI application instance. :return: A list of class:`tipfy.Rule` instances. """ rules = [] for app_module in app.get_config('tipfy', 'apps_installed'): try: # Load the urls module from the app and extend our rules. app_rules = import_string('%s.urls' % app_module) rules.extend(app_rules.get_rules(app)) except ImportError: pass return rules
def get_rules(app): """Returns a list of URL rules for the application. The list can be defined entirely here or in separate ``urls.py`` files. :param app: The WSGI application instance. :return: A list of class:`tipfy.Rule` instances. """ # Here we show an example of joining all rules from the # ``apps_installed`` definition set in config.py. rules = [] for app_module in app.get_config('tipfy', 'apps_installed'): try: # Load the urls module from the app and extend our rules. app_rules = import_string('%s.urls' % app_module) rules.extend(app_rules.get_rules(app)) except ImportError, e: import logging logging.error('Importerror: %s' % e) pass
def get_jinja2_instance(): """Returns an instance of :class:`Jinja2`, registering it in the WSGI app if not yet registered. :return: An instance of :class:`Jinja2`. """ app = Tipfy.app registry = app.registry if 'jinja2_instance' not in registry: factory_spec = app.get_config(__name__, 'engine_factory') if factory_spec: if isinstance(factory_spec, basestring): factory = import_string(factory_spec) else: factory = factory_spec else: factory = create_jinja2_instance registry['jinja2_instance'] = factory() return registry['jinja2_instance']
def get_jinja2_instance(): """Returns an instance of :class:`Jinja2`, registering it in the WSGI app if not yet registered. :return: An instance of :class:`Jinja2`. """ app = Tipfy.app registry = app.registry if "jinja2_instance" not in registry: factory_spec = app.get_config(__name__, "engine_factory") if factory_spec: if isinstance(factory_spec, basestring): factory = import_string(factory_spec) else: factory = factory_spec else: factory = create_jinja2_instance registry["jinja2_instance"] = factory() return registry["jinja2_instance"]