def mode(self, value): Imports.extend('codemirror-%s' % value, [ ('%s.min.js' % value, 'codemirror/%%(version)s/mode/%s/' % value) ], version="codemirror", required=["codemirror"]) self._report.jsImports.add('codemirror-%s' % value) self._config(value)
def styleActiveLine(self, value): Imports.extend('codemirror-active-line', [ ('active-line.min.js', 'codemirror/%(version)s/addon/selection/') ], version="codemirror", required=["codemirror"]) self._report.jsImports.add('codemirror-active-line') self._config(value)
def matchBrackets(self, value): # matchbrackets.js Imports.extend( 'codemirror-matchbrackets', [('matchbrackets.min.js', 'codemirror/%(version)s/addon/edit/')], version="codemirror", required=["codemirror"]) self._report.jsImports.add('codemirror-matchbrackets') self._config(value)
def html(self): """ :return: """ self.html_tmpl = HtmlTmplBase.STATIC_PAGE results = self._to_html_obj() importMng = Imports.ImportManager(online=True, report=self._report) require_js = importMng.to_requireJs(results, self.excluded_packages) results['paths'] = "{%s}" % ", ".join(["%s: '%s'" % (k, p) for k, p in require_js['paths'].items()]) results['jsFrgs_in_req'] = require_js['jsFrgs'] htmlParts = [] cssParts = dict(self._report.body.style.get_classes_css()) order_components = list(self._report.components.keys()) for component_id in order_components: component = self._report.components[component_id] if component.name == 'Body': continue if component.options.managed: htmlParts.append(component.html()) cssParts.update(component.style.get_classes_css()) body = str(self._report.body.set_content(self._report, "\n".join(htmlParts))) results['body'] = body results['header'] = self._report.headers return self.html_tmpl.strip() % results
def npm(args): """ Description: ------------ Install the external packages relying on the NPM Javascript command line availabke on the NodeJs server. This will not install the packages using the definition in Imports but on the ones in the NPM configuration. Attributes: ---------- :param parser: -pkg, String, The packages list comma separated :param parser: -s, Path of the NodeJs server """ Imports.npm(args.packages.split(","), path=args.server, is_node_server=True, update=False)
def requirements(page: primitives.PageModel, app_path: str = None): """ Description: ------------ Get the list of all the packages required in the Node Application Packages can be installed in the app using the command > nmp install package1 package2 ..... Attributes: ---------- :param primitives.PageModel page: Python object. The report object :param str app_path: """ npms = [] import_mng = Imports.ImportManager(page=page) import_mng.online = True for req in import_mng.cleanImports(page.jsImports, Imports.JS_IMPORTS): if 'register' in Imports.JS_IMPORTS[req]: if 'npm' in Imports.JS_IMPORTS[req]['register']: npm_name = Imports.JS_IMPORTS[req]['register']['npm'] npms.append(npm_name) if app_path is not None: npm_package_path = os.path.join(app_path, npm_name) if not os.path.exists(npm_package_path): print("Missing package: %s" % npm_name) else: print("No npm requirement defined for %s" % req) else: print("No npm requirement defined for %s" % req) return npms
def update(args): """ Description: ------------ Install only the defined packages locally. The install will rely on the version and configuration in the Imports module Attributes: ---------- :param parser: -pkg, String, The packages list comma separated :param parser: -p, The project path """ Imports.npm(args.packages.split(","), path=args.path, is_node_server=False, update=True)
def imports(self, online=False): """ Description: ------------ Return the :doc:`report/import_manager`, which allows to import automatically packages for certain components to run. :rtype: Imports.ImportManager """ if self.__import_manage is None: self.__import_manage = Imports.ImportManager(online, report=self) return self.__import_manage
def codepen(self, js_base: Any, css_obj: primitives.CssClsModel = None, target: str = '_self'): """ Description: ------------ Send the piece of Javascript to Codepen for testing. Related Pages: https://codepen.io/ Attributes: ---------- :param Any js_base: A Js or out Browser object. :param primitives.CssClsModel css_obj: The internal CSS object from the page. :param str target: A string flag to specify the target page in the browser. """ import webbrowser if hasattr(js_base, '_to_html_obj'): results = js_base._to_html_obj(content_only=True) js_external = re.findall( '<script language="javascript" type="text/javascript" src="(.*?)"></script>', results['jsImports']) result = { "js": results["jsFrgs"], "js_external": ";".join(js_external) } else: self.writeReport(js_base) import_obj = Imports.ImportManager() import_obj.online = True css_external = import_obj.cssURLs( import_obj.cssResolve(js_base.page.cssImport)) js_external = import_obj.jsURLs( import_obj.jsResolve(js_base.page.jsImports)) result = { "js": ";".join(self.__data), "js_external": ";".join(js_external), "css_external": ";".join(css_external) } if css_obj is not None: result["css"] = str(css_obj) data = js_base.location.postTo("https://codepen.io/pen/define/", {"data": json.dumps(result)}, target=target) out_file = open(os.path.join(self.file_path, "CodePenJsLauncher.html"), "w") out_file.write('<html><body></body><script>%s</script></html>' % data.replace("\\\\n", "")) webbrowser.open(out_file.name)
def _repr_html_(self): """ Description: ------------ Standard output for Jupyter Notebooks. This is what will use IPython in order to display the results in cells. """ results = self._to_html_obj() importMng = Imports.ImportManager(online=True, report=self._report) require_js = importMng.to_requireJs(results, self.excluded_packages) results['paths'] = "{%s}" % ", ".join(["%s: '%s'" % (k, p) for k, p in require_js['paths'].items()]) results['jsFrgs_in_req'] = require_js['jsFrgs'] return self.html_tmpl.strip() % results
def install_all(args): """ Description: ------------ Install all the internally defined packages locally. This will mimic the structure of NPM in order to facilitate the links. Attributes: ---------- :param parser: -p, The project path """ packages = set(Imports.CSS_IMPORTS.keys()) | set(Imports.JS_IMPORTS.keys()) project_path = args.path or os.getcwd() reports_path = utils.get_report_path(project_path, raise_error=False) sys.path.append(os.path.join(reports_path, '..')) static_path = "static" if os.path.exists(os.path.join(reports_path, '..', "ui_settings.py")): settings = __import__("ui_settings", fromlist=['object']) static_path = settings.PACKAGE_PATH module_path = os.path.join(reports_path, static_path) if not os.path.exists(module_path): os.makedirs(module_path) Imports.npm(packages, path=module_path, is_node_server=False, update=False)
def close(self, js_obj=None): """ Description: ------------ Write the file and close the buffer. Attributes: ---------- :param js_obj: The internal JsObject """ src_obj = js_obj.page if hasattr(js_obj, 'page') else js_obj out_file = open( os.path.join(self.file_path, "%s.js" % self.script_name), "w") js_external = "" if js_obj is not None: out_file.write("//Javascript Prototype extensions \n\n") for fnc, details in src_obj._props.get('js', {}).get('prototypes', {}).items(): out_file.write("%s = function(%s){%s};" % (fnc, ",".join( details.get('pmts', [])), details["content"])) out_file.write("\n\n//Javascript Global functions \n\n") for fnc, details in src_obj._props.get('js', {}).get('functions', {}).items(): out_file.write("function %s(%s){%s}" % (fnc, ",".join( details.get('pmt', [])), details["content"])) import_obj = Imports.ImportManager() import_obj.online = True js_external = import_obj.jsResolve(src_obj.jsImports) out_file.write("\n\n") out_file.write("//Javascript Data\n\n") for data_id, data in src_obj._props.get("data", {}).get('sources', {}).items(): out_file.write("var data_%s = %s" % (data_id, json.dumps(data))) out_file.write("\n\n") out_file.write("//Javascript functions\n\n") if len(src_obj._props.get('js', {}).get('onReady', [])) > 0: out_file.write("%s;" % jsConvertFncs( src_obj._props.get('js', {}).get('onReady', []), toStr=True)) out_file.write(";".join(self.__data)) out_file.close() with open(r"%s\Launche_%s.html" % (self.path, self.script_name), "w") as f: f.write( '<html><head></head><body></body>%s<script src="js/%s.js"></script></html>' % (js_external, self.script_name)) return r"%s\Launche_%s.html" % (self.path, self.script_name)
def codepen(self, rptObj, cssObj=None, target='_self'): """ Send the piece of Javascript to Codepen for testing Related Pages: https://codepen.io/ :param rptObj: The report object :param cssObj: The internal CSS object from the page :param target: A string flag to specify the target page in the browser """ import webbrowser if hasattr(rptObj, '_to_html_obj'): results = rptObj._to_html_obj(content_only=True) js_external = re.findall( '<script language="javascript" type="text/javascript" src="(.*?)"></script>', results['jsImports']) result = { "js": results["jsFrgs"], "js_external": ";".join(js_external) } else: self.writeReport(rptObj) import_obj = Imports.ImportManager(online=True) css_external = import_obj.cssURLs( import_obj.cssResolve(rptObj._src.cssImport)) js_external = import_obj.jsURLs( import_obj.jsResolve(rptObj._src.jsImports)) result = { "js": ";".join(self.__data), "js_external": ";".join(js_external), "css_external": ";".join(css_external) } if cssObj is not None: result["css"] = cssObj.toCss() data = rptObj.location.postTo("https://codepen.io/pen/define/", {"data": json.dumps(result)}, target=target) outFile = open(os.path.join(self.file_path, "CodePenJsLauncher.html"), "w") outFile.write('<html><body></body><script>%s</script></html>' % data.replace("\\\\n", "")) webbrowser.open(outFile.name)
def imports(self) -> Imports.ImportManager: """ Description: ------------ Return the :doc:`report/import_manager`, which allows to import automatically packages for certain components to run. By default the imports are retrieved online from CDNJS paths. This can be changed by loading the packages locally and switching off the online mode. Usage:: page = Report() page.imports :rtype: Imports.ImportManager """ if self.__import_manage is None: self.__import_manage = Imports.ImportManager(page=self) return self.__import_manage
def html(self): """ Description: ------------ Function to get the result HTML page fragments from all the HTML components. Usage: ----- page = Report() page.ui.text("This is a text") page.outs.html() """ self.html_tmpl = HtmlTmplBase.STATIC_PAGE results = self._to_html_obj() if self.page is not None: import_mng = self.page.imports else: import_mng = Imports.ImportManager(page=self.page) require_js = import_mng.to_requireJs(results, self.excluded_packages) results['paths'] = "{%s}" % ", ".join(["%s: '%s'" % (k, p) for k, p in require_js['paths'].items()]) results['jsFrgs_in_req'] = require_js['jsFrgs'] html_parts = [] css_parts = dict(self.page.body.style.get_classes_css()) results["cssStyle"] += "\n".join(list(css_parts.values())) order_components = list(self.page.components.keys()) for component_id in order_components: component = self.page.components[component_id] if component.name == 'Body': continue if component.options.managed: html_parts.append(component.html()) css_parts.update(component.style.get_classes_css()) body = str(self.page.body.set_content(self.page, "\n".join(html_parts))) for js_id, wk_content in self.page._props.get('js', {}).get("workers", {}).items(): body += '\n<script id="%s" type="javascript/worker">\n%s\n</script>' % (js_id, wk_content) results['body'] = body results['header'] = self.page.headers return self.html_tmpl.strip() % results
def _repr_html_(self): """ Description: ------------ Standard output for Jupyter Notebooks. This is what will use IPython in order to display the results in cells. """ if self.__requireJs is not None: results = self.__requireJs else: results = self._to_html_obj() if self.page is not None: importMng = self.page.imports else: importMng = Imports.ImportManager(page=self.page) require_js = importMng.to_requireJs(results, self.excluded_packages) results['paths'] = "{%s}" % ", ".join(["%s: '%s'" % (k, p) for k, p in require_js['paths'].items()]) results['jsFrgs_in_req'] = require_js['jsFrgs'] if self.__requireJs_attrs: results.update(self.__requireJs_attrs) results["pageId"] = id(self.page) return self.html_tmpl.strip() % results
import epyk as pk # from epyk.core.js import Imports from epyk.core.html import Html # Extend the current list of packages to include Google charts as a reference Imports.extend( "google-chart", [('loader.js', 'charts/')], version=None, cdnjs_url="https://www.gstatic.com", required=None) # Create the bespoke HTML component class Chart(Html.Html): # Link this component to the external Javascript module requirements = ('google-chart', ) name = "New Google Chart" def __init__(self, report, vals, html_code=None, width=None, height=None, options=None, profile=None): super(Chart, self).__init__(report, vals, html_code=html_code, css_attrs={"width": width, "height": height}) self._jsStyles = options or {} @property def _js__builder__(self): # Create the generic build function for those object # Those generic Javascrip builder are receiving the below parameters # - htmlObj: The HTML dom object # - data: The value passed in the vals variable # - options: The self._jsStyles object # This function is generic and will be used by all the different object created # This Js fragment will be used in the refresh and build method
def _to_html_obj(self, htmlParts=None, cssParts=None, split_js=False): """ Description: ------------ Create the HTML result object from the report definition Attributes: ---------- :param htmlParts: Optional. HTML Content of the page :param cssParts: Optional. CSS classes content of the page :return: A python dictionary with the HTML results """ order_components = list(self._report.components.keys()) if htmlParts is None: htmlParts, cssParts = [], {} for component_id in order_components: component = self._report.components[component_id] if component.name == 'Body': cssParts.update(component.style.get_classes_css()) continue if component.options.managed: htmlParts.append(component.html()) # cssParts.update(component.style.get_classes_css()) onloadParts, onloadPartsCommon = list(self._report._jsText), {} for data_id, data in self._report._props.get("data", {}).get('sources', {}).items(): onloadParts.append("var data_%s = %s" % (data_id, json.dumps(data))) for k, v in self._report._props.get('js', {}).get('functions', {}).items(): sPmt = "(%s)" % ", ".join(list(v["pmt"])) if "pmt" in v else "{}" onloadParts.append("function %s%s{%s}" % (k, sPmt, v["content"].strip())) if split_js: onloadPartsCommon = self._report._props.get('js', {}).get("constructors", {}) else: for c, d in self._report._props.get('js', {}).get("constructors", {}).items(): onloadParts.append(d) for c, d in self._report._props.get('js', {}).get("configs", {}).items(): onloadParts.append(str(d)) for c, d in self._report._props.get('js', {}).get("datasets", {}).items(): onloadParts.append(d) for b in self._report._props.get('js', {}).get("builders", []): onloadParts.append(b) for b in self._report._props.get('js', {}).get("builders_css", []): onloadParts.append(b) # Add the component on ready functions for component_id in order_components: component = self._report.components[component_id] if component.name == 'Body': for event, source_fncs in component._browser_data['keys'].items(): for source, event_fncs in source_fncs.get_event().items(): str_fncs = JsUtils.jsConvertFncs(event_fncs['content'], toStr=True) onloadParts.append("%s.addEventListener('%s', function(event){%s})" % (source, event, str_fncs)) continue onloadParts.extend(component._browser_data['component_ready']) for event, source_fncs in component._browser_data['mouse'].items(): for source, event_fncs in source_fncs.items(): str_fncs = JsUtils.jsConvertFncs(event_fncs['content'], toStr=True) onloadParts.append("%s.addEventListener('%s', function(event){%s})" % (source, event, str_fncs)) for event, source_fncs in component._browser_data['keys'].items(): for source, event_fncs in source_fncs.get_event().items(): str_fncs = JsUtils.jsConvertFncs(event_fncs['content'], toStr=True) onloadParts.append("%s.addEventListener('%s', function(event){%s})" % (source, event, str_fncs)) # Add the page on document ready functions for on_ready_frg in self._report._props.get('js', {}).get('onReady', []): onloadParts.append(on_ready_frg) # Add the document events functions for event, source_fncs in self._report._props.get('js', {}).get('events', []).items(): for source, event_fncs in source_fncs.get_event().items(): str_fncs = JsUtils.jsConvertFncs(event_fncs['content'], toStr=True) onloadParts.append("%s.addEventListener('%s', function(event){%s})" % (source, event, str_fncs)) importMng = Imports.ImportManager(online=True, report=self._report) results = { 'cssStyle': "%s\n%s" % ("\n".join([v for v in cssParts.values()]), "\n".join(self._report._cssText)), 'cssContainer': ";".join(["%s:%s" % (k, v) for k, v in self._report._props.get('css', {}).get('container', {}).items()]), 'content': "\n".join(htmlParts), 'jsFrgsCommon': onloadPartsCommon, # This is only used in some specific web frameworks and it is better to keep the data as list 'jsFrgs': ";".join(onloadParts), 'cssImports': importMng.cssResolve(self._report.cssImport, self._report.cssLocalImports, excluded=self.excluded_packages), 'jsImports': importMng.jsResolve(self._report.jsImports, self._report.jsLocalImports, excluded=self.excluded_packages) } return results
def html_file(self, path=None, name=None, split_files=False, install_modules=False, options=None): """ Description: ------------ Function used to generate a static HTML page for the report Usage:: Attributes: ---------- :param path: The path in which the output files will be created :param name: The filename without the extension :return: The file full path """ options = options or {} if path is None: path = os.path.join(os.getcwd(), "outs") if not os.path.exists(path): os.makedirs(path) if name is None: name = int(time.time()) html_file_path = os.path.join(path, "%s.html" % name) htmlParts = [] cssParts = dict(self._report.body.style.get_classes_css()) order_components = list(self._report.components.keys()) for component_id in order_components: component = self._report.components[component_id] if component.name == 'Body': continue if component.options.managed: htmlParts.append(component.html()) cssParts.update(component.style.get_classes_css()) body = str(self._report.body.set_content(self._report, "\n".join(htmlParts))) results = self._to_html_obj(htmlParts, cssParts, split_js=split_files) if split_files: results['cssImports'] = '%s\n<link rel="stylesheet" href="%s/%s.css" type="text/css">\n\n' % (results['cssImports'], options.get("css_route", './css'), name) body = '%s\n\n<script language="javascript" type="text/javascript" src="%s/%s.js"></script>' % (body, options.get("js_route", './js'), name) static_path = path if options.get("static_path") is not None: static_path = os.path.join(path, options.get("static_path")) if not os.path.exists(os.path.join(static_path, 'css')): os.makedirs(os.path.join(static_path, 'css')) with open(os.path.join(static_path, 'css', "%s.css" % name), "w") as f: f.write(results['cssStyle']) if not os.path.exists(os.path.join(static_path, 'js')): os.makedirs(os.path.join(static_path, 'js')) with open(os.path.join(static_path, 'js', "%s.js" % name), "w") as f: f.write(";".join(results['jsFrgsCommon'].values())) # Add the worker sections when no server available for js_id, wk_content in self._report._props.get('js', {}).get("workers", {}).items(): body += '\n<script id="%s" type="javascript/worker">\n%s\n</script>' % (js_id, wk_content) with open(html_file_path, "w") as f: results['body'] = body results['header'] = self._report.headers f.write(HtmlTmplBase.STATIC_PAGE % results) if install_modules and self._report._node_modules is not None: Imports.npm(self._report.imports().requirements, path=self._report._node_modules[0], is_node_server=False) return html_file_path
'select', 'select-ajax', 'vis', 'mathjs', 'socket.io', 'codemirror', 'leaflet', 'showdown', 'sortable', 'google-platform']] class Font(object): size, header_size, unit = 20, 14, "px" family = "Calibri" css.Font = Font EXTENSIONS = {} Imports.extend_imports(EXTENSIONS) def build_interface(): """ This function will build a new components hierarchy which will be used in project mode. """ import os import sys import inspect core_component_path = os.path.split(html.__file__)[0] sys.path.append(core_component_path) module_per_package = {} for paths in [core_component_path] + HTML_COMPONENTS_PATH : for f in os.listdir(paths):
from epyk.core.js import Imports Imports.extend("json-pretty-formatter", [ ('json-formatter.umd.min.js', "json-formatter-js@%(version)s/dist/"), ('json-formatter.css', "json-formatter-js@%(version)s/dist/"), ], version="2.3.4", cdnjs_url="https://cdn.jsdelivr.net/npm")
def _to_html_obj(self, htmlParts: Optional[List[str]] = None, cssParts: Optional[Dict[str, Any]] = None, split_js: bool = False): """ Description: ------------ Create the HTML result object from the report definition. Attributes: ---------- :param Optional[List[str]] htmlParts: Optional. HTML Content of the page. :param Optional[List[str]] cssParts: Optional. CSS classes content of the page. :param bool split_js: Optional. Flag to specify if JS, CSS and HTML need to be written in different files. :return: A python dictionary with the HTML results """ order_components = list(self.page.components.keys()) if htmlParts is None: htmlParts, cssParts = [], {} for component_id in order_components: component = self.page.components[component_id] if component.name == 'Body': cssParts.update(component.style.get_classes_css()) continue if component.options.managed: htmlParts.append(component.html()) # For cells in Jupyter notebooks if self.__jupyter_cell: component.options.managed = False # cssParts.update(component.style.get_classes_css()) onloadParts, onloadPartsCommon = list(self.page.properties.js.frgs), {} for data_id, data in self.page._props.get("data", {}).get('sources', {}).items(): onloadParts.append("var data_%s = %s" % (data_id, json.dumps(data))) for k, v in self.page._props.get('js', {}).get('functions', {}).items(): pmt = "(%s)" % ", ".join(list(v["pmt"])) if "pmt" in v else "{}" onloadParts.append("function %s%s{%s}" % (k, pmt, v["content"].strip())) if split_js: onloadPartsCommon = self.page._props.get('js', {}).get("constructors", {}) else: for c, d in self.page._props.get('js', {}).get("constructors", {}).items(): onloadParts.append(d) for c, d in self.page._props.get('js', {}).get("configs", {}).items(): onloadParts.append(str(d)) for c, d in self.page._props.get('js', {}).get("datasets", {}).items(): onloadParts.append(d) for b in self.page._props.get('js', {}).get("builders", []): onloadParts.append(b) for b in self.page._props.get('js', {}).get("builders_css", []): onloadParts.append(b) # Add the component on ready functions for component_id in order_components: component = self.page.components[component_id] if component.name == 'Body': for event, source_funcs in component._browser_data['keys'].items(): for source, event_funcs in source_funcs.get_event().items(): str_funcs = JsUtils.jsConvertFncs( event_funcs['content'], toStr=True, profile=event_funcs.get("profile", False)) onloadParts.append("%s.addEventListener('%s', function(event){%s})" % (source, event, str_funcs)) continue onloadParts.extend(component._browser_data['component_ready']) for event, source_funcs in component._browser_data['mouse'].items(): for source, event_funcs in source_funcs.items(): str_funcs = JsUtils.jsConvertFncs( event_funcs['content'], toStr=True, profile=event_funcs.get("profile", False)) if 'sub_items' in event_funcs: # This is using jquery # TODO: Find a way to replace Jquery onloadParts.append( "%s.on('%s', '%s', function(event){%s})" % (source, event, event_funcs['sub_items'], str_funcs)) else: onloadParts.append("%s.%s('%s', function(event){%s})" % ( source, event_funcs.get("fncType", "addEventListener"), event, str_funcs)) for event, source_funcs in component._browser_data['keys'].items(): for source, event_funcs in source_funcs.get_event().items(): str_funcs = JsUtils.jsConvertFncs( event_funcs['content'], toStr=True, profile=event_funcs.get("profile", False)) onloadParts.append("%s.addEventListener('%s', function(event){%s})" % (source, event, str_funcs)) # Add the page on document ready functions for on_ready_frg in self.page._props.get('js', {}).get('onReady', []): onloadParts.append(on_ready_frg) # Add the document events functions for event, source_funcs in self.page._props.get('js', {}).get('events', []).items(): for source, event_funcs in source_funcs.get_event().items(): str_funcs = JsUtils.jsConvertFncs(event_funcs['content'], toStr=True) onloadParts.append("%s.addEventListener('%s', function(event){%s})" % (source, event, str_funcs)) if self.page is not None: import_mng = self.page.imports else: import_mng = Imports.ImportManager(page=self.page) results = { 'cssStyle': "%s\n%s" % ("\n".join([v for v in cssParts.values()]), self.page.properties.css.text), 'cssContainer': ";".join( ["%s:%s" % (k, v) for k, v in self.page._props.get('css', {}).get('container', {}).items()]), 'content': "\n".join(htmlParts), # This is only used in some specific web frameworks and it is better to keep the data as list 'jsFrgsCommon': onloadPartsCommon, 'jsFrgs': ";".join(onloadParts), 'cssImports': import_mng.cssResolve( self.page.cssImport, self.page.cssLocalImports, excluded=self.excluded_packages), 'jsImports': import_mng.jsResolve( self.page.jsImports, self.page.jsLocalImports, excluded=self.excluded_packages) } return results
def install(path: str, packages: list = None, node_server: bool = False, update: bool = False, verbose: bool = True, page: primitives.PageModel = None): """ Description: ------------ Install files using the npm structure is compatible. This will allow to run the script totally locally (without dependency on internet). Usage:: PyNpm.install(r"C:\tmps\packages", ['bootstrap'], update=True) Attributes: ---------- :param list packages: All the packages to be added to the install :param str path: Optional. The install path (if node server, the folder root for /node_modules :param bool node_server: Boolean. Optional. Specify if npm from NodeJs must be used to install the package :param bool update: Optional. Specify is the version of the package needs to be updated :param bool verbose: Optional. Display version details (default True). :param primitives.PageModel page: Optional. The Page / Report object on which the list of packages will be defined. """ if packages is None: if page is None: raise ValueError("Package or page must be defined") packages = page.imports.requirements if node_server: if not isinstance(packages, list): packages = [packages] if update: subprocess.run('npm update %s' % " ".join(packages), shell=True, cwd=path) else: to_be_installed = [] for p in packages: package_path = os.path.join(path, 'node_modules', p) if not os.path.exists(package_path): to_be_installed.append(p) if to_be_installed: subprocess.run('npm install %s' % " ".join(to_be_installed), shell=True, cwd=path) if verbose: logging.warning(" PYK_NPM >> All packages installed [%s]" % " ".join(to_be_installed)) elif verbose: logging.warning(" PYK_NPM >> packages already installed") else: if verbose and not path.endswith("node_modules"): logging.warning("NodeJs is using a node_modules folder.") for p in packages: if not os.path.exists(os.path.join(path, p)) or update: for category in [Imports.JS_IMPORTS, Imports.CSS_IMPORTS]: for mod in category.get(p, {}).get('modules', []): request = Request(Imports.script_cdnjs_path(p, mod)) response = urlopen(request).read() script_path = Imports.script_npm_path(p, mod, path) mod_path, script = os.path.split(script_path) if not os.path.exists(mod_path): os.makedirs(mod_path) with open(script_path, "wb") as f: f.write(response) # Add extra ressources required by the package. for mod in category.get(p, {}).get('assets', []): request = Request(Imports.script_cdnjs_path(p, mod)) response = urlopen(request).read() script_path = Imports.script_npm_path(p, mod, path) mod_path, script = os.path.split(script_path) if not os.path.exists(mod_path): os.makedirs(mod_path) with open(script_path, "wb") as f: f.write(response)
""" """ import collections from epyk.core.js import Imports from epyk.core.Page import Report #Imports.installed_packages() report = Report() imports = Imports.ImportManager(report=report) modules = collections.OrderedDict() print(imports.getModules(modules, 'c3')) i = imports.cleanImports(['c3'], Imports.JS_IMPORTS) print(i) i = imports.cssResolve(['c3']) print(i) f = imports.getFiles(['c3'], ['c3']) print(f['css'][0]['file']['script']) # p = imports.getPackage('jqueryui', static_path=r"..\outs") p = imports.getFullPackage('font-awesome', static_path=r"..\outs")
from epyk.core.js import Imports Imports.extend( "js-datepicker", [ ('datepicker.min.js', ''), ('datepicker.min.css', ''), ], version="5.11.0", cdnjs_url= "https://raw.githubusercontent.com/qodesmith/datepicker/master/dist")