コード例 #1
0
    def generate(self):
        if self.args.name is not None:
            args = self.args.__dict__
            for template_name, file_path in files.items():
                file_path = file_path.format(**args)
                file_path = os.path.abspath(os.path.join(self.directory, file_path))

                file_dir = os.path.dirname(file_path)
                if not os.path.exists(file_dir):
                    print("Creating directory {}".format(file_dir))
                    os.makedirs(file_dir)
                print("Creating {}".format(file_path))

                with codecs.open(os.path.join(template_dir, template_name), encoding="utf-8") as stream:
                    text = stream.read()
                    newline = text.endswith("\n")  # fix for jinja2 templates removing trailing newline
                    template = Template(text)

                with codecs.open(file_path, "w", encoding="utf-8") as stream:
                    stream.write(template.render(**args))
                    if newline:
                        stream.write("\n")

            self.init_github()
            if self.github_name:
                self.create_github_repo()

        if self.args.project_short_name is not None and self.args.directory is not None:
            self.set_project_directory_shortcut()
コード例 #2
0
def generate(result, startTime):
    test_cases_list = []
    report_headers = {}
    test_cases = []
    start = startTime.strftime("%Y-%m-%d %H:%M:%S")
    duration = str(datetime.now() - startTime).split(".")[0]
    status = "成功: {} 失败: {} 出错: {} 跳过: {}".format(len(result.successes),
                                                  len(result.failures),
                                                  len(result.errors),
                                                  len(result.skipped))
    report_headers.update(
        dict(start_time=start, duration=duration, status=status))
    test_cases.extend(result.errors)
    test_cases.extend(result.failures)
    test_cases.extend(result.successes)
    test_cases.extend(result.skipped)
    for case in test_cases:
        case_id = case.get("case_id", "Case000")
        _case = case.get("case")
        msg = case.get("msg")
        status = case.get("type")
        case_name = getattr(_case, "_testMethodName", "初始化模块")
        case_des = getattr(_case, case_name + "_des", "登陆易途8司导端")
        test_cases_list.append((case_id, case_name, status, msg, case_des))
    test_cases_list = sorted(test_cases_list, key=lambda x: x[0])
    total_test = len(test_cases_list)
    with open("templates/report_template.html", encoding="utf-8") as f:
        html = Template(f.read())
        return html.render(title="易途8安卓自动化测试报告",
                           headers=report_headers,
                           test_cases_list=test_cases_list,
                           total_test=total_test)
コード例 #3
0
def dump_configuration_file():
    config = pkg_resources.resource_string(cloudify_cli.__name__,
                                           'resources/config.yaml')

    template = Template(config)
    rendered = template.render(log_path=DEFAULT_LOG_FILE)
    target_config_path = get_configuration_path()
    with open(os.path.join(target_config_path), 'w') as f:
        f.write(rendered)
        f.write(os.linesep)
コード例 #4
0
def generate(result, startTime):
    test_cases_list = []
    report_headers = {}
    test_cases = []
    start = startTime.strftime("%Y-%m-%d %H:%M:%S")
    duration = str(datetime.now() - startTime).split(".")[0]
    # 获取成功/失败/错误/跳过数量以及着色
    success, failed, error, skip = len(result.successes), len(result.failures),\
                                   len(result.errors), len(result.skipped)
    status = "<span style='color: #5cb85c'>成功: {}</span> <span style='color: #d9534f'>失败: {}</span> " \
             "<span style='color: #f0ad4e'>出错: {}</span> <span style='color: #5bc0de'>跳过: {}</span>".format(
        success, failed, error, skip)
    info = "成功: {} 失败: {} 出错: {} 跳过: {}".format(
        success, failed, error, skip)

    # 邮件展示用例运行状态
    rv = "未通过" if result.errors or result.failures else "通过"
    report_headers.update(dict(start_time=start, duration=duration, status=status))

    # 整合所有case
    test_cases.extend(sorted(result.failures, key=lambda x: x.get("case_id", "Case000")))
    test_cases.extend(sorted(result.errors, key=lambda x: x.get("case_id", "Case000")))
    test_cases.extend(sorted(result.successes, key=lambda x: x.get("case_id", "Case000")))
    test_cases.extend(sorted(result.skipped, key=lambda x: x.get("case_id", "Case000")))

    for case in test_cases:
        case_id = case.get("case_id")
        case_pic = case.get("case_id") + "_" + case['case']._testMethodName
        _case = case.get("case")
        msg = case.get("msg")
        msg = msg[1].__str__() if msg and case["type"] != "info" else msg
        status = case.get("type")
        suite = getattr(Config, "case_info").get(str(case_id))
        if suite is None:
            suite = getattr(Config, "case_info").get(
                str(re.findall(r"\((.+)\)", _case.description)[0].split(".")[-1]))
        if getattr(_case, "_testMethodName"):
            case_name = getattr(_case, "_testMethodName")
        else:
            case_name = re.findall(r"\((.+)\)", _case.description)[0].split(".")[-1]
        if getattr(_case, case_name, None) is None:
            case_des = "登录初始化模块"
        else:
            case_des = getattr(getattr(_case, case_name), "__doc__")
        test_cases_list.append((case_id, suite, status, msg, case_des, case_pic))
    # 通过case_id排序
    # test_cases_list = sorted(test_cases_list, key=lambda x: x[0])
    total_test = len(test_cases_list)
    with open(Config.report_mod, encoding="utf-8") as f:
        html = Template(f.read())
        # 渲染html模板
        return html.render(headers=report_headers, test_cases_list=test_cases_list,
                           total_test=total_test, conf=Config,
                           success=success, failed=failed, error=error, rv=rv,
                           skip=skip), info, rv
コード例 #5
0
ファイル: utils.py プロジェクト: gocloudxyz/cloudify-cli
def dump_configuration_file():
    config = pkg_resources.resource_string(
        cloudify_cli.__name__,
        'resources/config.yaml')

    template = Template(config)
    rendered = template.render(log_path=DEFAULT_LOG_FILE)
    target_config_path = get_configuration_path()
    with open(os.path.join(target_config_path), 'w') as f:
        f.write(rendered)
        f.write(os.linesep)
コード例 #6
0
def set_config(enable_colors=False):
    cli_config = pkg_resources.resource_string(cloudify_cli.__name__,
                                               'config/config_template.yaml')

    enable_colors = str(enable_colors).lower()
    template = Template(cli_config)
    rendered = template.render(log_path=DEFAULT_LOG_FILE,
                               enable_colors=enable_colors)
    with open(config.CLOUDIFY_CONFIG_PATH, 'a') as f:
        f.write(rendered)
        f.write(os.linesep)
コード例 #7
0
def generate_task_stub(
    task: str,
    search_stub: str,
    solution_stubs: List[str],
    output_file: Path,
):
    content = (experiments_dir() / "TASK.md.jinja").read_text()
    template = Template(content)
    stub = template.render(task=task,
                           search_stub=search_stub,
                           solution_stubs=solution_stubs)
    output_file.write_text(stub)
コード例 #8
0
    def assert_compare_file_control(self, control_path, actual_path):
        """Helper to compare file."""
        current_directory = resources_path()
        context = {'current_directory': current_directory}
        with open(control_path) as control_file:
            template_string = control_file.read()
            template = Template(template_string)
            control_string = template.render(context).strip()

        with io.open(actual_path, encoding='utf-8') as actual_file:
            actual_string = actual_file.read().strip()
            self.assertEquals(control_string, actual_string)
コード例 #9
0
    def _modify_docstring(self, doc, calls):
        examplesPart = Template(to_unicode(self.template))

        pattern = self.REPLACE_PATTERN
        space = re.findall(pattern, doc)[0]

        rendered = add_prefix_to_lines(
            space,
            examplesPart.render(calls=calls,
                                add_prefix_to_lines=add_prefix_to_lines,
                                space=space))

        return re.sub(pattern, to_string(rendered), to_string(doc), count=1)
コード例 #10
0
ファイル: init.py プロジェクト: codilime/cloudify-cli
def set_config(enable_colors=False):
    cli_config = pkg_resources.resource_string(
        cloudify_cli.__name__,
        'config/config_template.yaml')

    enable_colors = str(enable_colors).lower()
    template = Template(cli_config)
    rendered = template.render(
        log_path=DEFAULT_LOG_FILE,
        enable_colors=enable_colors
    )
    with open(config.CLOUDIFY_CONFIG_PATH, 'w') as f:
        f.write(rendered)
        f.write(os.linesep)
コード例 #11
0
def generate_search_stub(task, solutions, stats: dict, search_length: int,
                         output_file: Path):
    content = (experiments_dir() / "SEARCH.md.jinja").read_text()
    template = Template(content)
    stub = template.render(
        task=task,
        search_length=search_length,
        n_runs=stats["n_runs"],
        n_steps=stats["n_steps"],
        solutions=solutions,
        n_generalizes=stats["n_generalizes"],
        n_solutions=stats["n_solutions"],
    )
    output_file.write_text(stub)
コード例 #12
0
    def assert_compare_file_control(self, control_path, actual_path):
        """Helper to compare file."""
        current_directory = resources_path()
        context = {
            'current_directory': current_directory
        }
        with open(control_path) as control_file:
            template_string = control_file.read()
            template = Template(template_string)
            control_string = template.render(context).strip()

        with io.open(actual_path, encoding='utf-8') as actual_file:
            actual_string = actual_file.read().strip()
            self.assertEquals(control_string, actual_string)
コード例 #13
0
ファイル: util.py プロジェクト: chunhk/burlap
def remote_template(template_file, variables, dest_file, \
    use_sudo=False, **kwargs):

  with open(template_file, 'r') as f:
    template_content = f.read()

  template = Template(template_content)
  content = template.render(**variables)
  local_file = "/tmp/" + string_md5(content) + ".template"

  with open(local_file, 'w') as f:
    f.write(content)

  remote_file(local_file, dest_file, use_sudo=use_sudo, **kwargs)
  local("rm %s" % local_file)
コード例 #14
0
def test_from_string(elasticapm_client):
    elasticapm_client.begin_transaction("transaction.test")
    template = Template("<html></html")
    template.render()
    elasticapm_client.end_transaction("test")

    transactions = elasticapm_client.instrumentation_store.get_all()
    spans = transactions[0]['spans']

    expected_signatures = {'<template>'}

    assert {t['name'] for t in spans} == expected_signatures

    assert spans[0]['name'] == '<template>'
    assert spans[0]['type'] == 'template.jinja2'
コード例 #15
0
def test_from_string(instrument, elasticapm_client):
    elasticapm_client.begin_transaction("transaction.test")
    template = Template("<html></html")
    template.render()
    elasticapm_client.end_transaction("test")

    transactions = elasticapm_client.events[TRANSACTION]
    spans = elasticapm_client.spans_for_transaction(transactions[0])

    expected_signatures = {"<template>"}

    assert {t["name"] for t in spans} == expected_signatures

    assert spans[0]["name"] == "<template>"
    assert spans[0]["type"] == "template.jinja2"
コード例 #16
0
def test_from_string(instrument, elasticapm_client):
    elasticapm_client.begin_transaction("transaction.test")
    template = Template("<html></html")
    template.render()
    elasticapm_client.end_transaction("test")

    transactions = elasticapm_client.transaction_store.get_all()
    spans = transactions[0]["spans"]

    expected_signatures = {"<template>"}

    assert {t["name"] for t in spans} == expected_signatures

    assert spans[0]["name"] == "<template>"
    assert spans[0]["type"] == "template.jinja2"
コード例 #17
0
ファイル: jinja2_tests.py プロジェクト: ruflin/apm-python
    def test_from_string(self):
        self.client.begin_transaction("transaction.test")
        template = Template("<html></html")
        template.render()
        self.client.end_transaction("test")

        transactions = self.client.instrumentation_store.get_all()
        traces = transactions[0]['traces']

        expected_signatures = ['transaction', '<template>']

        self.assertEqual(set([t['name'] for t in traces]),
                         set(expected_signatures))

        self.assertEqual(traces[0]['name'], '<template>')
        self.assertEqual(traces[0]['type'], 'template.jinja2')
コード例 #18
0
ファイル: html.py プロジェクト: intel/cve-bin-tool
def render_cves(hid: str, cve_row: Template, tag: str,
                cves: List[Dict[str, str]]) -> str:
    """Return rendered form of CVEs using cve_row template

    Args:
        hid (str): Unique id for each product
        cve_row (Template): JinjaTemplate to be used for rendering
        tag (str): Marked by user. (default: New) Can be anything [NEW, MITIGATED, IGNORED, UNEXPLORED]
        cves (List[Dict[str, str]]): List of CVEs present in the products.

    Returns:
        str: CVE(s) in rendered form
    """
    list_cves = []
    for i, cve in enumerate(cves):
        # render CVE template with data and add to list_cves
        list_cves.append(
            cve_row.render(
                cve_number=cve["cve_number"],
                severity=cve["severity"],
                description=cve["description"],
                tag=tag,
                var_id=f"{hid}{i}{tag}",
                fix_id=hid,
            ))
    return "".join(list_cves)
コード例 #19
0
def generate_solution_stub(metrics, task, table, output_file: Path):
    exp_logger.info(f"Generate SOLUTION for {metrics}")
    content = (experiments_dir() / "SOLUTION.md.jinja").read_text()
    template = Template(content)
    stub = template.render(
        program=str(metrics["program"]),
        program_length=len(metrics["program"]),
        program_clean=program_format(metrics["program"], "_"),
        program_comma=program_format(metrics["program"], ","),
        task=task,
        table=table,
        n_runs=metrics["found_after"],
        runtime=metrics["current_runtime"],
        runtime_limit=metrics["time_limit"],
        space_probability=f"$$\\frac{{1}}{{{metrics['space_size']}}}$$",
        complexity=metrics["complexity"])
    output_file.write_text(stub)
コード例 #20
0
    def create_config(cls, workdir):
        config_path = os.path.join(workdir, CONFIG_FILE_NAME)
        if not os.path.isfile(config_path):
            config_template = pkg_resources.resource_string(
                __package__, 'config_template.yaml')

            default_values = {
                'log_path': os.path.join(workdir, 'cli.log'),
                'enable_colors': True
            }

            template = Template(config_template)
            rendered = template.render(**default_values)
            with open(config_path, 'w') as f:
                f.write(rendered)
                f.write(os.linesep)

        return cls(config_path)
コード例 #21
0
    def test_from_string(self):
        self.client.begin_transaction("transaction.test")
        template = Template("<html></html")
        template.render()
        self.client.end_transaction("test")

        transactions, traces = self.client.instrumentation_store.get_all()

        expected_signatures = ["transaction", "<template>"]

        self.assertEqual(set([t["signature"] for t in traces]), set(expected_signatures))

        # Reorder according to the kinds list so we can just test them
        sig_dict = dict([(t["signature"], t) for t in traces])
        traces = [sig_dict[k] for k in expected_signatures]

        self.assertEqual(traces[1]["signature"], "<template>")
        self.assertEqual(traces[1]["kind"], "template.jinja2")
        self.assertEqual(traces[1]["transaction"], "test")
コード例 #22
0
async def process_partition(
    loop: asyncio.BaseEventLoop,
    results_queue: asyncio.Queue,
    server_address: URL,
    http: aiohttp.ClientSession,
    partition: PointsPartition,
    mission_template: Template,
    mission_loader: str,
    mission_name: str,
    width: int,
    scale: int,
) -> Awaitable[None]:
    LOG.debug(
        f"query range [{partition.start}:{partition.end}] on server "
        f"{server_address}"
    )

    file_name = f"{mission_name}_{partition.start}_{partition.end}.mis"
    missions_url = server_address / "missions"
    mission_dir_url = missions_url / "heightmap"
    mission_url = mission_dir_url / file_name

    points = (
        index_to_point(i, width, scale)
        for i in range(partition.start, partition.end + 1)
    )
    mission = mission_template.render(
        loader=mission_loader,
        points=points,
    )

    data = FormData()
    data.add_field(
        'mission',
        mission.encode(),
        filename=file_name,
        content_type='plain/text',
    )

    await http.post(mission_dir_url, data=data)
    await http.post(mission_url / "load")
    await http.post(missions_url / "current" / "begin")

    async with http.get(server_address / "radar" / "stationary-objects") as response:
        data = await response.json()
        data = [
            pack(HEIGHT_PACK_FORMAT, int(point['pos']['z']))
            for point in data
        ]
        data = b''.join(data)

    await http.post(missions_url / "current" / "unload")
    await http.delete(mission_url)

    await results_queue.put((partition, data))
コード例 #23
0
    def test_from_string(self):
        self.client.begin_transaction()
        template = Template("<html></html")
        template.render()
        self.client.end_transaction(None, "test")

        transactions, traces = self.client.instrumentation_store.get_all()

        expected_signatures = ['transaction', '<template>']

        self.assertEqual(set([t['signature'] for t in traces]),
                         set(expected_signatures))

        # Reorder according to the kinds list so we can just test them
        sig_dict = dict([(t['signature'], t) for t in traces])
        traces = [sig_dict[k] for k in expected_signatures]

        self.assertEqual(traces[1]['signature'], '<template>')
        self.assertEqual(traces[1]['kind'], 'template.jinja2')
        self.assertEqual(traces[1]['transaction'], 'test')
コード例 #24
0
ファイル: config.py プロジェクト: tezos-checker/checker
def generate_src_module(module: Path, template: Template,
                        config: CheckerConfig) -> None:
    """Generates a source code module using the provided template and configuration

    Provides the following variables to the template:
        * config (CheckerConfig)
    """
    logger.info(
        f"Rendering src module template '{template.name}' using provided config"
    )
    rendered = template.render(config=config)
    logger.info(f"Writing rendered module at {module}")
    with module.open("w") as f:
        f.write(rendered)
コード例 #25
0
    def resolve_template(self, template):
        """Takes a template and tries to return back the appropriate
        Jinja template object.
        If an explicit Django template object is passed, do nothing."""
      
        # dirty rotten hack:
        # there's one Django test that fails when sent to a Jinja template,
        #   (d.c.auth.tests.views.ChangePasswordTest.test_password_change_succeeds)
        #   it's a test-specific template (not used elsewhere) that simply contains
        #   `{{ form.as_ul }}`, and tests for text it expects; it fails here because
        #   Jinja expects parentheses for method calls (e.g. `{{ form.as_ul() }}`)
        # there's no good way that I can see to intelligently test for this, so I'm
        #   simply going to brute force my way to the result Django expects
        if self._in_test_mode and template == 'registration/login.html':
            t = JinjaTemplate('{{ form.as_ul() }}')
            t.name = 'registration/login.html'
            return t

        # sanity check: if I got an explicit Django template object,
        # I don't want to do anything at all
        if isinstance(template, DjangoTemplate):
            return template

        # sanity check: what if I get a **Jinja** template?
        # don't do anything to that either
        if isinstance(template, JinjaTemplate):
            return template

        # okay, if I have a string or iterable, then figure out the right template
        # and return it
        if isinstance(template, basestring):
            return self._environment.get_template(template)
        elif isinstance(template, (list, tuple)):
            return self._environment.select_template(template)

        # something is wrong; stop
        raise TypeError, 'Unrecognized object sent as a template.'
コード例 #26
0
ファイル: config.py プロジェクト: tezos-checker/checker
def generate_token_src_module(module: Path, template: Template,
                              token_config: ReferencedTokenConfig) -> None:
    """Generates a token source code module using the provided template and configuration

    Provides the following variables to the template:
        * token_config (ReferencedTokenConfig)
        * module_name (str)
    """
    logger.info(
        f"Rendering token src module template '{template.name}' using provided config"
    )
    module_name = module.name.split(".")[0]
    rendered = template.render(module_name=module_name,
                               token_config=token_config)
    logger.info(f"Writing rendered module at {module}")
    with module.open("w") as f:
        f.write(rendered)
コード例 #27
0
 def template_not_found(name):
     content = return_error_message(
         "template error: can't find the template named `%s`" % name)
     return Template(content)
コード例 #28
0
        self.pool = {}
        self.paths = []

    def __getattr__(self, name):
        path = [{"access": name}]
        self.paths.append(path)
        t = Tracer(path)
        attrs = self.pool.get(name)
        if attrs is None:
            attrs = self.pool[name] = {}
        ob = Object(name, attrs, tracer=t)
        return ob


# property access
t = Template("name == {{c.name}} && age > {{c.age}}")
c = Env()
t.render(c=c)
print(c.pool, c.paths)

# nested access
t = Template("name == {{c.ob.name}} && age > {{c.ob.age}}")
c = Env()
t.render(c=c)
print(c.pool, c.paths)

# method call
t = Template("name == {{c.find_friend(c.name)}} && age > {{c.ob.age}}")
c = Env()
t.render(c=c)
print(c.pool, c.paths)
コード例 #29
0
 def _render(template: Template, **kwargs) -> str:
     logging.debug("Rendering '%s' template...", template.filename)
     return "\n".join(template.generate(**kwargs))
コード例 #30
0
def plot_single_state(program, image_dir):
    """Visualise the state of the system.

    Args:
        program: The Program object (program tape, state etc.).
        image_dir: The directory to write the state image to.
    """
    addresses = False

    state = program["state"]
    storage = program["storage"]

    instruction_pointer = state["instruction_pointer"] + -1 * state["min"]

    program_tape = []
    prev_node_name = None
    for i, v in enumerate(storage["work_tape"] + storage["program_tape"]):
        node_name = str(i)
        program_tape.append({
            "node_name": node_name,
            "prev_node_name": prev_node_name,
            "value": v,
            "work_tape": i < (-1 * state["min"]),
        })
        prev_node_name = node_name

    weight_tape = []
    prev_node_name = None
    for i, v in enumerate(list(storage["weights"])):
        node_name = str(i)
        weight_tape.append({
            "node_name": node_name,
            "prev_node_name": prev_node_name,
            "value": int(v)
        })
        prev_node_name = node_name

    weight_tape.append({
        "node_name": str(i + 1),
        "prev_node_name": prev_node_name,
        "value": " "
    })
    content = (implementation_dir() / "convert" /
               "template.tex.jinja").read_text()
    template = Template(content)

    node_name_head = ("a" + program_tape[instruction_pointer]["node_name"]
                      if addresses else "s" +
                      program_tape[instruction_pointer]["node_name"])
    a = template.render(
        program_tape=program_tape,
        weight_tape=weight_tape,
        node_name_first=program_tape[0]["node_name"],
        node_name_last=program_tape[-1]["node_name"],
        addresses=addresses,
        node_name_instruction_head=node_name_head,
        node_name_weight_head="w" + str(state["weight_pointer"]),
        s_align="s" + str(-1 * state["min"]),
        time=state["current_runtime"],
    )
    a = a.replace("\n   \n", "\n")

    if addresses:
        addresses_str = "_addresses"
    else:
        addresses_str = ""

    path = image_dir / f"{state['current_runtime']:08d}{addresses_str}.tex"
    path.write_text(a)

    to_image(path)
コード例 #31
0
ファイル: misc.py プロジェクト: umar93132/portal
def send_mail(to, etype, request, data=None):
    add_cc = ['mentoring_request', 'mentoring_request_intro']
    if data is None:
        data = {}
    mi = emails.get(etype, 'data').copy()

    if mi.get('mailer'):
        mailer = mailer_factory_from_settings(mi.get('mailer'), '')
    else:
        mailer = get_mailer(request)

    if 'user' not in data:
        from alchemist.models import User
        data['user'] = User.fr(request)

    if request.authenticated_userid and data['user'].id != request.authenticated_userid:
        from alchemist.models import User
        data['auth_user'] = User.fr(request)

    for k, v in mi.iteritems():
        if callable(v):
            v = v(data, request)
        if '/templates/' in v:
            v = render(v, data, request)
        elif isinstance(v, basestring):
            if '{{' in v and '}}' in v:
                v = Template(v).render(**data)
            else:
                v = v.format(**data)
        mi[k] = v

    if 'attachments' in data:
        attachments = data['attachments']
    elif 'attachments' in mi and mi['attachments'] and mi['attachments'] != 'None':
        with open(os.path.dirname(__file__) + mi['attachments']) as fo:
            a_file = fo.read()
        attachments = [Attachment(os.path.basename(mi['attachments']),
                                  'application/' + mi['attachments'][-3:],
                                  a_file)]
    else:
        attachments = None
    if not isinstance(to, list):
        to = to.split(',')

    from alchemist.models.settings import Settings

    send_from = mi.get('from')
    bcc = [bc for bc in mi.get('bcc', '').split(',') if bc]
    sender = Settings.get('admin_mail', '*****@*****.**')
    sender = sender.split(',')
    main_admin_mail = sender[0].strip()
    if main_admin_mail:
        bcc.append(main_admin_mail)
    if not send_from:
        send_from = main_admin_mail or '*****@*****.**'
    cc = mi.get('cc') if mi.get('cc') else []
    if '@' not in cc and not isinstance(cc, list):
        cc = Settings.get(cc, cc).split(',')
    if not cc and etype in add_cc:
        cc = [email.strip() for email in Settings.get('cc_emails', '').split(',')]
    mail = Message(mi['subject'], to, mi['text'], mi['html'],
                   sender=send_from,
                   bcc=bcc, cc=cc)
    if attachments:
        mail.attachments = attachments
    mailer.send(mail)
コード例 #32
0
 def project_release_version_url(self, version:str) -> str:
     entry = CONFIG['manager']['project_release_version_url']
     template = Template(entry)
     return template.render(home_url=self.home_url(), project_name=self.project_name, version=version)
コード例 #33
0
 def project_release_list_url(self) -> str:
     entry = CONFIG['manager']['project_release_list_url']
     template = Template(entry)
     return template.render(home_url=self.home_url(), project_name=self.project_name)
コード例 #34
0
 def account_login_url(self) -> str:
     entry = CONFIG['manager']['account_login_url']
     template = Template(entry)
     return template.render(home_url=self.home_url())
コード例 #35
0
ファイル: emails.py プロジェクト: RaHus/portal
def send_mail(to, etype, request, data=None):
    add_cc = ["mentoring_request", "mentoring_request_intro"]
    if data is None:
        data = {}
    mi = emails.get(etype, "data").copy()

    if mi.get("mailer"):
        mailer = mailer_factory_from_settings(mi.get("mailer"), "")
    else:
        mailer = get_mailer(request)

    if "user" not in data and request.user:
        data["user"] = request.user

    if request and request.authenticated_userid and data["user"].id != request.authenticated_userid:
        data["auth_user"] = request.user

    for k, v in mi.iteritems():
        if callable(v):
            v = v(data, request)
        if ".jinja2" in v:
            v = render(v, data, request)
        elif isinstance(v, basestring):
            if "{{" in v and "}}" in v:
                v = Template(v).render(**data)
            else:
                v = v.format(**data)
        mi[k] = v

    if "attachments" in data:
        attachments = data["attachments"]
    elif "attachments" in mi and mi["attachments"] and mi["attachments"] != "None":
        with open(os.path.dirname(os.path.dirname(__file__)) + mi["attachments"]) as fo:
            a_file = fo.read()
        attachments = [Attachment(os.path.basename(mi["attachments"]), "application/" + mi["attachments"][-3:], a_file)]
    else:
        attachments = None
    if not isinstance(to, list):
        to = to.split(",")

    from alchemist.models.settings import Settings

    send_from = mi.get("from")
    bcc = [bc for bc in data.get("bcc", mi.get("bcc", "").split(",")) if bc]
    sender = Settings.get("admin_mail", "*****@*****.**")
    sender = sender.split(",")
    main_admin_mail = sender[0].strip()
    if main_admin_mail:
        bcc.append(main_admin_mail)
    if not send_from:
        send_from = main_admin_mail or "*****@*****.**"
    cc = mi.get("cc") if mi.get("cc") else []
    if "@" not in cc and not isinstance(cc, list):
        cc = Settings.get(cc, cc).split(",")
    if not cc and etype in add_cc:
        cc = [email.strip() for email in Settings.get("cc_emails", "").split(",")]
    if debug and not set(Settings.get("allowed_outgoing", "").split(",")).issuperset(bcc + cc + to):
        print "Wanted to send email %s to %s, didn't" % (etype, bcc + cc + to)
        return None
    mail = Message(mi["subject"], to, mi["text"], mi["html"], sender=send_from, bcc=bcc, cc=cc)
    if attachments:
        mail.attachments = attachments
    mailer.send(mail)
コード例 #36
0
ファイル: make_base.py プロジェクト: ra2003/flask-cms
def get_base(*args, **kwargs):
    rtn = get_head(*args, **kwargs)
    rtn += get_body()
    return Template(rtn)
コード例 #37
0
ファイル: errors.py プロジェクト: zhiiker/FarBox
</head>
<body>
    <p style="color:red"> {{message}} </p>
    <textarea class="lined" style="width:100%;min-height: 500px;">{{source}}</textarea>
    <script>
        $(function() {
                    $(".lined").linedtextarea(
                    {selectedLine: {{lineno}}}
                    );
                });
    </script>
</body>
</html>
"""

error_500_template = Template(error_500_template_resource)
error_syntax_error_template = Template(error_syntax_error_template_resource)


@app.errorhandler(500)
def page_error(error):
    debug = False
    template_kwargs = {}
    info = getattr(error, 'description', None)
    if isinstance(info, TemplateSyntaxError):
        debug = True
        template_kwargs = dict(lineno=info.lineno,
                               source=info.source,
                               message=info.message)
    elif isinstance(info, dict) and info.get('debug'):
        debug = True
コード例 #38
0
# -*- coding: utf-8 -*-
from jinja2.environment import Template


BLUEPRINT_VIEWS_TEMPLATE = Template(u'''\
# -*- coding: utf-8 -*-
from {{ blueprint_name }} import {{ blueprint_name }}

# Put your {{ blueprint_name }} blueprint views here

''')


BLUEPRINT_INIT_TEMPLATE = Template(u'''\
# -*- coding: utf-8 -*-
from flask.blueprints import Blueprint


{{ blueprint_name }} = Blueprint('{{ blueprint_name }}', __name__,
                                 template_folder='templates',
                                 static_folder='static',
                                 url_prefix='/{{ blueprint_name }}')


# All of yours blueprint logic
from views import *

''')


BLUEPRINT_MODELS_TEMPLATE = Template(u'''\