Exemplo n.º 1
0
def import_module_from_directory(version: str,
                                 importdir: Path,
                                 force_reload=False):
    module_files = ModuleFiles.load_from_dirpath(importdir)  # raise ValueError
    spec = ModuleSpec.load_from_path(module_files.spec)  # raise ValueError
    validate_python_functions(module_files.code)  # raise ValueError

    if not force_reload:
        # Don't allow importing the same version twice
        try:
            ModuleVersion.objects.get(id_name=spec.id_name,
                                      source_version_hash=version)
            raise ValueError(f'Version {version} of module {spec.id_name}'
                             ' has already been imported')
        except ModuleVersion.DoesNotExist:
            # this is what we want
            pass

    if module_files.javascript:
        js_module = module_files.javascript.read_text(encoding='utf-8')
    else:
        js_module = ''

    # Copy whole directory to S3
    prefix = '%s/%s/' % (spec.id_name, version)

    try:
        # If files already exist, delete them so we can overwrite them.
        #
        # This can race: a worker may be loading the code to execute it. But
        # races are unlikely to affect anybody because:
        #
        # * If force_reload=True we're in dev or test, where we control
        #   everything.
        # * Otherwise, we've already checked there's no ModuleVersion, so
        #   probably nothing is trying and load what we're deleting here.
        minio.remove_recursive(minio.ExternalModulesBucket, prefix)
    except FileNotFoundError:
        pass  # common case: we aren't overwriting code

    minio.fput_directory_contents(minio.ExternalModulesBucket, prefix,
                                  Path(importdir))

    # If that succeeds, initialise module in our database
    module_version = ModuleVersion.create_or_replace_from_spec(
        spec, source_version_hash=version, js_module=js_module)

    logger.info('Imported module %s' % spec.id_name)

    return module_version
 def test_validate_python_missing_render(self):
     """test missing/unloadable render function"""
     test_dir = Path(self._test_module_path('missing_render_module'))
     with self.assertRaisesRegex(ValueError, 'missing_render_module.py'):
         validate_python_functions(test_dir / 'missing_render_module.py')
 def test_validate_valid_python_functions(self):
     test_dir = Path(self._test_module_path('importable'))
     validate_python_functions(test_dir / 'importable.py')
Exemplo n.º 4
0
 def _validate(self, data):
     dirpath = MockDir({"module.py": data.encode("utf-8")})
     path = dirpath / "module.py"
     validate_python_functions(path)
Exemplo n.º 5
0
 def _validate(self, data):
     dirpath = MockDir({
         'module.py': data.encode('utf-8'),
     })
     path = dirpath / 'module.py'
     validate_python_functions(path)