当前位置: 首页>>代码示例>>Python>>正文


Python slimit.minify函数代码示例

本文整理汇总了Python中slimit.minify函数的典型用法代码示例。如果您正苦于以下问题:Python minify函数的具体用法?Python minify怎么用?Python minify使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了minify函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: bake_js

def bake_js(source_dir="js5", dest_file="script5.js"):
	create_baked_directory()
	fn = os.path.join(os.path.dirname(__file__), "..", "static", "baked", str(get_build_number()), dest_file)
	if not os.path.exists(fn):
		js_content = ""
		for sfn in get_js_file_list(source_dir):
			jsfile = open(os.path.join(os.path.dirname(__file__), "..", sfn))
			js_content += minify(jsfile.read()) + "\n"
			jsfile.close()

		o = open(fn, "w")
		o.write(minify(js_content, mangle=True, mangle_toplevel=False))
		o.close()
开发者ID:Abchrisabc,项目名称:rainwave,代码行数:13,代码来源:buildtools.py

示例2: build

    def build(cls, basepath, bundle_key, ext):
        bundle = {}

        # Iterate over files in bundle; determine last modified time and
        # assemble content
        last_mtime = 0
        contents = ""
        for path in ASSET_MANIFEST[bundle_key]:
            path = os.path.join(os.path.abspath(basepath),
                path[len('/static/'):])
            last_mtime = max(last_mtime, os.stat(path)[stat.ST_MTIME])
            contents += open(path, "rb").read() + "\n"

        if ext == "js":
            bundle["contents"] = slimit.minify(contents, mangle=True,
                mangle_toplevel=True)
        elif ext == "css":
            bundle["contents"] = cssmin.cssmin(contents)
        else:
            assert False

        bundle["sha1"] = hashlib.sha1(bundle["contents"]).hexdigest()
        bundle["last_modified"] = datetime.datetime.fromtimestamp(last_mtime)
        bundle["mime_type"] = "text/javascript" if ext == "js" else "text/css"

        StaticBuild._bundles[bundle_key] = bundle
开发者ID:imclab,项目名称:rendr.it,代码行数:26,代码来源:__init__.py

示例3: minify_scripts

    def minify_scripts():
        try:
            import slimit
            for fn in load_static_file_paths('ui/*.js'):
                if 'packages' in fn or not os.access(os.path.dirname(fn), os.W_OK):
                    return
                if fn.endswith('.min.js'):
                    continue
                min_fn = fn.replace('.js', '.min.js')
                if os.path.exists(min_fn) and os.path.getmtime(fn) <= os.path.getmtime(min_fn):
                    continue
                with codecs.open(fn, encoding='utf-8') as inf:
                    content = inf.read()
                    minified = slimit.minify(content, mangle=True, mangle_toplevel=True)
                    with codecs.open(min_fn, 'w', encoding='utf-8') as outf:
                        outf.write(minified)

            import csscompressor
            for fn in load_static_file_paths('ui/*.css'):
                if 'packages' in fn or not os.access(os.path.dirname(fn), os.W_OK):
                    return
                if fn.endswith('.min.css'):
                    continue
                min_fn = fn.replace('.css', '.min.css')
                if os.path.exists(min_fn) and os.path.getmtime(fn) <= os.path.getmtime(min_fn):
                    continue
                with codecs.open(fn, encoding='utf-8') as inf:
                    content = inf.read()
                    minified = csscompressor.compress(content)
                    with codecs.open(min_fn, 'w', encoding='utf-8') as outf:
                        outf.write(minified)
        except ImportError:
            pass
开发者ID:tradaniel,项目名称:aliyun-odps-python-sdk,代码行数:33,代码来源:common.py

示例4: compressJs

 def compressJs(self, s):
     """ Compress JS string. """
     jscompiler = config.get('global', 'jscompiler')
     if jscompiler == 'internal':
         from slimit import minify
         s = minify(s, mangle=False)
         
     else:
         tmp = open('/tmp/wctmp', 'w')
         tmp.write(s)
         tmp.close()
         
         cmd = jscompiler % {'input':'/tmp/wctmp', 'output':'/tmp/wctmpout'}
         proc = subprocess.Popen([cmd], 
             shell=True, 
             stdin=subprocess.PIPE, 
             stdout=subprocess.PIPE, 
             stderr=subprocess.PIPE)
         for line in proc.stdout.readlines():
             sys.stdout.write(line)
         for line in proc.stderr.readlines():
             sys.stdout.write(line)
         
         proc.wait()
         if proc.returncode != 0:
             exit(1)
             
         tmp = open('/tmp/wctmpout', 'r')
         s = tmp.read().strip()
         tmp.close()
         
     return s
开发者ID:Eyjafjallajokull,项目名称:wecomp,代码行数:32,代码来源:wecomp.py

示例5: handle_javascript

def handle_javascript(js_data, mangle=True, mangle_toplevel=True):
    """
    压缩混淆js
    :param js_data: js字符串
    :return:
    """
    return minify(js_data, mangle=mangle, mangle_toplevel=mangle_toplevel)
开发者ID:yubang,项目名称:modular_front,代码行数:7,代码来源:static_minify.py

示例6: run

    def run(self):
        """Execute command"""
        if not slimit:
            print("You need `slimit' module to minify JavaScript files")
            return

        for root, _, files in os.walk("kiroku/data/js"):
            for fname in files:
                if ".min." in fname:
                    continue

                fname = os.path.join(root, fname)
                minified = None
                new_name, ext = os.path.splitext(fname)
                new_name = os.path.join(new_name + ".min" + ext)

                with open(fname) as fobj:
                    minified = slimit.minify(fobj.read(), mangle=True)

                if minified:
                    with open(new_name, "w") as fobj:
                        fobj.write(minified)
                    # append minified file path without leading 'kiroku/'
                    new_name = new_name[7:]
                    self.distribution.package_data['kiroku'].append(new_name)
开发者ID:gryf,项目名称:kiroku,代码行数:25,代码来源:setup.py

示例7: minify_string

 def minify_string(self, string, outfile=None, *, path=None):
     from slimit import minify
     result = minify(string, mangle=True)
     if outfile:
         open(outfile, 'w').write(result)
     else:
         return result
开发者ID:score-framework,项目名称:py.js,代码行数:7,代码来源:minifier.py

示例8: minicite

def minicite(js_names, do_wrap, do_minify):
    '''Concatenate, wrap, and minify project JavaScript files.'''
    
    # Read code
    js_files = [open(js_name).read() for js_name in js_names]
    
    # Concatenate code
    js = '\n\n'.join(js_files)

    # Optionally wrap code
    # Note: Wrapper file must contain %s for interpolation
    if do_wrap:

        # Read wrapper
        with open('js-util/wrapper.js') as wrap_file:
            wrap = wrap_file.read()
        
        # Wrap code
        js = wrap % js

    # Optionally minify code
    if do_minify:
        js = slimit.minify(js, mangle=True)
    
    # Return code
    return js
开发者ID:CenterForOpenScience,项目名称:scinet-citelet,代码行数:26,代码来源:minify.py

示例9: wrap_mini

def wrap_mini(paths, basename='pdp', debug=True):
    '''
    :param paths: list of paths to JavaScript files that are to be minified
    :type paths: list of strings
    :param basename: a prefix to prepend to the minified filename. The
                     minified filename will be {basename}-min-{pdp_version}.js
    :type basename: string
    :param debug: If set to True, no minification takes place and the input
                  `paths` are returned as is.
    :type debug: bool
    :returns: list of strings -- the strings is a filesystem path to the
              minified version of the file. If debug is set to True, the return
              value will be equal to the input `paths`.
    '''
    if debug:
        return paths
    else:
        d = resource_filename('pdp', 'static')
        version = get_distribution('pdp').version
        s = ''
        for path in paths:
            with open(os.path.join(d, path), 'r') as f:
                s += f.read()
        smin = minify(s, mangle=True, mangle_toplevel=False)
        outname = '{basename}-min-{version}.js'.format(**locals())
        outpath = os.path.join(d, outname)
        with open(outpath, 'w') as f:
            f.write(smin)
        return [outname]
开发者ID:pacificclimate,项目名称:pdp,代码行数:29,代码来源:minify.py

示例10: _build_javascript

    def _build_javascript(self):
        js_name = self._config['js_name'] + '.js'
        source = os.path.join(self._cwd, 'src', js_name)
        dest = os.path.join(self._config['build_path'], js_name)

        if not os.path.exists(source):
            source = os.path.join(self._cwd, 'src', 'application.js')
            if not os.path.exists(source):
                return

        try:
            self._js_string = self._concat_javascript(source)
        except:
            raise

        if os.path.exists(dest):
            try:
                os.remove(dest)
            except:
                raise RemoveFileError('Could not delete the existing javascript application file.')

        try:
            f = open(dest, 'w+')
        except:
            raise FileNotWritableError('Could not write the javascript file.')

        if self._config['minify_js']:
            self._js_string = minify(self._js_string, mangle=True, mangle_toplevel=True)

        f.write(self._js_string)
        f.close()
开发者ID:dsteinbrunner,项目名称:grace,代码行数:31,代码来源:build.py

示例11: _minify

    def _minify(self, data, type, paths=[]):
        sep = ''

        # figure out how to minify something
        if type == 'javascript':
            sep = ';'

            # use envoy to run the custom command if it's supplied
            custom = self.config.get('js_minifier')
            if custom is not None:
                minify = lambda x: envoy.run(custom, data=x).std_out

            # otherwise use slimit
            else:
                options = self.config.get(
                  'js_minifier_options', {'mangle': True}
                )

                minify = lambda x: slimit.minify(x, **options)

        elif type == 'css':
            # only one option for css right now
            minify = cssmin.cssmin

        def real_minify(path, contents):
            if '.min' in path:
                return contents

            return minify(contents)

        minified = sep.join(
          [real_minify(path, contents) for path, contents in zip(paths, data)]
        )

        return minified
开发者ID:itsky365,项目名称:crammit,代码行数:35,代码来源:__init__.py

示例12: build_asset

def build_asset( destdir, asset ):

	target = os.path.join( destdir, assets.assets[ asset ][ 'output' ] )

	destination = open( target, 'wb' )

	for jsname in assets.assets[ asset ]['order']:

		isMax = False

		try:
			fname = assets.assets[ asset ][ 'min_files' ][ jsname ]
		except KeyError, ke:
			fname = assets.assets[ asset ][ 'max_files' ][ jsname ]
			isMax = True


		newname = os.path.join( os.path.dirname( os.path.realpath( __file__ ) ), 'static', fname )

		f = open( newname, 'rb')
		if isMax is True:
			print 'minifying and concatenating ' + fname
			destination.write(
				minify( f.read(), mangle = True, mangle_toplevel = False )
			)
		else:
			print 'concatenating ' + fname
			destination.write( f.read() )

		f.close()
开发者ID:SouthPatron,项目名称:django-ravensuite,代码行数:30,代码来源:rs.py

示例13: run

def run():
	minified = ""
	for currentFile in files:
		minified += minify(open('../static/js/' + currentFile).read(), mangle=True, mangle_toplevel=True)
		minified += '\n'
	minFile = open('../static/js/main.js', 'w')
	minFile.write(minified)
	minFile.close()
开发者ID:AbhiAgarwal,项目名称:dubsit,代码行数:8,代码来源:minify.py

示例14: _compress

    def _compress(self):
        output = []

        for src in self.includes:
            with open('www/%s' % src) as f:
                output.append(minify(f.read()))

        return '\n'.join(output)
开发者ID:imclab,项目名称:in-memoriam,代码行数:8,代码来源:render_utils.py

示例15: minify_file

def minify_file(file_debug, file_minified):
    try:
        return minify_closure(file_debug, file_minified)
    except NameError:
        with open(file_minified, 'w') as file_out:
            with open(file_debug, 'r') as file_in:
                file_out.write(minify(file_in.read()))
                return True
开发者ID:deluge-torrent,项目名称:deluge,代码行数:8,代码来源:minify_web_js.py


注:本文中的slimit.minify函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。