Skip to content
Snippets Groups Projects
Select Git revision
  • c7edebc8572cda1005ad96106c2ba41aaa8e5b96
  • master default protected
  • 29-alias-for-apps
  • 30-restructure-ci-version-checking
  • 16-update-documentation
  • 11-write-example-app
  • 1.0.5
  • 1.0.4
  • 1.0.3
  • 1.0.2
  • 1.0.1
11 results

sams_hub.py

Blame
  • user avatar
    Sebastian Lobinger authored
    c7edebc8
    History
    Code owners
    Assign users and groups as approvers for specific file changes. Learn more.
    sams_hub.py 3.06 KiB
    from flask import Flask, request, session
    from .exceptions import (
      ManifestDefaultLanguageMissing
      , DefaultLanguageDictMissing
      , AppNotExist
      , FunctionNotExists
    )
    from typing import Dict, List
    from importlib import import_module
    #from .exceptions import HubDirNotExist, FunctionNotExists
    #from importlib import import_module
    from .sams_app import SAMSApp
    from .exceptions import FunctionNotExists
    from optparse import Values
    import sys
    
    def eprint(*args, **kwargs):
      print(*args, file=sys.stderr, **kwargs)
    
    class SAMSHub:
    
      def __init__(self, name: str, config: dict):
        self._config = config;
        if not self._config.get('default_language'):
          raise TypeError(
            'Parameter config musst contain a value for "default_language"')
        self._apps = {}
        self._flaskApp = Flask(name)
        self._flaskApp.context_processor(self._context_processor)
        self._flaskApp.secret_key = 'my awesome SAMSHub secret_key'
      
      def addApp(self, app: SAMSApp = None):
        if not isinstance(app, SAMSApp):
          raise TypeError('Argument app has to be a SAMSApp.')
        self._apps[app.name] = app
        if app.name is self._config.get('main_app'):
          self._flaskApp.register_blueprint(app.blueprint)
        else:
          self._flaskApp.register_blueprint(
            app.blueprint, url_prefix = '/' + app.name)
      
      @property
      def appKeys(self):
        return self._apps.keys()
      
      @property
      def flaskApp(self):
        return self._flaskApp
      
      def app(self, name):
        try:
          return self._apps[name]
        except:
          raise AppNotExist
      
      def __add_urls(self, module):
        for view in self.__manifests[module].get('views', []):
          pathElements = [module]
          if view['url']:
            pathElements.append(view['url'])
          rule = '/' + '/'.join(pathElements)
          endpoint = '_'.join(view['function'].split('.'))
          view_func = self.__get_attr(self.__modules[module], view['function'])
          self.__blueprints[module].add_url_rule(rule = rule, endpoint = endpoint
            , view_func = view_func)
      
      def _context_processor(self):
        return {
          'app_lang': self.app(request.blueprint).lang(
            session.get('language', self._config['default_language'])
          ),
          'menu': self.menu(
            session.get('language', self._config['default_language']))
        }
      
      def menu(self, langCode):
        menu = []
        for app in self._apps.values():
          if self._config.get('main_app') is app.name:
            menu.extend(app.menu(langCode = langCode))
          else:
            menu.extend(app.menu(langCode = langCode, urlPrefix = app.name))
        return menu
      
      @staticmethod
      def _get_module_rule(module, path):
        pathElements = [module]
        if path:
          pathElements.append(path)
        return '/' + '/'.join(pathElements)
    
      @staticmethod
      def _get_attr(object, attrString):
        attr = None
        try:
          return getattr(object, attrString)
        except AttributeError:
          pass
        attrList = attrString.split('.')
        if len(attrList) <= 1:
          raise FunctionNotExists('The function ' + attrString + ' does not exist')
        return(
          SAMSHub._get_attr(getattr(object, attrList[0]), '.'.join(attrList[1:]))
        )