def test_staticfiles_find_matches_relative_and_absolute_paths(self): abs_path = os.path.join(os.path.dirname(__file__), 'test_app', 'static', 'test.js') self.assertEqual(abs_path, find('test.js')) self.assertIsNone(find('test_app/static/test.js')) self.assertTrue(os.path.exists(abs_path)) self.assertEqual(find(abs_path), abs_path)
def bundle_component(path, client_path, translate=None, path_to_react=None, devtool=None, client=False): if not os.path.isabs(path): abs_path = staticfiles.find(path) if not abs_path: raise ComponentSourceFileNotFound(path) path = abs_path if not os.path.exists(path): raise ComponentSourceFileNotFound(path) if not os.path.isabs(client_path): abs_client_path = staticfiles.find(client_path) if not abs_client_path: raise ComponentSourceFileNotFound(client_path) client_path = abs_client_path if not os.path.exists(client_path): raise ComponentSourceFileNotFound(client_path) config = generate_config_for_component(path, client_path, translate=translate, path_to_react=path_to_react, devtool=devtool) config_file = generate_config_file(config) var = generate_var_from_path(client_path) path_to_config_file = get_path_to_config_file(config_file, prefix=var + '.') return webpack(path_to_config_file)
def test_bundle_urls_can_be_resolved_via_the_static_file_finder_used_by_the_dev_server( self): bundle = webpack('django_test_app/webpack.config.js') assets = bundle.get_assets() self.assertTrue(len(assets), 1) relative_url = assets[0]['url'].split('/static/')[-1] self.assertEqual(staticfiles.find(relative_url), assets[0]['path'])
def test_bundle_urls_can_be_resolved_via_the_static_file_finder_used_by_the_dev_server( self): bundle = webpack('django_test_app/webpack.config.js') urls = bundle.get_urls() self.assertTrue(len(urls['main']['js']), 1) relative_url = urls['main']['js'][0].split('/static/')[-1] self.assertEqual(staticfiles.find(relative_url), bundle.get_assets()[0])
def webpack(config_file, watch_config=None, watch_source=None): if not settings.BUNDLE_ROOT: raise ImproperlyConfigured('webpack.conf.settings.BUNDLE_ROOT has not been defined.') if not settings.BUNDLE_URL: raise ImproperlyConfigured('webpack.conf.settings.BUNDLE_URL has not been defined.') if not os.path.isabs(config_file): abs_path = staticfiles.find(config_file) if not abs_path: raise ConfigFileNotFound(config_file) config_file = abs_path if not os.path.exists(config_file): raise ConfigFileNotFound(config_file) if watch_config is None: watch_config = settings.WATCH_CONFIG_FILES if watch_source is None: watch_source = settings.WATCH_SOURCE_FILES try: output = js_host_function.call( config=config_file, watch=watch_source, watchDelay=settings.WATCH_DELAY, watchConfig=watch_config, cache=False, fullStats=settings.OUTPUT_FULL_STATS, bundleDir=settings.get_path_to_bundle_dir(), ) except FunctionError as e: raise six.reraise(BundlingError, BundlingError(*e.args), sys.exc_info()[2]) stats = json.loads(output) if stats['errors']: raise BundlingError( '{}\n\n{}'.format(config_file, '\n\n'.join(stats['errors'])) ) if stats['warnings']: warnings.warn(stats['warnings'], WebpackWarning) # Generate contextual information about the generated assets stats['urlsToAssets'] = {} path_to_bundle_dir = settings.get_path_to_bundle_dir() for asset, config_file in six.iteritems(stats['pathsToAssets']): if path_to_bundle_dir in config_file: rel_path = config_file[len(path_to_bundle_dir):] rel_url = pathname2url(rel_path) if rel_url.startswith('/'): rel_url = rel_url[1:] url = '{}{}/{}/{}'.format(settings.BUNDLE_URL, settings.OUTPUT_DIR, settings.BUNDLE_DIR, rel_url) stats['urlsToAssets'][asset] = url return WebpackBundle(stats)
def render_component(path, props=None, to_static_markup=False, renderer=render_server, request_headers=None, timeout=None): if not os.path.isabs(path): abs_path = staticfiles.find(path) if not abs_path: raise ComponentSourceFileNotFound(path) path = abs_path if not os.path.exists(path): raise ComponentSourceFileNotFound(path) return renderer.render(path, props, to_static_markup, request_headers, timeout=timeout)
def bundle_component(path, translate=None, devtool=None): if not os.path.isabs(path): abs_path = staticfiles.find(path) if not abs_path: raise ComponentSourceFileNotFound(path) path = abs_path if not os.path.exists(path): raise ComponentSourceFileNotFound(path) config = generate_config_for_component(path, translate=translate, devtool=devtool) config_file = generate_config_file(config) var = generate_var_from_path(path) path_to_config_file = get_path_to_config_file(config_file, prefix=var + '.') return webpack(path_to_config_file)
def render_component( # Rendering options path, props=None, to_static_markup=None, # Bundling options bundle=None, translate=None, # Prop handling json_encoder=None): if not os.path.isabs(path): abs_path = staticfiles.find(path) if not abs_path: raise ComponentSourceFileNotFound(path) path = abs_path if not os.path.exists(path): raise ComponentSourceFileNotFound(path) bundled_component = None if bundle or translate: bundled_component = bundle_component(path, translate=translate) path = bundled_component.get_paths()[0] if json_encoder is None: json_encoder = JSONEncoder if props is not None: serialized_props = json.dumps(props, cls=json_encoder) else: serialized_props = None try: markup = js_host_function.call(path=path, serializedProps=serialized_props, toStaticMarkup=to_static_markup) except FunctionError as e: raise six.reraise(ReactRenderingError, ReactRenderingError(*e.args), sys.exc_info()[2]) return RenderedComponent(markup, path, props, serialized_props, bundled_component, to_static_markup)
def render_component( # Rendering options path, props=None, to_static_markup=None, # Bundling options bundle=None, translate=None, # Prop handling json_encoder=None ): if not os.path.isabs(path): abs_path = staticfiles.find(path) if not abs_path: raise ComponentSourceFileNotFound(path) path = abs_path if not os.path.exists(path): raise ComponentSourceFileNotFound(path) bundled_component = None if bundle or translate: bundled_component = bundle_component(path, translate=translate) path = bundled_component.get_paths()[0] if json_encoder is None: json_encoder = JSONEncoder if props is not None: serialized_props = json.dumps(props, cls=json_encoder) else: serialized_props = None try: markup = js_host_function.call( path=path, serializedProps=serialized_props, toStaticMarkup=to_static_markup ) except FunctionError as e: raise six.reraise(ReactRenderingError, ReactRenderingError(*e.args), sys.exc_info()[2]) return RenderedComponent(markup, path, props, serialized_props, bundled_component, to_static_markup)
def test_bundle_urls_can_be_resolved_via_the_static_file_finder_used_by_the_dev_server(self): bundle = webpack('django_test_app/webpack.config.js') urls = bundle.get_urls() self.assertTrue(len(urls['main']['js']), 1) relative_url = urls['main']['js'][0].split('/static/')[-1] self.assertEqual(staticfiles.find(relative_url), bundle.get_assets()[0])
def render_route( # Rendering options path, # path to routes file client_path, # path to client routes file request, # pass in request object props=None, to_static_markup=None, # Bundling options bundle=None, translate=None, # Prop handling json_encoder=None ): if not os.path.isabs(path): abs_path = staticfiles.find(path) if not abs_path: raise ComponentSourceFileNotFound(path) path = abs_path if not os.path.exists(path): raise ComponentSourceFileNotFound(path) if not os.path.isabs(client_path): abs_client_path = staticfiles.find(client_path) if not abs_client_path: raise ComponentSourceFileNotFound(client_path) client_path = abs_client_path if not os.path.exists(client_path): raise ComponentSourceFileNotFound(client_path) bundled_component = None import re client_re = re.compile(r"client-(?:\w*\d*).js",re.IGNORECASE) server_re = re.compile(r"server-(?:\w*\d*).js",re.IGNORECASE) if bundle or translate: bundled_component = bundle_component(path, client_path, translate=translate) assets = bundled_component.get_assets() for asset in assets: m = client_re.search(asset['name']) if m: client_path = asset['path'] m = server_re.search(asset['name']) if m: path = asset['path'] if json_encoder is None: json_encoder = JSONEncoder if props is not None: serialized_props = json.dumps(props, cls=json_encoder) else: serialized_props = None try: location = { 'pathname': request.path, 'query': request.GET.dict() } cbData = json.loads(js_host_function.call( path=path, location=location, serializedProps=serialized_props, toStaticMarkup=to_static_markup )) except FunctionError as e: raise six.reraise(ReactRenderingError, ReactRenderingError(*e.args), sys.exc_info()[2]) if cbData['match']: return RouteRenderedComponent(cbData['markup'], client_path, props, serialized_props, bundled_component, to_static_markup) else: if cbData['redirectInfo']: return RouteRedirect(**cbData['redirectInfo']) else: return RouteNotFound()
def webpack(config_file, watch_config=None, watch_source=None): if not settings.BUNDLE_ROOT: raise ImproperlyConfigured( 'webpack.conf.settings.BUNDLE_ROOT has not been defined.') if not settings.BUNDLE_URL: raise ImproperlyConfigured( 'webpack.conf.settings.BUNDLE_URL has not been defined.') if not os.path.isabs(config_file): abs_path = staticfiles.find(config_file) if not abs_path: raise ConfigFileNotFound(config_file) config_file = abs_path if not os.path.exists(config_file): raise ConfigFileNotFound(config_file) if watch_config is None: watch_config = settings.WATCH_CONFIG_FILES if watch_source is None: watch_source = settings.WATCH_SOURCE_FILES try: output = js_host_function.call( config=config_file, watch=watch_source, watchDelay=settings.WATCH_DELAY, watchConfig=watch_config, cache=False, fullStats=settings.OUTPUT_FULL_STATS, bundleDir=settings.get_path_to_bundle_dir(), ) except FunctionError as e: raise six.reraise(BundlingError, BundlingError(*e.args), sys.exc_info()[2]) stats = json.loads(output) if stats['errors']: raise BundlingError('{}\n\n{}'.format(config_file, '\n\n'.join(stats['errors']))) if stats['warnings']: warnings.warn(stats['warnings'], WebpackWarning) # Generate contextual information about the generated assets stats['urlsToAssets'] = {} path_to_bundle_dir = settings.get_path_to_bundle_dir() for asset, config_file in six.iteritems(stats['pathsToAssets']): if path_to_bundle_dir in config_file: rel_path = config_file[len(path_to_bundle_dir):] rel_url = pathname2url(rel_path) if rel_url.startswith('/'): rel_url = rel_url[1:] url = '{}{}/{}/{}'.format(settings.BUNDLE_URL, settings.OUTPUT_DIR, settings.BUNDLE_DIR, rel_url) stats['urlsToAssets'][asset] = url return WebpackBundle(stats)