Exemplo n.º 1
0
def compileHandlebar(path, appName, paramPath=""):
    compiler = Compiler()

    source = ""
    templatePath = os.path.join(path, "templates/" + appName + "/src/config.py.hbs")

    with open(templatePath, 'r') as myfile:
        data=myfile.read()
        template = compiler.compile(data)

    if paramPath == "":
       paramPath = os.path.join(path, "parameters.json")



    with open(paramPath, 'r') as parameterJson:
        #check if template is filled with actual data
        content = json.load(parameterJson)
        for key,value in content.items():
            for kkey, vvalue in value.items():
                if "<" in vvalue or ">" in vvalue:
                    raise ValueError ("The chosen param file does not contain all needed values.")

        appContent = content[appName]

    output = template(appContent)

    return output.lower()
Exemplo n.º 2
0
def blog_post(request, post_id):
    context = dict()

    r = requests.get('{0}/posts?api_key={1}&id={2}'.format(settings.TUMBLR_API_URL,
            settings.TUMBLR_API_KEY, post_id))

    if r.status_code == 200:
        post_response = r.json.get('response', {})
        posts = post_response.get('posts', [])

        if posts:
            post = posts[0]
            f_date = datetime.strptime(post['date'], '%Y-%m-%d %H:%M:%S %Z')
            post['formated_date'] = f_date.strftime('%B %d, %Y')

            if settings.DISQUS_INTEGRATION_ENABLED:
                post['disqus_enabled'] = True

            path_to_here = os.path.abspath(os.path.dirname(__file__))
            f = open('{0}/static/templates/blog-post-{1}.html'.format(path_to_here, post['type']), 'r')
            f_data = f.read()
            f.close()

            compiler = Compiler()
            template = compiler.compile(unicode(f_data))
            context['post_data'] = template(post)
            context['post_title'] = post.get('title', '')

    return render(request, 'blog-post.html', context)
Exemplo n.º 3
0
def blog_post(request, post_id):
    context = dict()

    r = requests.get("{0}/posts?api_key={1}&id={2}".format(settings.TUMBLR_API_URL, settings.TUMBLR_API_KEY, post_id))

    if r.status_code == 200:
        post_response = r.json.get("response", {})
        posts = post_response.get("posts", [])

        if posts:
            post = posts[0]
            f_date = datetime.strptime(post["date"], "%Y-%m-%d %H:%M:%S %Z")
            post["formated_date"] = f_date.strftime("%B %d, %Y")

            path_to_here = os.path.abspath(os.path.dirname(__file__))
            f = open("{0}/static/templates/blog-post-{1}.html".format(path_to_here, post["type"]), "r")
            f_data = f.read()
            f.close()

            compiler = Compiler()
            template = compiler.compile(unicode(f_data))
            context["post_data"] = template(post)
            context["post_title"] = post["title"]

    return render(request, "blog-post.html", context)
Exemplo n.º 4
0
def generate_page(data):

    compiler = Compiler()
    source = u"{{>header}}{{#list programs}}{{fileName}}{{lineCount}}{{/list}}"
    template = compiler.compile(source)

    def _list(this, options, items):
        result = [u"<ul>"]
        for thing in items:
            result.append(u"<li>")
            result.append(u'Source File:<a href="' + thing["fileName"] + '">' + thing["fileName"] + "</a>")
            result.append(u" - " + str(thing["lineCount"]) + " lines without comments or blank lines")
            result.append(u"</li>")
        result.append(u"</ul>")
        return result

    helpers = {"list": _list}

    # Add partials
    header = compiler.compile(u"<h1>Programs</h1>")
    partials = {"header": header}

    output = template(data, helpers=helpers, partials=partials)

    open("index.html", "wb").write(output)
Exemplo n.º 5
0
def compileHandlebar(path, appName, paramPath=""):
    compiler = Compiler()

    source = ""
    templatePath = os.path.join(path,
                                "templates/" + appName + "/src/config.py.hbs")

    with open(templatePath, 'r') as myfile:
        data = myfile.read()
        template = compiler.compile(data)

    if paramPath == "":
        paramPath = os.path.join(path, "parameters.json")

    with open(paramPath, 'r') as parameterJson:
        #check if template is filled with actual data
        content = json.load(parameterJson)
        for key, value in content.items():
            for kkey, vvalue in value.items():
                if "<" in vvalue or ">" in vvalue:
                    raise ValueError(
                        "The chosen param file does not contain all needed values."
                    )

        appContent = content[appName]

    output = template(appContent)

    return output.lower()
Exemplo n.º 6
0
    def search_string(self):
        """"
        Returns the JSON string that LendingClub expects for it's search
        """
        self.__normalize()

        # Get the template
        tmpl_source = str(open(self.tmpl_file).read())

        # Process template
        compiler = Compiler()
        template = compiler.compile(tmpl_source)
        out = template(self)
        if not out:
            return False
        out = ''.join(out)

        #
        # Cleanup output and remove all extra space
        #

        # remove extra spaces
        out = re.sub('\n', '', out)
        out = re.sub('\s{3,}', ' ', out)

        # Remove hanging commas i.e: [1, 2,]
        out = re.sub(',\s*([}\\]])', '\\1', out)

        # Space between brackets i.e: ],  [
        out = re.sub('([{\\[}\\]])(,?)\s*([{\\[}\\]])', '\\1\\2\\3', out)

        # Cleanup spaces around [, {, }, ], : and , characters
        out = re.sub('\s*([{\\[\\]}:,])\s*', '\\1', out)

        return out
Exemplo n.º 7
0
def blog_post(request, post_id):
    context = dict()

    r = requests.get('{0}/posts?api_key={1}&id={2}'.format(
        settings.TUMBLR_API_URL, settings.TUMBLR_API_KEY, post_id))

    if r.status_code == 200:
        post_response = r.json.get('response', {})
        posts = post_response.get('posts', [])

        if posts:
            post = posts[0]
            f_date = datetime.strptime(post['date'], '%Y-%m-%d %H:%M:%S %Z')
            post['formated_date'] = f_date.strftime('%B %d, %Y')

            if settings.DISQUS_INTEGRATION_ENABLED:
                post['disqus_enabled'] = True

            path = '{0}/static/templates/blog-post-{1}.html'.format(
                os.path.join(os.path.dirname(__file__), '..'), post['type'])
            with open(path, 'r') as f:
                f_data = f.read()

            compiler = Compiler()
            template = compiler.compile(unicode(f_data))
            context['post_data'] = template(post)
            context['post_title'] = post.get('title', None)

    return render(request, 'blog-post.html', context)
Exemplo n.º 8
0
    def test_smoke(self):
        compiler = Compiler()

        def _list(this, options, items):
            result = ["<ul>"]
            for thing in items:
                result.append("<li>")
                result.extend(options["fn"](thing))
                result.append("</li>")
            result.append("</ul>")
            return result

        source = u"{{#list people}}{{firstName}} {{lastName}}{{/list}}"
        template = compiler.compile(source)
        context = {
            "people": [
                {"firstName": "Yehuda", "lastName": "Katz"},
                {"firstName": "Carl", "lastName": "Lerche"},
                {"firstName": "Alan", "lastName": "Johnson"},
            ]
        }
        rendered = template(context, helpers={u"list": _list})
        self.assertEqual(
            u"<ul><li>Yehuda Katz</li><li>Carl Lerche</li>" "<li>Alan Johnson</li></ul>", str_class(rendered)
        )
Exemplo n.º 9
0
    def test_smoke(self):
        compiler = Compiler()

        def _list(this, options, items):
            result = ['<ul>']
            for thing in items:
                result.append('<li>')
                result.extend(options['fn'](thing))
                result.append('</li>')
            result.append('</ul>')
            return result

        source = u"{{#list people}}{{firstName}} {{lastName}}{{/list}}"
        template = compiler.compile(source)
        context = {
            'people': [{
                'firstName': "Yehuda",
                'lastName': "Katz"
            }, {
                'firstName': "Carl",
                'lastName': "Lerche"
            }, {
                'firstName': "Alan",
                'lastName': "Johnson"
            }]
        }
        rendered = template(context, helpers={u'list': _list})
        self.assertEqual(
            u"<ul><li>Yehuda Katz</li><li>Carl Lerche</li>"\
            "<li>Alan Johnson</li></ul>",
            str_class(rendered))
Exemplo n.º 10
0
def _compile_template(swagger_template_file, template_params):
    compiler = Compiler()
    with codecs.open(swagger_template_file, 'r', 'utf-8') as f:
        template_file = f.read()
    template = compiler.compile(template_file)
    filled_template = template(template_params)
    return filled_template
Exemplo n.º 11
0
def handlebars_dynamic_load(package, name):
    """ Dynamically compile a Handlebars template.

    NOTE: This will do nothing in production mode!
    """

    if not App.is_dev_server:
        return None

    combined_name = "%s_%s" % (package, name)
    if combined_name in handlebars_partials:
        handlebars_partials[combined_name]

    logging.info("Dynamically loading %s-package/%s.handlebars." %
                 (package, name))
    file_name = "clienttemplates/%s-package/%s.handlebars" % (package, name)

    in_file = open(file_name, 'r')
    source = unicode(in_file.read())
    # HACK: Pybars doesn't handle {{else}} for some reason
    source = source.replace("{{else}}", "{{^}}")

    matches = re.search('{{>[\s]*([\w\-_]+)[\s]*}}', source)
    if matches:
        for partial in matches.groups():
            (partial_package, partial_name) = partial.split("_")
            handlebars_dynamic_load(partial_package, partial_name)

    compiler = Compiler()
    function = compiler.compile(source)
    handlebars_partials[combined_name] = function

    return function
Exemplo n.º 12
0
def handlebars_dynamic_load(package, name):
    """ Dynamically compile a Handlebars template.

    NOTE: This will do nothing in production mode!
    """

    if not App.is_dev_server:
        return None

    combined_name = "%s_%s" % (package, name)
    if combined_name in handlebars_partials:
        handlebars_partials[combined_name]

    logging.info("Dynamically loading %s-package/%s.handlebars."
                  % (package, name))
    file_name = "clienttemplates/%s-package/%s.handlebars" % (package, name)

    in_file = open(file_name, 'r')
    source = unicode(in_file.read())
    # HACK: Pybars doesn't handle {{else}} for some reason
    source = source.replace("{{else}}", "{{^}}")

    matches = re.search('{{>[\s]*([\w\-_]+)[\s]*}}', source)
    if matches:
        for partial in matches.groups():
            (partial_package, partial_name) = partial.split("_")
            handlebars_dynamic_load(partial_package, partial_name)

    compiler = Compiler()
    function = compiler.compile(source)
    handlebars_partials[combined_name] = function

    return function
Exemplo n.º 13
0
def create_and_save_doc(document_data, index_html, output_pdf):
    """
    Creates a PDF invoice by filling an HTML template with a YML file.

    Parameters
    ----------
    document_data : dict
        Data to use for filling the HTML template.
    index_html : str
        Absolute path to html template file.
    output_pdf : str
        Name of the output PDF file.

    Returns
    -------
    Saves the output PDF to output/ directory
    """
    pos_number = 1
    document_data['totals'] = {'net': 0, 'gross': 0, 'tax': 0}
    for pos in document_data['positions']:
        if not 'tax_rate' in pos:
            pos['tax_rate'] = document_data['tax_rate']

        pos['pos_number'] = pos_number
        pos['total_net_price'] = pos['net_price'] * pos['amount']
        pos['total_tax'] = \
            pos['total_net_price'] * (pos['tax_rate'] / float(100))
        pos['total_gross_price'] = pos['total_net_price'] + pos['total_tax']

        document_data['totals']['net'] += pos['total_net_price']
        document_data['totals']['gross'] += pos['total_gross_price']
        document_data['totals']['tax'] += pos['total_tax']

        pos['amount'] = locale.format_string("%.2f", pos['amount'])
        pos['tax_rate'] = locale.format_string("%.2f", pos['tax_rate'])
        pos['net_price'] = locale.format_string("%.2f", pos['net_price'])
        pos['total_net_price'] = \
            locale.format_string("%.2f", pos['total_net_price'])
        pos['text'] = pos['text'].replace('\n', '<br>')

        pos_number += 1

    document_data['totals']['net'] = \
        locale.format_string("%.2f", document_data['totals']['net'])
    document_data['totals']['gross'] = \
        locale.format_string("%.2f", document_data['totals']['gross'])
    document_data['totals']['tax'] = \
        locale.format_string("%.2f", document_data['totals']['tax'])

    with codecs.open(index_html, encoding="utf-8") as index_file:
        html_text = index_file.read()

        compiler = Compiler()
        template = compiler.compile(html_text)

        html_text = template(document_data)

        weasytemplate = HTML(string=html_text)
        weasytemplate.write_pdf(os.path.join('/app', 'output', output_pdf))
    return
Exemplo n.º 14
0
    def search_string(self):
        """"
        Returns the JSON string that LendingClub expects for it's search
        """
        self.__normalize()

        # Get the template
        tmpl_source = unicode(open(self.tmpl_file).read())

        # Process template
        compiler = Compiler()
        template = compiler.compile(tmpl_source)
        out = template(self)
        if not out:
            return False
        out = ''.join(out)

        #
        # Cleanup output and remove all extra space
        #

        # remove extra spaces
        out = re.sub('\n', '', out)
        out = re.sub('\s{3,}', ' ', out)

        # Remove hanging commas i.e: [1, 2,]
        out = re.sub(',\s*([}\\]])', '\\1', out)

        # Space between brackets i.e: ],  [
        out = re.sub('([{\\[}\\]])(,?)\s*([{\\[}\\]])', '\\1\\2\\3', out)

        # Cleanup spaces around [, {, }, ], : and , characters
        out = re.sub('\s*([{\\[\\]}:,])\s*', '\\1', out)

        return out
Exemplo n.º 15
0
def blog_post(request, post_id):
    context = dict()

    r = requests.get('{0}/posts?api_key={1}&id={2}'.format(
        settings.TUMBLR_API_URL, settings.TUMBLR_API_KEY, post_id))

    if r.status_code == 200:
        post_response = r.json.get('response', {})
        posts = post_response.get('posts', [])

        if posts:
            post = posts[0]
            f_date = datetime.strptime(post['date'], '%Y-%m-%d %H:%M:%S %Z')
            post['formated_date'] = f_date.strftime('%B %d, %Y')

            path_to_here = os.path.abspath(os.path.dirname(__file__))
            f = open(
                '{0}/static/templates/blog-post-{1}.html'.format(
                    path_to_here, post['type']), 'r')
            f_data = f.read()
            f.close()

            compiler = Compiler()
            template = compiler.compile(unicode(f_data))
            context['post_data'] = template(post)
            context['post_title'] = post['title']

    return render(request, 'blog-post.html', context)
Exemplo n.º 16
0
def blog_post(request, post_id):
    if settings.BLOG_PLATFORM == 'tumblr':
        r = requests.get('{0}/posts?api_key={1}&id={2}'.format(
            settings.TUMBLR_API_URL, settings.TUMBLR_API_KEY, post_id))

        if r.status_code == 200:
            post_response = r.json().get('response', {})
            posts = post_response.get('posts', [])

            if posts:
                post = posts[0]
                f_date = datetime.strptime(post['date'],
                                           '%Y-%m-%d %H:%M:%S %Z')
                post['formated_date'] = f_date.strftime('%B %d, %Y')

    elif settings.BLOG_PLATFORM == 'wordpress':
        r = requests.get('{0}/posts/{1}'.format(settings.WORDPRESS_API_URL,
                                                post_id))
        if r.status_code == 200:
            # Get Wordpress response into the same format as Tumblr so we can
            # reuse Handlebars template
            post = r.json()
            convertWordpressResponse(post)

    # At this point we should have a post dict from either Tumblr or Wordpress
    post['disqus_enabled'] = settings.DISQUS_INTEGRATION_ENABLED
    if settings.SHARETHIS_PUBLISHER_KEY:
        post['sharethis_enabled'] = True

    path = '{0}/static/templates/blog-post-{1}.html'.format(
        os.path.join(os.path.dirname(__file__), '..'), post['type'])
    with open(path, 'r') as f:
        f_data = f.read()

    compiler = Compiler()
    template = compiler.compile(unicode(f_data))

    context = dict()
    context['post_data'] = template(post)

    alt_title = ''
    if (post['type'] == 'photo' or post['type'] == 'video'):
        alt_title = '{0}: {1}'.format(post['type'].capitalize(),
                                      post['caption'][3:-4])
    elif (post['type'] == 'quote'):
        alt_title = '{0}: {1}'.format(post['type'].capitalize(), post['text'])
    elif (post['type'] == 'audio'):
        alt_title = '{0}: {1} - {2}'.format(post['type'].capitalize(),
                                            post['artist'], post['track_name'])

    context['post_title'] = post.get('title', unescape(alt_title))

    if post['type'] == 'text' and post['body']:
        context['meta_description'] = strip_tags(post['body'])[:150]

    if post['tags']:
        context['meta_keywords'] = ', '.join(post['tags'])

    return render(request, 'blog-post.html', context)
Exemplo n.º 17
0
def applySwap(KeyPairs, File):
	Template_File = open(File, 'r')
	with Template_File:
		source = Template_File.read()
	compiler = Compiler()
	template = compiler.compile(source)
	Swapped = template(KeyPairs)
	return Swapped
    def test_process_templates(self):
        config = "{{#if A}}{{B}}{{/if}}"
        values = {"A": "true", "B": "XYZ"}

        compiler = Compiler()
        template = compiler.compile(config)

        assert "XYZ" == template(values)
Exemplo n.º 19
0
def analyseAndRender(dataLocation, templateLocation, optionsLocation=""):
    global df

    if optionsLocation != "":
        with open(optionsLocation) as json_file:
            options = json.load(json_file)

    # For local csv

    if ".csv" in dataLocation and "https://docs.google.com" not in dataLocation:
        df = _makeDataFrame(dataLocation)

    # For google sheets as csv

    elif "https://docs.google.com" in dataLocation:
        print("It's a google sheet")

    # If its already a dataframe

    else:
        df = dataLocation

    with io.open(templateLocation, 'r', encoding='utf-8') as tempSource:
        compiler = Compiler()
        template = compiler.compile(tempSource.read())

    helpers = {
        "getCellByNumber": getCellByNumber,
        "getCellByLabel": getCellByLabel,
        "checkDifferenceBetweenValues": checkDifferenceBetweenValues,
        "checkAgainstRollingMean": checkAgainstRollingMean,
        "getRollingMean": getRollingMean,
        "getDifference": getDifference,
        "sortAscending": sortAscending,
        "sortDescending": sortDescending,
        "getRankedItemDescending": getRankedItemDescending,
        "sumAcrossAllCols": sumAcrossAllCols,
        "totalSumOfAllCols": totalSumOfAllCols,
        "formatNumber": formatNumber,
        "groupBy": groupBy,
        "groupByTime": groupByTime,
        "filterBy": filterBy,
        "summariseCol": summariseCol,
        "checkDifferenceBetweenResults": checkDifferenceBetweenResults,
        "uniqueValues": uniqueValues,
        "summariseColByTimePeriod": summariseColByTimePeriod,
        "makeList": makeList
    }

    output = template(df, helpers=helpers)

    # String replacements
    if optionsLocation != "":
        if 'replacements' in options:
            output = _replaceStrings(options['replacements'], output)

    # print(output.encode('utf-8'))
    return output
Exemplo n.º 20
0
def compile_template(template_dict, template_name):
    """Compile template."""
    compiler = Compiler()
    partials = {
        name: compiler.compile(template)
        for name, template in template_dict.items() if name != template_name
    }
    compiled = compiler.compile(template_dict[template_name])
    return compiled, partials
Exemplo n.º 21
0
def timeline_template():
    """Returns a compiled handlebars template (as a function),
    which can be called on an input data object to produce HTML
    """
    compiler = Compiler()
    with open("timeline_view.handlebars", "r", encoding="utf8") as f:
        raw_template = f.read()
    template = compiler.compile(raw_template)
    return template
Exemplo n.º 22
0
def blog_post(request, post_id):
    if settings.BLOG_PLATFORM == 'tumblr':
        r = requests.get('{0}/posts?api_key={1}&id={2}'.format(
            settings.TUMBLR_API_URL, settings.TUMBLR_API_KEY, post_id))

        if r.status_code == 200:
            post_response = r.json().get('response', {})
            posts = post_response.get('posts', [])

            if posts:
                post = posts[0]
                f_date = datetime.strptime(post['date'], '%Y-%m-%d %H:%M:%S %Z')
                post['formated_date'] = f_date.strftime('%B %d, %Y')

    elif settings.BLOG_PLATFORM == 'wordpress':
        r = requests.get('{0}/posts/{1}'.format(
            settings.WORDPRESS_API_URL, post_id))
        if r.status_code == 200:
            # Get Wordpress response into the same format as Tumblr so we can
            # reuse Handlebars template
            post = r.json()
            convertWordpressResponse(post)

    # At this point we should have a post dict from either Tumblr or Wordpress
    post['disqus_enabled'] = settings.DISQUS_INTEGRATION_ENABLED
    if settings.SHARETHIS_PUBLISHER_KEY:
        post['sharethis_enabled'] = True

    path = '{0}/static/templates/blog-post-{1}.html'.format(
        os.path.join(os.path.dirname(__file__), '..'), post['type'])
    with open(path, 'r') as f:
        f_data = f.read()

    compiler = Compiler()
    template = compiler.compile(unicode(f_data))

    context = dict()
    context['post_data'] = template(post)

    alt_title = ''
    if (post['type'] == 'photo' or post['type'] == 'video'):
        alt_title = '{0}: {1}'.format(post['type'].capitalize(), post['caption'][3:-4])
    elif (post['type'] == 'quote'):
        alt_title = '{0}: {1}'.format(post['type'].capitalize(), post['text'])
    elif (post['type'] == 'audio'):
        alt_title = '{0}: {1} - {2}'.format(post['type'].capitalize(), post['artist'], post['track_name'])

    context['post_title'] = post.get('title', unescape(alt_title))

    if post['type'] == 'text' and post['body']:
        context['meta_description'] = strip_tags(post['body'])[:150]

    if post['tags']:
        context['meta_keywords'] = ', '.join(post['tags'])

    return render(request, 'blog-post.html', context)
Exemplo n.º 23
0
def render_from_file(template_file, variables):
    """Render from template string with interpolated variables."""
    compiler = Compiler()
    partials = {
        f.stem: compiler.compile(f.read_text())
        for f in template_file.parent.glob("*.hbs")
    }
    source = template_file.read_text()
    template = compiler.compile(source, path=str(template_file.parent))
    return template(variables, partials=partials)
Exemplo n.º 24
0
    def render_content(self, data, content):
        bars = Compiler()
        content = bars.compile(self._clean_content(content))

        # need to render partials
        partials = {}
        for key, val in self._raw_partials.items():
            partials[key] = bars.compile(self._clean_content(val))

        return content(data, helpers=self._meta.helpers, partials=partials)
Exemplo n.º 25
0
    def render_content(self, data, content):
        bars = Compiler()
        content = bars.compile(self._clean_content(content))

        # need to render partials
        partials = {}
        for key, val in self._raw_partials.items():
            partials[key] = bars.compile(self._clean_content(val))

        return content(data, helpers=self._meta.helpers, partials=partials)
Exemplo n.º 26
0
def render(source, context, helpers=None, partials=None, knownHelpers=None, knownHelpersOnly=False):
    compiler = Compiler()
    template = compiler.compile(source)
    # For real use, partials is a dict of compiled templates; but for testing
    # we compile just-in-time.
    if not partials:
        real_partials = None
    else:
        real_partials = dict((key, compiler.compile(value)) for key, value in list(partials.items()))
    return str_class(template(context, helpers=helpers, partials=real_partials))
Exemplo n.º 27
0
    def output_pdf(self, pdf_name):
        self.prepare_invoice_items()
        with codecs.open(self.template, encoding="utf-8") as index_file:
            html_text = index_file.read()
            compiler = Compiler()
            template = compiler.compile(html_text)
            html_text = template(self.document_data)

            weasytemplate = HTML(string=html_text,
                                 base_url="template/index.html")
            weasytemplate.write_pdf(pdf_name)
Exemplo n.º 28
0
 def map_template(self, *args):
     source = self.get_data(args[0]['id'])
     # print(source)
     abs_file_path = os.path.join(os.path.dirname(__file__),
                                  '../../templates/report.html')
     with open(abs_file_path) as data_file:
         data = data_file.read()
     compiler = Compiler()
     template = compiler.compile(data)
     output = template(source)
     return output
 def __init__(self):
     self.__compiler = Compiler()
     self.__header_template = self.__compiler.compile(
         TemplateGenerator.HEADER_TEMPLATE)
     self.__enum_template = self.__compiler.compile(
         TemplateGenerator.ENUM_TEMPLATE)
     self.__stringsdict_template = self.__compiler.compile(
         TemplateGenerator.STRINGSDICT_TEMPLATE)
     self.__plurals_template = self.__compiler.compile(
         TemplateGenerator.PLURAL_TEMPLATE)
     self.__variables_template = self.__compiler.compile(
         TemplateGenerator.VARIABLES_TEMPLATE)
Exemplo n.º 30
0
def render(source, context, helpers=None, partials=None, knownHelpers=None,
           knownHelpersOnly=False):
    compiler = Compiler()
    template = compiler.compile(source)
    # For real use, partials is a dict of compiled templates; but for testing
    # we compile just-in-time.
    if not partials:
        real_partials = None
    else:
        real_partials = dict((key, compiler.compile(value))
            for key, value in list(partials.items()))
    return str_class(template(context, helpers=helpers, partials=real_partials))
Exemplo n.º 31
0
	def generate(self, data, templateLocation):
		compiler = Compiler()
		
		source = open(templateLocation).read().decode('utf-8')
		template = compiler.compile(source)

		output = template(data)
		parser = etree.XMLParser(remove_blank_text=True)
		root = etree.XML(output, parser)
		xml_output = etree.tostring(root, pretty_print = True, xml_declaration = True, encoding='UTF-8')
		artifactObj = Artifact(xml_output)
		return artifactObj
Exemplo n.º 32
0
    def generate(self, data, templateLocation):
        compiler = Compiler()

        source = open(templateLocation).read().decode('utf-8')
        template = compiler.compile(source)

        output = template(data)
        parser = etree.XMLParser(remove_blank_text=True)
        root = etree.XML(output, parser)
        xml_output = etree.tostring(root,
                                    pretty_print=True,
                                    xml_declaration=True,
                                    encoding='UTF-8')
        artifactObj = Artifact(xml_output)
        return artifactObj
Exemplo n.º 33
0
    def render_post_json(posts,
                         images_per_row=2,
                         max_width=512,
                         template_file='post.hb'):

        fb_posts = []
        post_idx = 0
        for post_id, created_time, message, images, locations, places, tags in posts:
            post_idx = post_idx + 1
            post_images = []
            for i in range(0, len(images)):
                image = images[i]
                if image.get('src'):
                    image_url = image['src']
                    image_url_hash = hashlib.md5(
                        image_url.encode()).hexdigest()
                    GhostImporter._resize_image(image)
                    post_image = {
                        'filename': image_url_hash,
                        'width': image['width'],
                        'height': image['height'],
                        'src': image_url,
                        'row': int(i / images_per_row)
                    }
                    post_images.append(post_image)

            message_lines = [
                m for m in message.replace('"', '').splitlines() if m.strip()
            ] if message else []

            fb_post = {
                'date': re.sub(" .*", "", created_time),
                'message': message_lines,
                'has_image': len(post_images) > 0,
                'has_locations': locations and len(locations) > 0,
                'gallery_idx': post_idx,
                'images': post_images,
                'locations': ",".join(locations) if locations else None,
                'places': places,
                'tags': [("with " + ", ".join(tags))] if tags else None
            }
            fb_posts.append(fb_post)

        compiler = Compiler()
        template_source = open(template_file, 'r').read()
        template = compiler.compile(template_source)
        output = template({'fb_posts': fb_posts})
        return output
Exemplo n.º 34
0
def render(input_file, value_file, output_file, enable_env):
    with open(input_file, encoding="utf-8") as inputF:
        source = inputF.read()

    with open(value_file) as valueF:
        values = json.load(valueF)
    if enable_env:
        for k, v in os.environ.iteritems():
            values[k] = v

    compiler = Compiler()
    template = compiler.compile(source)
    output = template(values, helpers={"eq": eq})

    with open(output_file, "w+") as outputF:
        outputF.write(output)
Exemplo n.º 35
0
def _create_template(diff):
    diff = diff._asdict()
    template_source = _read_template_file('diff_email.hbs')
    diff['css'] = _read_template_file('basic.css')
    template = Compiler().compile(template_source)(diff)
    email_body = inline_styler.inline_css(template)
    return email_body
Exemplo n.º 36
0
    def __get_compiled_template(self, template_name):
        template_path = self.__get_template_path(template_name)
        try:
            from pybars import Compiler
        except ImportError as e:
            Compiler = None
            logger.debug(str(e))
            logger.warning(
                "Unable to load pybars; install pybars3 to load profile directly from the current session "
            )

        with open(template_path, "r") as file_with_template:
            source = file_with_template.read()
        compiler = Compiler()
        template = compiler.compile(source)
        return template
Exemplo n.º 37
0
    def test_compile_with_path(self):
        template = u"Hi {{name}}!"
        context = {
            'name': 'Ahmed'
        }
        result = u"Hi Ahmed!"
        path = '/project/widgets/templates'

        compiler = Compiler()

        # compile and check that speficified path is used
        self.assertEqual(result, compiler.compile(template, path=path)(context))
        self.assertTrue(sys.modules.get('pybars._templates._project_widgets_templates') is not None)

        # recompile and check that a new path is used
        self.assertEqual(result, compiler.compile(template, path=path)(context))
        self.assertTrue(sys.modules.get('pybars._templates._project_widgets_templates_1') is not None)
Exemplo n.º 38
0
    def get_hbs(self, source, obj):
        compiler = Compiler()
        base_template = compiler.compile(
            u'<!DOCTYPE html><html lang="es">{{> head}}<body><div>{{> nav}}<div>{{> content}}</div></div>{{> footer}}</body></html>'
        )
        head = compiler.compile(
            get_template("_head_organizations.html").render(obj))
        footer = compiler.compile(get_template("_footer.html").render({}))
        content_template = compiler.compile(source)
        nav = compiler.compile(get_template("_navbar.html").render(obj))

        def _proposal_card_renderer(proposal, *args, **kwargs):
            context = copy.copy(obj)
            request = context['view'].request
            context['proposal'] = proposal.get('this')
            return get_template(
                "popular_proposal/popular_proposal_card.html").render(
                    context, request)

        everything = base_template(
            obj,
            partials={
                "content": content_template,
                "head": head,
                "nav": nav,
                "footer": footer
            },
            helpers={"proposal_card_renderer": _proposal_card_renderer})
        return everything
Exemplo n.º 39
0
    def _initTemplate(self):

        #
        #  Load the template
        #
        self.config.logger.info("Reading template file 'email_html_template.mustache'...")
        f = codecs.open("email_html_template.mustache", encoding='utf-8', mode='rb')
        strtempl = f.read()
        f.close()

        #
        #  Compile the template
        #
        from pybars import Compiler
        compiler = Compiler()
        self.html_full_results_template = compiler.compile(strtempl)

        self.email_html_template = compiler.compile(strtempl)
Exemplo n.º 40
0
 def __init__(self, source):
   self.compiler = Compiler()
   self.source = source
   self.compiler.register_helper(u'if_eq', self.helper_if_eq)
   self.compiler.register_helper(u'unless_eq', self.helper_unless_eq)
   self.compiler.register_helper(u'if_gt', self.helper_if_gt)
   self.compiler.register_helper(u'if_lt', self.helper_if_lt)
   self.compiler.register_helper(u'if_gteq', self.helper_if_gteq)
   self.compiler.register_helper(u'if_lteq', self.helper_if_lteq)
   self.compiler.register_helper(u'nl2br', self.helper_nl2br)
Exemplo n.º 41
0
Arquivo: views.py Projeto: orf/syte
def blog_post(request, post_id):
    context = dict()

    if settings.BUILTIN_POST_ENABLED:
        _post = get_object_or_404(models.Post,id=post_id,published=True)
        post = dict()
        post["id"] = _post.id
        post["title"] = _post.title
        post["formated_date"] = _post.publish_date.strftime('%B %d, %Y')
        post["type"] = "text"
        post["body"] = _post.text
        post["tags"] = [tag.name for tag in _post.tags.all()]
    else:
        r = requests.get('{0}/posts?api_key={1}&id={2}'.format(settings.TUMBLR_API_URL,
                settings.TUMBLR_API_KEY, post_id))
        if r.status_code != 200:
            post = None
        else:
            posts = r.json.get('response', {}).get("posts",[])
            if not posts:
                post = None
            else:
                post = posts[0]
                tdate = datetime.strptime(post['date'], '%Y-%m-%d %H:%M:%S %Z')
                post["formated_date"] = tdate.strftime('%B %d, %Y')

    if post:
        if settings.DISQUS_INTEGRATION_ENABLED:
            post['disqus_enabled'] = True

        path_to_here = os.path.abspath(os.path.dirname(__file__))
        f = open('{0}/static/templates/blog-post-{1}.html'.format(path_to_here, post['type']), 'r')
        f_data = f.read()
        f.close()

        compiler = Compiler()
        print post
        template = compiler.compile(unicode(f_data))
        context['post_data'] = template(post)
        context['post_title'] = post['title']

    return render(request, 'blog-post.html', context)
Exemplo n.º 42
0
    def test_compile_with_path(self):
        template = u"Hi {{name}}!"
        context = {'name': 'Ahmed'}
        result = u"Hi Ahmed!"
        path = '/project/widgets/templates'

        compiler = Compiler()

        # compile and check that speficified path is used
        self.assertEqual(result,
                         compiler.compile(template, path=path)(context))
        self.assertTrue(
            sys.modules.get('pybars._templates._project_widgets_templates')
            is not None)

        # recompile and check that a new path is used
        self.assertEqual(result,
                         compiler.compile(template, path=path)(context))
        self.assertTrue(
            sys.modules.get('pybars._templates._project_widgets_templates_1')
            is not None)
Exemplo n.º 43
0
    def _initTemplate(self):

        #
        #  Load the template
        #
        self.config.logger.info(
            "Reading template file 'email_html_template.mustache'...")
        f = codecs.open("email_html_template.mustache",
                        encoding='utf-8',
                        mode='rb')
        strtempl = f.read()
        f.close()

        #
        #  Compile the template
        #
        from pybars import Compiler
        compiler = Compiler()
        self.html_full_results_template = compiler.compile(strtempl)

        self.email_html_template = compiler.compile(strtempl)
Exemplo n.º 44
0
def cli(template, source, outputdir, pagename):
    outputdir = Path(outputdir)
    outputdir.mkdir(parents=True, exist_ok=True)

    df = pd.read_csv(source)

    compiler = Compiler()
    template = compiler.compile(open(template).read())

    with open(outputdir / "index.html", "w") as f:
        f.write(
            template(
                {
                    "data": df,
                    "dataPerVoltage": {
                        voltage: dataToTable(
                            df[df["Input voltage @ V"] == voltage])
                        for voltage in df["Input voltage @ V"].unique()
                    },
                    "pageName": pagename
                },
                helpers=buildHelpers(outputdir, df)))
Exemplo n.º 45
0
 def test_smoke(self):
     compiler = Compiler()
     def _list(this, options, items):
         result = ['<ul>']
         for thing in items:
             result.append('<li>')
             result.extend(options['fn'](thing))
             result.append('</li>')
         result.append('</ul>')
         return result
     source = u"{{#list people}}{{firstName}} {{lastName}}{{/list}}"
     template = compiler.compile(source)
     context = {
         'people': [
             {'firstName': "Yehuda", 'lastName': "Katz"},
             {'firstName': "Carl", 'lastName': "Lerche"},
             {'firstName': "Alan", 'lastName': "Johnson"}
        ]}
     rendered = template(context, helpers={u'list': _list})
     self.assertEqual(
         u"<ul><li>Yehuda Katz</li><li>Carl Lerche</li>"\
         "<li>Alan Johnson</li></ul>",
         str_class(rendered))
Exemplo n.º 46
0
def renderTemplate(templateFileName, nameValueData):

    compiler = Compiler()

    with codecs.open(templateFileName, encoding='utf-8') as f:
        templateString = f.read()

    handlebarsTemplate = compiler.compile(templateString)

    # remember functionality of helpers and partials
    # see https://github.com/wbond/pybars3

    from pybarscustom import _equal, _urlify, _languageRadioPartial, _getLanguageTitleInNativeLanguage

    helpers = {'equal': _equal, 'urlify': _urlify, 'getLanguageTitle' : _getLanguageTitleInNativeLanguage}

    languageRadioPartial = compiler.compile(_languageRadioPartial())

    partials = { 'languageRadio' : languageRadioPartial}

    render = handlebarsTemplate(nameValueData, helpers = helpers, partials = partials)

    return render
Exemplo n.º 47
0
def generate_manifests(template_vars: Dict[str, str], dest: Path) -> None:
    """Given template_vars, a dict from template variable name to the value for that variable, recursively find all
    files under K8_DIR, expand them as handlebars templates if they have a .tmpl.yml extension, and copy them to the
    same relative location in dest.  Files found under K8_DIR that do not end with .tmpl.yml are copied unchanged to
    dest.
    """
    compiler = Compiler()

    TEMPLATE_SUFFIX = '.tmpl.yml'

    # As we walk cur_dir we'll find additional subdirectories which we'll push here to be explored in later iterations.
    to_explore: List[Path] = [K8_DIR.absolute()]
    while len(to_explore) > 0:
        cur_dir = to_explore.pop().absolute()
        log.info('Looking for Kubernetes files and templates in %s', cur_dir)
        for file_or_dir in cur_dir.iterdir():
            if file_or_dir.is_dir():
                to_explore.append(file_or_dir)
            else:
                dest_file = dest / file_or_dir.absolute().relative_to(
                    K8_DIR.absolute())
                dest_file.parent.mkdir(parents=True, exist_ok=True)
                if str(file_or_dir).endswith(TEMPLATE_SUFFIX):
                    dest_file = dest_file.parent / (
                        dest_file.name[:-len(TEMPLATE_SUFFIX)] + '.yml')
                    log.info('Expanding template %s to %s', file_or_dir,
                             dest_file)
                    with open(file_or_dir, 'rt', encoding='utf-8') as inf:
                        contents = inf.read()
                        template = compiler.compile(contents)
                        out_contents = template(template_vars)
                        with open(dest_file, 'wt', encoding='utf-8') as outf:
                            outf.write(out_contents)
                else:
                    log.info('Copying %s to %s', file_or_dir, dest_file)
                    shutil.copy(file_or_dir, dest_file)
Exemplo n.º 48
0
        def _decorator(func):
            def _func(content):
                if EDIT_MODE in self.view_mode:
                    response.write(XML("""<script>
jQuery(function(){
    jQuery('#%s a').unbind("click").click(function(e) {e.preventDefault();});
});</script>""" % content_el_id))

                    response.write(XML("<div class='%s' onclick='%s'>&nbsp;</div>" %
                                       (('managed_html_content_anchor' if self._is_published(content)
                                            else 'managed_html_content_anchor_pending'),
                                        (self._post_content_js(name, 'edit') if settings.editable else ''))))

                    response.write(XML("<div onclick='%s' class='managed_html_content_inner'>" %
                                        (self._post_content_js(name, 'edit') if settings.editable else '')))
                    _body_len = len(response.body.getvalue())
                    
                func(Storage(content and content.data and json.loads(content.data) or {}))
                
                if EDIT_MODE in self.view_mode:
                    response.write(XML('</div>'))
            
            if (EDIT_MODE in self.view_mode and request.ajax and
                    self.keyword in request.vars and request.vars[self.keyword] == name):
                
                import cStringIO
                action = request.vars.get('_action')
                
                if action in ('edit', 'revert'):
                    
                    if not settings.editable:
                        raise HTTP(400)
                    
                    if action == 'revert':
                        response.flash = T('Reverted')
                        content = self._get_content(name, id=request.vars.content_id)
                    else:
                        content = self._get_content(name)
                        
                    if not content:
                        content = self._get_content(name)
                    data = content and content.data and json.loads(content.data) or {}
                    
                    virtual_record = Storage(id=0)
                    for field in fields:
                        virtual_record[field.name] = data[field.name] if field.name in data else field.default
                        
                        if type(virtual_record[field.name]) == unicode:
                            virtual_record[field.name] = virtual_record[field.name].encode('utf-8', 'ignore')
                        
                        if field.type == 'text':
                            field.widget = field.widget or self.text_widget
                            field.requires = IS_HTML()
                            
                        elif field.type.startswith('list:'):
                            if field.name + '[]' in request.vars:
                                request.vars[field.name] = [v for v in request.vars[field.name + '[]'] if v]
                                if field.type == 'list:integer' or field.type.startswith('list:reference'):
                                    request.vars[field.name] = map(int, request.vars[field.name])
                            
                        if field.name == 'handlebars':
                            virtual_record[field.name] = convert_handlebars(virtual_record[field.name])

                        if (field.name == 'handlebars' or field.name == 'html') and request.vars['dummy_form']:
                            field.widget = self.text_widget
                            field.requires = IS_HTML()
                            
                    form = SQLFORM(
                        DAL(None).define_table('no_table', *fields),
                        virtual_record,
                        upload=settings.upload,
                        showid=False,
                        buttons=[],
                    )
                    
                    if form.accepts(request.vars, session, formname='managed_html_content_form_%s' % name):
                        data = {}
                        for field in fields:
                            field_value = form.vars[field.name]
                            data[field.name] = field_value
                            if field.name == 'handlebars':
                                if field_value:
                                    from pybars import Compiler
                                    field_value = convert_handlebars(field_value.decode('utf-8', 'ignore'))
                                    tree = Compiler._get_handlebars_template()(field_value).apply('template')[0]
                                    data[field.name] = field_value
                                else:
                                    tree = None
                                data['handlebars_tree'] = tree

                        table_content = settings.table_content
                        self.db(table_content.name == name)(table_content.publish_on == None).delete()
                        table_content.insert(name=name, data=json.dumps(data))
                        content = self._get_content(name)
                        
                        response.flash = T('Edited')
                        
                        response.body = cStringIO.StringIO()
                        _func(content)
                        #self.write_managed_html(name=name, parent=None, type='handlebars')()
                        raise HTTP(200, response.body.getvalue())
                    
                    elif request.vars['_formkey']:
                        response.flash = T('Edit Failed')
                        response.body = cStringIO.StringIO()
                        _func(self._get_content(name))
                        raise HTTP(200, response.body.getvalue())
                        
                    if len(fields) == 1:
                        form.components = [form.custom.widget[fields[0].name]]
                        
                    form.components += [INPUT(_type='hidden', _name=self.keyword, _value=name),
                               INPUT(_type='hidden', _name='_action', _value='edit')]
                    content = self._get_content(name)
                    
                    raise HTTP(200, DIV(form))
                
                elif action in ('back', 'publish_now'):
                    content = self._get_content(name)
                    if action == 'publish_now':
                        if not settings.publishable:
                            raise HTTP(400)
                        content.update_record(publish_on=request.now)
                        response.js = 'managed_html_published("%s", true);' % el_id
                        response.flash = T('Published')
                    elif action == 'back':
                        response.js = 'managed_html_published("%s", %s);' % (
                                        el_id, 'true' if self._is_published(content) else 'false')
                    
                    response.body = cStringIO.StringIO()
                    _func(content)
                    raise HTTP(200, response.body.getvalue())

                elif action in ('unique_key'):
                    from gluon.utils import web2py_uuid
                    raise HTTP(200, web2py_uuid())
                elif action == 'show_add_content':
                    if not settings.editable:
                        raise HTTP(400)
                    raise HTTP(200, self._add_content(name, request.vars['_target_el']))
                else:
                    raise RuntimeError
                
            def wrapper(*args, **kwds):
                content = self._get_content(name, cache=kwargs.get('cache'))
                
                if EDIT_MODE in self.view_mode:
                    is_published = self._is_published(content)
                    
                    response.write(XML('<div id="%s" class="managed_html_content_block %s" content_type="%s">' %
                                        (el_id, 'managed_html_content_block_pending' if not is_published else '', kwargs.get('content_type', ''))))
                    
                    # === write content ===
                    response.write(XML('<div id="%s" class="managed_html_content">' % content_el_id))
                    _func(content)
                    response.write(XML('</div>'))  # <div style="clear:both;"></div>
                    
                    
                    response.write(XML('</div>'))
                    
                else:
                    # === write content ===
                    response.write(XML('<div id="%s">' % el_id))
                    _func(content)
                    response.write(XML('</div>'))
            return wrapper
Exemplo n.º 49
0
class PybarsPlus(object):
  source = None
  compiler = None
  template = None

  def __init__(self, source):
    self.compiler = Compiler()
    self.source = source
    self.compiler.register_helper(u'if_eq', self.helper_if_eq)
    self.compiler.register_helper(u'unless_eq', self.helper_unless_eq)
    self.compiler.register_helper(u'if_gt', self.helper_if_gt)
    self.compiler.register_helper(u'if_lt', self.helper_if_lt)
    self.compiler.register_helper(u'if_gteq', self.helper_if_gteq)
    self.compiler.register_helper(u'if_lteq', self.helper_if_lteq)
    self.compiler.register_helper(u'nl2br', self.helper_nl2br)

  def render(self, context):
    template = self.compiler.compile(self.source)
    if template:
      html = template(context)
      return unicode(''.join(html))
    return None

  def helper_if_eq(self, this, *args, **kwargs):
    options = args[0]
    if args[1] == kwargs['compare']:
      return options['fn'](this)
    else:
      return options['inverse'](this)

  def helper_unless_eq(self, this, *args, **kwargs):
    options = args[0]
    if args[1] != kwargs['compare']:
      return options['fn'](this)
    else:
      return options['inverse'](this)

  def helper_if_gt(self, this, *args, **kwargs):
    options = args[0]
    if args[1] > kwargs['compare']:
      return options['fn'](this)
    else:
      return options['inverse'](this)

  def helper_unless_gt(self, this, *args, **kwargs):
    pass

  def helper_if_lt(self, this, *args, **kwargs):
    options = args[0]
    if args[1] < kwargs['compare']:
      return options['fn'](this)
    else:
      return options['inverse'](this)

  def helper_unless_lt(self, this, *args, **kwargs):
    pass

  def helper_if_gteq(self, this, *args, **kwargs):
    options = args[0]
    if args[1] >= kwargs['compare']:
      return options['fn'](this)
    else:
      return options['inverse'](this)

  def helper_unless_gteq(self, this, *args, **kwargs):
    pass

  def helper_if_lteq(self, this, *args, **kwargs):
    options = args[0]
    if args[1] <= kwargs['compare']:
      return options['fn'](this)
    else:
      return options['inverse'](this)

  def helper_unless_lteq(self, this, *args, **kwargs):
    pass

  def helper_nl2br(self, this, *args, **kwargs):
    """
    var nl2br = (text + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + '<br>' + '$2');
    return new Handlebars.SafeString(nl2br);
    """
    result = re.sub(r'([^>\r\n]?)(\r\n|\n\r|\r|\n)', '<br/>', args[0])
    return strlist(result)
def compile_template_to_python(root_path, rel_path, file_name):
    dir_path = os.path.join(root_path, rel_path)
    input_path = os.path.join(dir_path, file_name)
    test_path = input_path + ".json"

    # We intentionally ignore Handlebars templates that don't have unit tests
    # when compiling to Python. If someday all templates have unit tests we
    # should emit an error here.
    if not os.path.exists(test_path):
        return None

    package_name = rel_path.replace("-", "_").split("_")[0]
    original_function_name = os.path.splitext(file_name)[0]
    partial_name = package_name + "_" + original_function_name
    function_name = original_function_name.replace("-", "_")

    out_dir_path = os.path.join("compiled_templates", package_name + "_package")
    output_path = os.path.join(out_dir_path, function_name) + ".py"
    init_path = os.path.join(out_dir_path, "__init__.py")

    compiler = Compiler()

    in_file = open(input_path, "r")
    source = unicode(in_file.read())
    source = re.sub(r"{{\s*else\s*}}", "{{^}}", source)  # Pybars doesn't handle {{else}} for some reason
    template = compiler.compile(source)

    output_string = []
    output_string.append("from pybars._compiler import strlist, _pybars_, Scope, escape, resolve, partial")
    output_string.append("")

    def write_fn(template, name, indent):

        output_string.append("%sdef %s(context, helpers=None, partials=None):" % (indent, name))
        output_string.append("%s    pybars = _pybars_" % indent)
        output_string.append("")

        output_string.append("%s    # Begin constants" % indent)

        for name, val in template.func_globals.items():
            if name.startswith("constant_"):
                if isinstance(val, unicode):
                    output_string.append("%s    %s = %s" % (indent, name, repr(val)))

        output_string.append("")

        for name, val in template.func_globals.items():
            if name.startswith("constant_"):
                if isinstance(val, types.FunctionType):
                    write_fn(val, name, indent + "    ")

        output_string.append("%s    # End constants" % indent)

        compiled_fn = inspect.getsource(template)
        fn_lines = compiled_fn.split("\n")

        for line in fn_lines[1:]:
            output_string.append("%s%s" % (indent, line))

    write_fn(template, function_name, "")

    if not os.path.exists(out_dir_path):
        os.makedirs(out_dir_path)

    out_file = open(init_path, "w")
    out_file.close()

    out_file = open(output_path, "w")
    out_file.write("\n".join(output_string))
    out_file.close()

    print "Compiled to %s" % output_path

    return (partial_name, package_name, function_name)
import csv
from pybars import Compiler
c = Compiler()
s = """<h3>Meet the 2015 challenge winners</h3>

{{#each row}}<p><strong><a href='/place/{{ id }}'>{{ title }}</a></strong> submitted by {{ submitter }}.</p>
{{/each}}"""
t = c.compile(s)

with open('2015-winners.csv', 'rU', encoding='utf-8') as csvfile:
    reader = csv.DictReader(csvfile)
    row = list(reader)

for r in row:
    r['title'] = r['title'].strip()
    r['submitter'] = r['submitter'].rstrip(' .')

print(t({"row": row}))
Exemplo n.º 52
0
def get_filter_json(filters):
    """"
    Given search filters, this function returns the JSON that
    LendingClub expects for it's investment search
    """
    compiler = Compiler()

    if not filters:
        return False

    tmpl_source = u"""
    [
        {
            "m_id": 39,
            "m_metadata": {
                "m_controlValues": [
                    {
                        "value": "Year3",
                        "label": "36-month",
                        "sqlValue": null,
                        "valueIndex": 0
                    },
                    {
                        "value": "Year5",
                        "label": "60-month",
                        "sqlValue": null,
                        "valueIndex": 1
                    }
                ],
                "m_type": "MVAL",
                "m_rep": "CHKBOX",
                "m_label": "Term (36 - 60 month)",
                "id": 39,
                "m_onHoverHelp": "Select the loan maturities you are interested to invest in",
                "m_className": "classname",
                "m_defaultValue": [
                    {
                        "value": "Year3",
                        "label": "36-month",
                        "sqlValue": null,
                        "valueIndex": 0
                    },
                    {
                        "value": "Year5",
                        "label": "60-month",
                        "sqlValue": null,
                        "valueIndex": 1
                    }
                ]
            },
            "m_value": [
            {{#if term36month}}
                {
                    "value": "Year3",
                    "label": "36-month",
                    "sqlValue": null,
                    "valueIndex": 0
                },
            {{/if}}
            {{#if term60month}}
                {
                    "value": "Year5",
                    "label": "60-month",
                    "sqlValue": null,
                    "valueIndex": 1
                }
            {{/if}}
            ],
            "m_visible": false,
            "m_position": 0
        },
        {
            "m_id": 38,
            "m_metadata": {
                "m_controlValues": [
                    {
                        "value": true,
                        "label": "Exclude loans invested in",
                        "sqlValue": null,
                        "valueIndex": 0
                    }
                ],
                "m_type": "SVAL",
                "m_rep": "CHKBOX",
                "m_label": "Exclude Loans already invested in",
                "id": 38,
                "m_onHoverHelp": "Use this filter to exclude loans from a borrower that you have already invested in.",
                "m_className": "classname",
                "m_defaultValue": [
                    {
                        "value": true,
                        "label": "Exclude loans invested in",
                        "sqlValue": null,
                        "valueIndex": 0
                    }
                ]
            },
            "m_value": [
            {{#if exclude_existing}}
                {
                    "value": true,
                    "label": "Exclude loans invested in",
                    "sqlValue": null,
                    "valueIndex": 0
                }
            {{/if}}
            ],
            "m_visible": false,
            "m_position": 0
        },
        {{#if funding_progress}}
        {
            "m_id": 15,
            "m_metadata": {
              "m_controlValues": [
                {
                  "value": 0,
                  "label": "0%",
                  "sqlValue": null,
                  "valueIndex": 0
                },
                {
                  "value": 10,
                  "label": "10%",
                  "sqlValue": null,
                  "valueIndex": 1
                },
                {
                  "value": 20,
                  "label": "20%",
                  "sqlValue": null,
                  "valueIndex": 2
                },
                {
                  "value": 30,
                  "label": "30%",
                  "sqlValue": null,
                  "valueIndex": 3
                },
                {
                  "value": 40,
                  "label": "40%",
                  "sqlValue": null,
                  "valueIndex": 4
                },
                {
                  "value": 50,
                  "label": "50%",
                  "sqlValue": null,
                  "valueIndex": 5
                },
                {
                  "value": 60,
                  "label": "60%",
                  "sqlValue": null,
                  "valueIndex": 6
                },
                {
                  "value": 70,
                  "label": "70%",
                  "sqlValue": null,
                  "valueIndex": 7
                },
                {
                  "value": 80,
                  "label": "80%",
                  "sqlValue": null,
                  "valueIndex": 8
                },
                {
                  "value": 90,
                  "label": "90%",
                  "sqlValue": null,
                  "valueIndex": 9
                },
                {
                  "value": 100,
                  "label": "100%",
                  "sqlValue": null,
                  "valueIndex": 10
                }
              ],
              "m_type": "SVAL",
              "m_rep": "SLIDER",
              "m_label": "Funding Progress",
              "id": 15,
              "m_onHoverHelp": "Specify a minimum funding level percentage desired.",
              "m_className": "classname",
              "m_defaultValue": [
                {
                  "value": 0,
                  "label": "0%",
                  "sqlValue": null,
                  "valueIndex": 0
                }
              ]
            },
            "m_value": [
              {
                "value": {{funding_progress}},
                "label": "{{funding_progress}}%",
                "sqlValue": null,
                "valueIndex": 1
              }
            ],
            "m_visible": false,
            "m_position": 0
        },
        {{/if}}
        {
            "m_id": 10,
            "m_metadata": {
                "m_controlValues": [
                    {
                        "value": "All",
                        "label": "All",
                        "sqlValue": null,
                        "valueIndex": 0
                    },
                    {
                        "value": "D",
                        "label": "<span class=\\"grades d-loan-grade\\">D</span> 18.76%",
                        "sqlValue": null,
                        "valueIndex": 1
                    },
                    {
                        "value": "A",
                        "label": "<span class=\\"grades a-loan-grade\\">A</span> 7.41%",
                        "sqlValue": null,
                        "valueIndex": 2
                    },
                    {
                        "value": "E",
                        "label": "<span class=\\"grades e-loan-grade\\">E</span> 21.49%",
                        "sqlValue": null,
                        "valueIndex": 3
                    },
                    {
                        "value": "B",
                        "label": "<span class=\\"grades b-loan-grade\\">B</span> 12.12%",
                        "sqlValue": null,
                        "valueIndex": 4
                    },
                    {
                        "value": "F",
                        "label": "<span class=\\"grades f-loan-grade\\">F</span> 23.49%",
                        "sqlValue": null,
                        "valueIndex": 5
                    },
                    {
                        "value": "C",
                        "label": "<span class=\\"grades c-loan-grade\\">C</span> 15.80%",
                        "sqlValue": null,
                        "valueIndex": 6
                    },
                    {
                        "value": "G",
                        "label": "<span class=\\"grades g-loan-grade\\">G</span> 24.84%",
                        "sqlValue": null,
                        "valueIndex": 7
                    }
                ],
                "m_type": "MVAL",
                "m_rep": "CHKBOX",
                "m_label": "Interest Rate",
                "id": 10,
                "m_onHoverHelp": "Specify the interest rate ranges of the notes  you are willing to invest in.",
                "m_className": "short",
                "m_defaultValue": [
                    {
                        "value": "All",
                        "label": "All",
                        "sqlValue": null,
                        "valueIndex": 0
                    }
                ]
            },
            "m_value": [
            {{#if grades.All }}
                {
                    "value": "All",
                    "label": "All",
                    "sqlValue": null,
                    "valueIndex": 0
                }
            {{else}}
                {{#if grades.D}}
                {
                    "value": "D",
                    "label": "<span class=\\"grades d-loan-grade\\">D</span> 18.76%",
                    "sqlValue": null,
                    "valueIndex": 1
                },
                {{/if}}
                {{#if grades.A}}
                {
                    "value": "A",
                    "label": "<span class=\\"grades a-loan-grade\\">A</span> 7.41%",
                    "sqlValue": null,
                    "valueIndex": 2
                },
                {{/if}}
                {{#if grades.E}}
                {
                    "value": "E",
                    "label": "<span class=\\"grades e-loan-grade\\">E</span> 21.49%",
                    "sqlValue": null,
                    "valueIndex": 3
                },
                {{/if}}
                {{#if grades.B}}
                {
                    "value": "B",
                    "label": "<span class=\\"grades b-loan-grade\\">B</span> 12.12%",
                    "sqlValue": null,
                    "valueIndex": 4
                },
                {{/if}}
                {{#if grades.F}}
                {
                    "value": "F",
                    "label": "<span class=\\"grades f-loan-grade\\">F</span> 23.49%",
                    "sqlValue": null,
                    "valueIndex": 5
                },
                {{/if}}
                {{#if grades.C}}
                {
                    "value": "C",
                    "label": "<span class=\\"grades c-loan-grade\\">C</span> 15.80%",
                    "sqlValue": null,
                    "valueIndex": 6
                },
                {{/if}}
                {{#if grades.G}}
                {
                    "value": "G",
                    "label": "<span class=\\"grades g-loan-grade\\">G</span> 24.84%",
                    "sqlValue": null,
                    "valueIndex": 7
                }
                {{/if}}
            {{/if}}
            ],
            "m_visible": false,
            "m_position": 0
        },
        {
            "m_id": 37,
            "m_metadata": {
                "m_controlValues": null,
                "m_type": "SVAL",
                "m_rep": "TEXTBOX",
                "m_label": "Keyword",
                "id": 37,
                "m_onHoverHelp": "Type any keyword",
                "m_className": "classname",
                "m_defaultValue": []
            },
            "m_value": null,
            "m_visible": false,
            "m_position": 0
        }
    ]
    """

    template = compiler.compile(tmpl_source)
    out = template(filters)
    if not out:
        return False
    out = ''.join(out)

    # remove extra spaces
    out = re.sub('\n', '', out)
    out = re.sub('\s{3,}', ' ', out)

    # Remove hanging commas i.e: [1, 2,]
    out = re.sub(',\s*([}\\]])', '\\1', out)

    # Space between brackets i.e: ],  [
    out = re.sub('([{\\[}\\]])(,?)\s*([{\\[}\\]])', '\\1\\2\\3', out)

    # Cleanup spaces around [, {, }, ], : and , characters
    out = re.sub('\s*([{\\[\\]}:,])\s*', '\\1', out)

    return out
Exemplo n.º 53
0
def execute_task(task, data={}):

	ctx = app.test_request_context()
	ctx.push()

	compiler = Compiler()

	try:
		if task['needs_users']:
			from saturdays.models.auth.user import User
			data['users'] = User.list()
	except KeyError:
		pass

	try:
		if task['needs_products']:
			from saturdays.models.ecom.product import Product
			data['products'] = Product.list()
	except KeyError:
		pass

	try:
		if task['needs_orders']:
			from saturdays.models.ecom.order import Order
			data['orders'] = Order.list()
	except KeyError:
		pass

	try:
		if task['needs_subscriptions']:
			from saturdays.models.ecom.subscription import Subscription
			data['subscriptions'] = Subscription.list()
	except KeyError:
		pass

	try:
		if task['has_email']:
			subject_template = compiler.compile(task['email_subject'])
			recipients_template = compiler.compile(task['email_to'])
			
			mandrill = Mandrill(app.config['MANDRILL_API_KEY'])
			body_template = compiler.compile(mandrill.templates.info(name=task['email_template'])['code'])


			message = mandrill.messages.send(
				message={
					'from_email': app.config['MANDRILL_FROM_EMAIL'],
					'from_name': app.config['MANDRILL_FROM_NAME'],
					'subject': subject_template(data),
					'html': body_template(data),
					'inline_css': True,
					'to': [{'email': recipients_template(data), 'type': 'to'}]
				},
				async=False
			)

			print(message)

			# body_template = compiler.compile(task['email_body'])

			# message = Message(subject_template(data),
			# 	sender=sender_template(data),
			# 	recipients=recipients_template(data).split(','))
			# message.html = body_template(data)

			# app.mail.send(message)

	except KeyError:
		pass

	try:
		if task['has_webhook']:
			body_template = compiler.compile(task['webhook_body'])

			response = requests.request(task['webhook_method'].lower(), task['webhook_url'], data=body_template(data), headers=task['webhook_headers'])
			

	except KeyError:
		pass