def styles(request, name): src = '' namespace = Namespace() for tv in ThemeValue.objects.all(): namespace.set_variable('${}-{}'.format(tv.group, tv.name), String(tv.value)) compiler = Compiler(namespace=namespace) return HttpResponse(compiler.compile_string(src), content_type='text/css')
def style_scss(self, *path): css_namespace = Namespace() for key, value in self.settings['keys'].items(): if isinstance(value, LCText): css_value = String(value) elif isinstance(value, LCColour): css_value = Color.from_hex(value) elif isinstance(value, LCBool): css_value = Boolean(value.simple()) elif isinstance(value, LCSpin): css_value = Number(value.simple()) else: raise ValueError("Unable to find comparable values") css_namespace.set_variable('${}'.format(key), css_value) cherrypy.response.headers['Content-Type'] = 'text/css' with open(os.path.join(self.settings['location'], *path), 'r') as css: css_content = css.read() compiler = Compiler(namespace=css_namespace, output_style='nested') # Something wrong with PyScss, # Syntax error: Found u'100%' but expected one of ADD. # Doesn't happen on next attempt, so we are doing bad thing attempts = 0 while attempts < 100: try: attempts += 1 ret_string = compiler.compile_string(css_content) return ret_string except Exception as exc: if attempts == 100: log.debug(exc)
def render_scss_file(filename, namespace): root_dir = os.path.dirname(filename) base_name, base_extension = os.path.splitext(os.path.basename(filename)) render_filename = os.path.join(root_dir, 'render_{}.css'.format(base_name)) with open(filename, 'r') as css_file, open(render_filename, 'w') as render_file: css_content = css_file.read() compiler = Compiler(namespace=namespace, output_style='compressed') render_file.write(compiler.compile_string(css_content))
def compile_file(self, infile, outfile, outdated=False, force=False): # noinspection PyUnresolvedReferences,PyUnresolvedReferences,PyPackageRequirements from scss import Compiler root = Path(os.path.abspath(settings.STATIC_ROOT)) compiler = Compiler(root=root, search_path=("./",)) css_content = compiler.compile(infile) with open(outfile, "w") as fd: fd.write(css_content) if self.verbose: print(css_content)
def compile_file(self, infile, outfile, outdated=False, force=False): # noinspection PyUnresolvedReferences,PyUnresolvedReferences,PyPackageRequirements from scss import Compiler root = Path(os.path.abspath(settings.STATIC_ROOT)) compiler = Compiler(root=root, search_path=("./", )) css_content = compiler.compile(infile) with open(outfile, "w") as fd: fd.write(css_content) if self.verbose: print(css_content)
def compile_scss(self, scss=''): """ Please make sure that https://pypi.org/project/pyScss/ is installed """ try: from scss import Compiler css = Compiler().compile_string(scss) except: css = '/* COMPILER ERROR: Details see Zope event.log */' # clean whitespace css_lines = [l.lstrip() for l in css.split('\n')] return '\n'.join(css_lines)
def generate_css_files(cls): from scss import Compiler print('Building CSS files') base_path = path( os.path.join('platypush', 'backend', 'http', 'static', 'css')) input_path = path(os.path.join(base_path, 'source')) output_path = path(os.path.join(base_path, 'dist')) for root, dirs, files in os.walk(input_path, followlinks=True): scss_file = os.path.join(root, 'index.scss') if os.path.isfile(scss_file): css_path = os.path.split( scss_file[len(input_path):])[0][1:] + '.css' css_dir = os.path.join(output_path, os.path.dirname(css_path)) css_file = os.path.join(css_dir, os.path.basename(css_path)) os.makedirs(css_dir, exist_ok=True) print('\tGenerating CSS {scss} -> {css}'.format(scss=scss_file, css=css_file)) with open(css_file, 'w') as f: css_content = Compiler(output_style='compressed', search_path=[root, input_path ]).compile(scss_file) css_content = cls._fix_css4_vars(css_content) f.write(css_content)
def generate_css_files(cls): try: # noinspection PyPackageRequirements from scss import Compiler except ImportError: print('pyScss module not found: {}. You will have to generate ' + 'the CSS files manually through python setup.py build install') return print('Building CSS files') base_path = path(os.path.join('platypush', 'backend', 'http', 'static', 'css')) input_path = path(os.path.join(base_path, 'source')) output_path = path(os.path.join(base_path, 'dist')) for root, dirs, files in os.walk(input_path, followlinks=True): scss_file = os.path.join(root, 'index.scss') if os.path.isfile(scss_file): css_path = os.path.split(scss_file[len(input_path):])[0][1:] + '.css' css_dir = os.path.join(output_path, os.path.dirname(css_path)) css_file = os.path.join(css_dir, os.path.basename(css_path)) os.makedirs(css_dir, exist_ok=True) print('\tGenerating CSS {scss} -> {css}'.format(scss=scss_file, css=css_file)) with open(css_file, 'w') as f: css_content = Compiler(output_style='compressed', search_path=[root, input_path]).compile(scss_file) css_content = cls._fix_css4_vars(css_content) f.write(css_content)
def handle_scss(scss_str): """ 编译scss字符串 :param scss_str: scss字符串 :return: """ return Compiler().compile_string(scss_str)
def template_static(filename): template_path = os.path.join( app.config['PROJECT_PATH'], 'application/templates/{}'.format( redis.get(app.config.get('THEME_KEY')))) if filename[-4:] == 'scss': file_path = os.path.join(template_path, filename) print "file_path: {}".format(file_path) filename = "{}{}".format(filename[:-4], "css") full_path = os.path.join(template_path, filename) if not os.path.exists(file_path): abort(404) with open(full_path, 'w') as f: f.write(Compiler().compile(file_path)) return send_from_directory(template_path, filename) else: abort(404)
def main(infile, outfile, format): yaml_file = infile.read() yaml_data = yaml.load(yaml_file) # Cache the current STDOUT, then replace it with a StringIO instance. cached_stdout = sys.stdout program_output = six.StringIO() sys.stdout = program_output # This will print to STDOUT, which will be captured into StringIO. parse_data(yaml_data) program_output.seek(0) scss_data = program_output.read() if format == 'scss': outfile.write(scss_data) elif format == 'css': outfile.write(Compiler().compile_string(scss_data)) sys.stdout = cached_stdout
from flask import Flask from scss import Scss from scss import Compiler Compiler().compile_string("a { color: red + green; }") app = Flask(__name__) if __name__ == '__main__': app.run(debug=True) from app import error from app import main from app import models
def cookWhenChangingSettings(context, bundle=None): """When our settings are changed, re-cook the not compilable bundles""" registry = getUtility(IRegistry) resources = registry.collectionOfInterface( IResourceRegistry, prefix="plone.resources", check=False ) if bundle is None: # default to cooking legacy bundle bundles = registry.collectionOfInterface( IBundleRegistry, prefix="plone.bundles", check=False ) if "plone-legacy" in bundles: bundle = bundles["plone-legacy"] else: bundle = bundles.setdefault("plone-legacy") bundle.resources = [] if not bundle.resources: # you can have a bundle without any resources defined and it's just # shipped as a legacy compiled js file return js_path = bundle.jscompilation css_path = bundle.csscompilation if not js_path and not css_path: logger.warning( "No js_path or css_path found. We need a plone.resource " "based resource path in order to store the compiled JS and CSS." ) return # Let's join all css and js css_compiler = Compiler(output_style="compressed") cooked_css = "" cooked_js = REQUIREJS_RESET_PREFIX siteUrl = getSite().absolute_url() request = getRequest() for package in bundle.resources or []: if package not in resources: continue resource = resources[package] if css_path: for css_resource in resource.css: css_url = siteUrl + "/" + css_resource response = subrequest(css_url) if response.status == 200: logger.info("Cooking css %s", css_resource) css = response.getBody() if css_resource[-8:] != ".min.css": css = css_compiler.compile_string(css) if not isinstance(css, str): css = css.decode("utf8") cooked_css += "\n/* Resource: {} */\n{}\n".format(css_resource, css) else: cooked_css += "\n/* Could not find resource: {} */\n\n".format( css_resource ) logger.warning("Could not find resource: %s", css_resource) if not resource.js or not js_path: continue js_url = siteUrl + "/" + resource.js response = subrequest(js_url) if response.status == 200: logger.info("Cooking js %s", resource.js) js = response.getBody() if not isinstance(js, str): js = js.decode("utf8") try: cooked_js += "\n/* resource: {} */\n{}".format( resource.js, js if resource.js.endswith(".min.js") else es5.minify_print(js), ) except SyntaxError: cooked_js += "\n/* Resource (error cooking): {} */\n{}".format( resource.js, js ) logger.warning("Error cooking resource: %s", resource.js) else: logger.warning("Could not find resource: %s", resource.js) cooked_js += "\n/* Could not find resource: {} */\n\n".format(js_url) cooked_js += REQUIREJS_RESET_POSTFIX persistent_directory = getUtility(IResourceDirectory, name="persistent") if OVERRIDE_RESOURCE_DIRECTORY_NAME not in persistent_directory: persistent_directory.makeDirectory(OVERRIDE_RESOURCE_DIRECTORY_NAME) container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME] def _write_resource(resource_path, cooked_string): if not resource_path: return if "++plone++" in resource_path: resource_path = resource_path.split("++plone++")[-1] if "/" in resource_path: resource_name, resource_filepath = resource_path.split("/", 1) else: resource_name = "legacy" resource_filepath = resource_path if resource_name not in container: container.makeDirectory(resource_name) if not isinstance( cooked_string, bytes ): # handle Error of OFS.Image # noqa: E501 cooked_string = cooked_string.encode("ascii", errors="ignore") try: folder = container[resource_name] fi = BytesIO(cooked_string) folder.writeFile(resource_filepath, fi) logger.info("Writing cooked resource: %s", resource_path) except NotFound: logger.warning("Error writing cooked resource: %s", resource_path) _write_resource(js_path, cooked_js) _write_resource(css_path, cooked_css) bundle.last_compilation = datetime.now() # refresh production meta bundles combine_bundles(context) # Disable CSRF protection on this request alsoProvides(request, IDisableCSRFProtection)
"""Compile static assets.""" from flask import current_app as app from flask_assets import Bundle from scss import Compiler from scss.namespace import Namespace namespace = Namespace() compiler = Compiler(namespace=namespace) # Namespace variables def pyscss_filter(_in, out, **kw): """ Custom pyscss filter, I forgot why, but I know its needed :param _in: Input stream that reads the scss file :param out: Out stream that writes to the css file :param kw: :return: """ out.write(compiler.compile_string(_in.read())) def compile_static_assets(assets): """ Create stylesheet bundles. :param assets: Flask-Assets Environment :type assets: Environment """ assets.auto_build = True assets.debug = True
def cookWhenChangingSettings(context, bundle=None): """When our settings are changed, re-cook the not compilable bundles """ registry = getUtility(IRegistry) resources = registry.collectionOfInterface(IResourceRegistry, prefix="plone.resources", check=False) if bundle is None: # default to cooking legacy bundle bundles = registry.collectionOfInterface(IBundleRegistry, prefix="plone.bundles", check=False) if 'plone-legacy' in bundles: bundle = bundles['plone-legacy'] else: bundle = bundles.setdefault('plone-legacy') bundle.resources = [] if not bundle.resources: # you can have a bundle without any resources defined and it's just # shipped as a legacy compiled js file return js_path = bundle.jscompilation css_path = bundle.csscompilation if not js_path and not css_path: logger.warn( 'No js_path or css_path found. We need a plone.resource ' 'based resource path in order to store the compiled JS and CSS.') return # Let's join all css and js css_compiler = Compiler(output_style='compressed') cooked_css = u'' cooked_js = REQUIREJS_RESET_PREFIX siteUrl = getSite().absolute_url() request = getRequest() for package in bundle.resources or []: if package not in resources: continue resource = resources[package] if css_path: for css_resource in resource.css: css_url = siteUrl + '/' + css_resource response = subrequest(css_url) if response.status == 200: logger.info('Cooking css %s', css_resource) css = response.getBody() if css_resource[-8:] != '.min.css': css = css_compiler.compile_string(css) cooked_css += u'\n/* Resource: {0} */\n{1}\n'.format( css_resource, css) else: cooked_css +=\ u'\n/* Could not find resource: {0} */\n\n'.format( css_resource ) logger.warn('Could not find resource: %s', css_resource) if not resource.js or not js_path: continue js_url = siteUrl + '/' + resource.js response = subrequest(js_url) if response.status == 200: js = response.getBody() try: logger.info('Cooking js %s', resource.js) cooked_js += '\n/* resource: {0} */\n{1}'.format( resource.js, js if '.min.js' == resource.js[-7:] else minify(js, mangle=False, mangle_toplevel=False)) except SyntaxError: cooked_js +=\ '\n/* Resource (error cooking): {0} */\n{1}'.format( resource.js, js ) logger.warn('Error cooking resource: %s', resource.js) else: logger.warn('Could not find resource: %s', resource.js) cooked_js += '\n/* Could not find resource: {0} */\n\n'.format( js_url) cooked_js += REQUIREJS_RESET_POSTFIX persistent_directory = getUtility(IResourceDirectory, name="persistent") if OVERRIDE_RESOURCE_DIRECTORY_NAME not in persistent_directory: persistent_directory.makeDirectory(OVERRIDE_RESOURCE_DIRECTORY_NAME) container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME] def _write_resource(resource_path, cooked_string): if not resource_path: return resource_path = resource_path.split('++plone++')[-1] resource_name, resource_filepath = resource_path.split('/', 1) if resource_name not in container: container.makeDirectory(resource_name) if not isinstance(cooked_string, str): # handle Error of OFS.Image cooked_string = cooked_string.encode('ascii', errors='ignore') try: folder = container[resource_name] fi = StringIO(cooked_string) folder.writeFile(resource_filepath, fi) logger.info('Writing cooked resource: %s', resource_path) except NotFound: logger.warn('Error writing cooked resource: %s', resource_path) _write_resource(js_path, cooked_js) _write_resource(css_path, cooked_css) bundle.last_compilation = datetime.now() # refresh production meta bundles combine_bundles(context) # Disable CSRF protection on this request alsoProvides(request, IDisableCSRFProtection)
def cookWhenChangingSettings(context, bundle=None): """When our settings are changed, re-cook the not compilable bundles """ registry = getUtility(IRegistry) resources = registry.collectionOfInterface( IResourceRegistry, prefix="plone.resources", check=False) if bundle is None: # default to cooking legacy bundle bundles = registry.collectionOfInterface( IBundleRegistry, prefix="plone.bundles", check=False) if 'plone-legacy' in bundles: bundle = bundles['plone-legacy'] else: bundle = bundles.setdefault('plone-legacy') bundle.resources = [] if not bundle.resources: # you can have a bundle without any resources defined and it's just # shipped as a legacy compiled js file return js_path = bundle.jscompilation css_path = bundle.csscompilation if not js_path and not css_path: logger.warn( 'No js_path or css_path found. We need a plone.resource ' 'based resource path in order to store the compiled JS and CSS.' ) return # Let's join all css and js css_compiler = Compiler(output_style='compressed') cooked_css = u'' cooked_js = REQUIREJS_RESET_PREFIX siteUrl = getSite().absolute_url() request = getRequest() for package in bundle.resources or []: if package not in resources: continue resource = resources[package] if css_path: for css_resource in resource.css: css_url = siteUrl + '/' + css_resource response = subrequest(css_url) if response.status == 200: logger.info('Cooking css %s', css_resource) css = response.getBody() if css_resource[-8:] != '.min.css': css = css_compiler.compile_string(css) if not isinstance(css, six.text_type): css = css.decode('utf8') cooked_css += u'\n/* Resource: {0} */\n{1}\n'.format( css_resource, css ) else: cooked_css +=\ u'\n/* Could not find resource: {0} */\n\n'.format( css_resource ) logger.warn('Could not find resource: %s', css_resource) if not resource.js or not js_path: continue js_url = siteUrl + '/' + resource.js response = subrequest(js_url) if response.status == 200: js = response.getBody() try: logger.info('Cooking js %s', resource.js) if not isinstance(js, six.text_type): js = js.decode('utf8') cooked_js += '\n/* resource: {0} */\n{1}'.format( resource.js, js if '.min.js' == resource.js[-7:] else es5.minify_print(js) ) except SyntaxError: cooked_js +=\ '\n/* Resource (error cooking): {0} */\n{1}'.format( resource.js, js ) logger.warn('Error cooking resource: %s', resource.js) else: logger.warn('Could not find resource: %s', resource.js) cooked_js += '\n/* Could not find resource: {0} */\n\n'.format( js_url ) cooked_js += REQUIREJS_RESET_POSTFIX persistent_directory = getUtility(IResourceDirectory, name="persistent") if OVERRIDE_RESOURCE_DIRECTORY_NAME not in persistent_directory: persistent_directory.makeDirectory(OVERRIDE_RESOURCE_DIRECTORY_NAME) container = persistent_directory[OVERRIDE_RESOURCE_DIRECTORY_NAME] def _write_resource(resource_path, cooked_string): if not resource_path: return resource_path = resource_path.split('++plone++')[-1] resource_name, resource_filepath = resource_path.split('/', 1) if resource_name not in container: container.makeDirectory(resource_name) if not isinstance(cooked_string, six.binary_type): # handle Error of OFS.Image # noqa: E501 cooked_string = cooked_string.encode('ascii', errors='ignore') try: folder = container[resource_name] fi = BytesIO(cooked_string) folder.writeFile(resource_filepath, fi) logger.info('Writing cooked resource: %s', resource_path) except NotFound: logger.warn('Error writing cooked resource: %s', resource_path) _write_resource(js_path, cooked_js) _write_resource(css_path, cooked_css) bundle.last_compilation = datetime.now() # refresh production meta bundles combine_bundles(context) # Disable CSRF protection on this request alsoProvides(request, IDisableCSRFProtection)
def MainHandler(request, data, usuario): try: #incluye los parametros del get no va a ignorar el lenguaje (solo se usa para memcache) var_full_path = request.get_full_path() llaveParaMemcache = var_full_path if users.is_current_user_admin(): llaveParaMemcache = PREFIJO_MEMCACHE_ADMIN+llaveParaMemcache #incluye hasta la ? o # y va a ignorar el lenguaje var_path = request.path if request.method == 'GET': leng = re.findall('^(\/leng-)([a-zA-Z]{3})(\/)', var_path) if (len(leng) > 0): leng = leng[0][1].lower() var_path = var_path[9:] data = data[9:] else: leng = LENGUAJE_PRED puntoExtension = data.rfind('.') extension = data[puntoExtension:] mime = 'text/html' esBinario = False for tipo in LISTA_PATRONES: if (tipo['patron'].match(extension)): mime = tipo['mime'] if tipo['bin']: esBinario = True break if not esBinario: mime = mime+'; charset=utf-8' if False:#Usar cache anterior = memcache.get(llaveParaMemcache) if (anterior): return HttpResponse(anterior, content_type=mime) #Se lee el template para saber cuales ids se deben buscar de la base de datos if (not esBinario): llavesEntidades = [] identificadores = [] module = __import__('models') #Buscar un template valido para la url ruta = data varRutaExiste = 0 #0. Primero se mira si tal vez existe la ruta exacta varRutaExiste = rutaExiste(ruta) if (varRutaExiste == 0): #1. Se le quita la extensión if (puntoExtension >= 0): ruta = ruta[:puntoExtension] #2. Se itera por los diferentes slash y se mira si existe template ultimoIndice = len(ruta) while True: rutaParcial = ruta[:ultimoIndice]+'.html' ultimoIndice = ruta.rfind('/', 0, ultimoIndice) varRutaExiste = rutaExiste(rutaParcial) if (not (varRutaExiste == 0) or ultimoIndice <= 0): break else: rutaParcial = ruta #Si no encontró se queda con el index if (varRutaExiste == 0 and ultimoIndice <= 0): data = 'index.html' else: data = rutaParcial todo = procesarTemplate(data, var_path) for parte in todo['nodos']: class_ = getattr(module, parte['tipo']) identificadores.append(ndb.Key(class_, parte['id'])) llavesEntidades = todo['busquedas'] #Se leen las entidades list_of_entities = ndb.get_multi(identificadores) dicci = {} for entidad in list_of_entities: if entidad is not None: nombreClase = entidad.__class__.__name__ if not dicci.has_key(nombreClase): dicci[nombreClase] = {} dicci[nombreClase][entidad.key.id()] = entidad.to_dict() entidades = {} cursores = {} data_q = request.GET.get('data-q', None) data_next = request.GET.get('data-next', None) id_pagina = request.GET.get('pg', None) for llaveEntidad in llavesEntidades: objeto_busqueda = simplejson.loads(llaveEntidad) if (data_q == llaveEntidad and not data_next == None): objeto_busqueda['next'] = data_next objeto = comun.buscarGQL(objeto_busqueda) entidades[llaveEntidad] = comun.to_dict(objeto['datos']) if (objeto.has_key('next')): cursores[llaveEntidad] = objeto['next'] if (id_pagina is not None): try: detalle = buscarPagina(request, usuario, True) try: detalle['tit'] = simplejson.loads(detalle['tit']) except: detalle['tit'] = 'pais.tv' try: detalle['desc'] = simplejson.loads(detalle['desc']) except: detalle['desc'] = 'pais.tv' try: detalle['q'] = simplejson.loads(detalle['q']) except: detalle['q'] = '' try: detalle['img'] = simplejson.loads(detalle['img']) except: detalle['img'] = 'pais.tv' except: detalle = {'tit': 'pais.tv','desc': 'pais.tv','img': 'pais.tv',} else: detalle = None context = { 'admin':users.is_current_user_admin(), 'path':var_path, 'detalle': detalle, 'raiz': StorageHandler.darRaizStorage(), 'qparams': request.GET,#Aca se propagan los query params para que esten disponibles en el template } respuesta = direct_to_template(request, data, context, mime) if (extension.startswith(".scss")): for llave in request.GET.keys(): valor = request.GET.get(llave) respuesta.content = comun.remplazar(respuesta.content, llave, valor) respuesta.content = Compiler().compile_string(respuesta.content) #Siempre se codifica utf-8 respuesta.content = comun.siempreUtf8(respuesta.content) else: respuesta = StorageHandler.read_file(data) if (respuesta.status_code == 204): #significa que no existe return respuesta memcache.set(llaveParaMemcache, respuesta.content) agregarRutaParaMemcache(request.path, llaveParaMemcache) if (not esBinario): respuesta.content = comun.remplazar(respuesta.content, '__USER__', generarVariablesUsuario(var_full_path, leng), True) return respuesta elif request.method == 'DELETE': #Borra rutas específicas de memcache response = HttpResponse("", content_type='application/json') borrarRutasDeMemcache(request.path, llaveParaMemcache) response.write(simplejson.dumps({'error':0})) except Exception, e: exc_type, exc_value, exc_traceback = sys.exc_info() response = HttpResponse("", content_type='application/json', status=500) response.write(simplejson.dumps({'error':1, 'msg': 'Error de servidor: '+repr(traceback.format_tb(exc_traceback))+'->'+str(e)}))
from app_env import config import scss.config from scss import Compiler from os import path import os current_folder = path.dirname(__file__) compiler = Compiler(search_path=[current_folder]) def generate_sheet(origin, target): with open(origin, 'r') as stylesheet: result = compiler.compile_string(stylesheet.read()) with open(target, 'w') as output: output.write(result) def update_style(): if not path.exists("dist/static/css"): os.makedirs("dist/static/css") generate_sheet('index.scss', 'dist/static/css/index.css') generate_sheet('pico_cart_style.scss', 'dist/static/css/pico8.css')