def _resolve_handler_by_name(self, name): try: [controller, action] = name.split('#') except ValueError as e: web_logger.warn("invalid action signature: %s. skip" % name) raise e return self.resolve_action(controller, action)
async def setup_middlewares(app): app.middlewares.append(normalize_path_middleware(append_slash=True)) app.middlewares.append(is_ajax) app.middlewares.append(csrf_token) csrf_setup(app) PRE_DISPATCHERS.append(csrf_pre_dispatch) for middleware in settings.MIDDLEWARES: try: mod = importlib.import_module(middleware) try: mw = getattr(mod, 'middleware') app.middlewares.append(mw) except AttributeError: pass try: setup = getattr(mod, 'setup') await awaitable(setup(app)) except AttributeError: pass try: PRE_DISPATCHERS.append(getattr(mod, 'pre_dispatch')) except AttributeError: pass except ImportError as e: web_logger.warn('Failed to register middleware %s' % middleware)
async def mail_traceback(request): if request.app.get('env', 'development') == 'development': traceback.print_exc() else: trace = traceback.format_exc() try: # Create a text/plain message if request.content_type == 'multipart/form-data': post = '<multipart>' else: post = await request.post() await send_mail( request.app, sender='%s service <noreply@%s>' % (settings.BRAND, request.url.host), recipients=tuple(e for e in getattr(settings, 'ADMINS', [])), subject='%s error report at %s -> %s' % (settings.BRAND, request.method, request.url), body="%s\n\nmatch:\n%s\n\nPOST:\n%s\n\nGET:\n%s\n\nHEADERS:\n%s" % (trace, request.match_info, post, request.query, request.headers)) except aiosmtplib.errors.SMTPConnectError as e: web_logger.warn("Failed to connect to SMTP server\n%s" % e.message) print(trace) except Exception as e: traceback.print_exc() print(trace)
def __init__(self, settings_module): # update this dict from global settings (but only for ALL_CAPS settings) for setting in dir(global_settings): if setting.isupper(): setattr(self, setting, getattr(global_settings, setting)) # store the settings module in case someone later cares self.SETTINGS_MODULE = settings_module if self.SETTINGS_MODULE: try: mod = importlib.import_module(self.SETTINGS_MODULE) tuple_settings = ("APPS", ) self._explicit_settings = set() for setting in dir(mod): if setting.isupper(): setting_value = getattr(mod, setting) if (setting in tuple_settings and not isinstance(setting_value, (list, tuple))): raise ImproperlyConfigured( "The %s setting must be a list or a tuple. " % setting) setattr(self, setting, setting_value) self._explicit_settings.add(setting) except ImportError: web_logger.warn("Failed to import settings module") else: web_logger.warn("No settings module specified")
def __init__(self, file) -> None: super().__init__() self.config = {} try: with open(os.path.join(settings.BASE_DIR, file), 'r') as stream: self.config = yaml.load(stream) except FileNotFoundError: web_logger.warn("config file %s not found at path %s" % (file, settings.BASE_DIR))
def _add_route(self, method, url, handler=None, name=None, **kwargs): gen_name = '' try: [url, handler, gen_name] = self._resolve_handler(url, handler) self.app.router.add_route(method, self._get_baseurl(url), handler, name=self._get_namespace(name if name else gen_name), **kwargs) except Exception as e: web_logger.warn("invalid route: %s [%s]. skip\nreason: %s" % (url, name if name else gen_name, e)) self._currentName = self._get_namespace(name if name else gen_name) self._currentPrefix = url return self
def use(self, url, app_name, name=''): oldName = self._currentName oldPrefix = self._currentPrefix oldPackage = self._currentPackage self._currentName = name if name else app_name self._currentPrefix = url self._currentPackage = app_name with self as subrouter: try: mod = importlib.import_module("%s.config.routes" % app_name) setup = getattr(mod, 'setup') setup(subrouter) except AttributeError: web_logger.warn("no setup method in %s router" % app_name) except ImportError as e: web_logger.warn("no routes for app %s" % app_name) self._currentName = oldName self._currentPrefix = oldPrefix self._currentPackage = oldPackage
async def setup(app): try: storage = None if hasattr(settings, 'SESSION_STORAGE'): try: mod = importlib.import_module(settings.SESSION_STORAGE) storage = await getattr(mod, 'setup')(app) except Exception as e: web_logger.warn( "failed to setup {} storage. Using simple cookie storage".format(settings.SESSION_STORAGE)) if not storage: app['redis_pool'] = await create_pool(('localhost', 6379)) storage = RedisStorage(app['redis_pool']) setup_session(app, storage) except: from cryptography import fernet import base64 web_logger.warn("failed to connect to Redis server. Using simple cookie storage") fernet_key = fernet.Fernet.generate_key() secret_key = base64.urlsafe_b64decode(fernet_key) setup_session(app, EncryptedCookieStorage(secret_key))
from aioweb_auth.exceptions import UserNotFoundError, PasswordDoesNotMatchError from aioweb.conf import settings def __import_class(path): chunks = path.split('.') mod = importlib.import_module('.'.join(chunks[:-1])) return getattr(mod, chunks[-1]) AUTHORIZATION_POLICY = __import_class(settings.AUTH_AUTHORIZATION_POLICY) if hasattr(settings, 'AUTH_IDENTITY_POLICY'): IDENTITY_POLICY = __import_class(settings.AUTH_IDENTITY_POLICY) else: web_logger.warn("No AUTH_IDENTITY_POLICY set. using SessionIdentityPolicy by default") IDENTITY_POLICY = SessionIdentityPolicy REQUEST_KEY = 'AIOWEB_AUTH' def __check_request_key(request): if not REQUEST_KEY in request or type(request[REQUEST_KEY]) != dict: request[REQUEST_KEY] = {} def remember_user(request, identity): __check_request_key(request) request[REQUEST_KEY]['remember'] = identity
def resolve_action(self, controller, action_name): if type(controller) == str: try: ctrl_class = self._import_controller(controller) except Exception as e: web_logger.warn("Failed to import controller: %s. skip\n reason : %s" % (controller, e)) raise e else: ctrl_class = controller async def action_handler(request): ctrl_instance = ctrl_class(request, self) if os.environ.get('AIOWEB_ENV', '') == 'test': self.app.__class__.last_controller = ctrl_instance try: action = getattr(ctrl_instance, action_name) except AttributeError as e: raise web.HTTPNotFound(reason='Action %s#%s not found' % (controller, action_name)) accept = request.headers.get('accept', ctrl_instance.__class__.DEFAULT_MIME) accept_entries = accept.split(',') allowed_content_type = getattr(action, 'content_type', { CtlDecoratorDescriptor.EXCEPT: tuple(), CtlDecoratorDescriptor.ONLY: tuple() }) cleaned_entries = [] for entry in accept_entries: cleaned_entry = entry.split(';')[0].strip() mime, subtype = cleaned_entry.split('/') if mime == '*': cleaned_entry = ctrl_instance.__class__.DEFAULT_MIME if cleaned_entry not in allowed_content_type[CtlDecoratorDescriptor.EXCEPT] and \ (cleaned_entry in allowed_content_type[CtlDecoratorDescriptor.ONLY] or len(allowed_content_type[CtlDecoratorDescriptor.ONLY]) == 0): cleaned_entries.append(cleaned_entry) serializer = make_serializer(ctrl_instance, cleaned_entries) setattr(request, 'serializer', serializer) serializer.raiseIfNotAllowed() # TODO: something better for preDispatcher in PRE_DISPATCHERS: if callable(preDispatcher): await awaitable(preDispatcher(request, ctrl_instance, action_name)) for preDispatcher in self.preDispatchers: if callable(preDispatcher): await awaitable(preDispatcher(request, ctrl_instance, action_name)) return await ctrl_instance._dispatch(action, action_name) url = "/%s/%s" % (controller, '' if action_name == 'index' else '%s/' % action_name) return [url, action_handler, "%s.%s" % (extract_name_from_class(ctrl_class.__name__, 'Controller'), action_name)]