示例#1
0
	def post_argv(self, post= None):
		if post:
			#####
			if 'picture' in post['post']['content']:
				content 	=  template.Template('<img src="{{ picture }}">').generate(picture=post['post']['content']['picture']).decode("utf-8")
			elif 'video' in post['post']['content']:
				content 	=  template.Template('<div class="video" link="{{ video }}"></div>').generate(video=post['post']['content']['video']).decode("utf-8")
			else:
				content 	= ""
			#####
			if 'type' in post and post['type'] == 'private':
				warning 	= "Bài viết đang được chờ kiểm duyệt, bạn thông cảm nhé :)"
			else:
				warning 	= ""
			#####
			if 'note' in post['post']['content']:
				# old version
				argv 	= {
					"id" 			: str(post['_id']),
					"content" 		: content,
					"note"			: escape.xhtml_escape(post['post']['content']['note']),
					"link" 			: "%s://%s/%s/%s/%s/%s.html" % (self.site.request.protocol, self.site.request.host, self.site.db_site['name'], self.site.db_page['name'], post['_id'], function.seo_encode(post['post']['title'])),
					"title"			: escape.xhtml_escape(post['post']['title']),
					"source"		: escape.xhtml_escape(post['post']['content']['source']),
					"time"			: post['time'],
					"user.name" 	: post['user']['first_name'] + ' ' + post['user']['last_name'],
					"user.picture"	: post['user']['picture'],
					"warning"		: warning,
					"banner" 		: ''
				}
			else:
				# newversion
				argv 	= {
					"id" 			: str(post['_id']),
					"content" 		: content,
					"note"			: escape.xhtml_escape(post['post']['note']),
					"link" 			: "%s://%s/%s/%s/%s/%s.html" % (self.site.request.protocol, self.site.request.host, self.site.db_site['name'], self.site.db_page['name'], post['_id'], function.seo_encode(post['post']['title'])),
					"title"			: escape.xhtml_escape(post['post']['title']),
					"source"		: escape.xhtml_escape(post['post']['source']),
					"time"			: post['time'],
					"user.name" 	: post['user']['first_name'] + ' ' + post['user']['last_name'],
					"user.picture"	: post['user']['picture'],
					"warning"		: warning,
					"banner" 		: "banner" if 'banner' in post['post'] and post['post']['banner'] else '',
				}
		else:
			argv 	= {
				"id" 			: '{{ id }}',
				"content" 		: '{{ content }}',
				"note" 			: '{{ note }}',
				"link" 			: '{{ link }}',
				"title"			: '{{ title }}',
				"source"		: '{{ source }}',
				"time"			: '{{ time }}',
				"user.name" 	: '{{ user.name }}',
				"user.picture"	: '{{ user.picture }}',
				"warning"		: '{{ warning }}',
				"banner" 		: '{{ banner }}',
			}
		return argv
示例#2
0
 def post_argv(self, post=None):
     if post:
         if 'thumbnail' in post['post']['content'] and post['post'][
                 'content']['thumbnail']:
             content = template.Template(
                 '<img src="{{ picture }}">').generate(
                     picture=post['post']['content']['thumbnail']).decode(
                         "utf-8")
         elif 'picture' in post['post']['content'] and post['post'][
                 'content']['picture']:
             content = template.Template(
                 '<img src="{{ picture }}">').generate(
                     picture=post['post']['content']['picture']).decode(
                         "utf-8")
         else:
             content = ""
         ### seo title generic ###
         if 'seo_title' in post['post']:
             seo_title = post['post']['seo_title']
         else:
             seo_title = function.seo_encode(post['post']['title'])
         ### link generic ###
         if 'link' in post['post']:
             link = post['post']['link']
         else:
             link = "/%s/%s/%s/%s.html" % (self.site.db_site['name'],
                                           self.site.db_page['name'],
                                           post['_id'], seo_title)
         ### is public post ###
         if 'type' in post:
             action = post['type']
         else:
             action = 'private'
         #####
         argv = {
             "id": str(post['_id']),
             "content": content,
             "link": link,
             "title": post['post']['title'],
             "by":
             post['user']['first_name'] + ' ' + post['user']['last_name'],
             "view": post['view']['count'] if 'view' in post else 0,
             "time": post['time'],
             "action": action,
         }
     else:
         argv = {
             "id": '{{ id }}',
             "content": '{{ content }}',
             "link": '{{ link }}',
             "title": '{{ title }}',
             "by": '{{ by }}',
             "view": '{{ view }}',
             "time": '{{ time }}',
             "action": '{{ action }}',
         }
     return argv
示例#3
0
def generate_cpp_files():
    " Generate cpp files. "

    H_TMPL = 'lang-tmpls/cpp/h.tmpl'
    CPP_TMPL = 'lang-tmpls/cpp/cpp.tmpl'

    t = template.Template(open(H_TMPL, 'rb').read())

    h_out = file_in.lower().split('.')[0] + '.h'
    output(t.generate(**context).replace('\n\n', '\n'), h_out)

    t = template.Template(open(CPP_TMPL, 'rb').read())

    cpp_out = file_in.lower().split('.')[0] + '.cpp'
    output(t.generate(**context).replace('\n\n', '\n'), cpp_out)
示例#4
0
	def post_argv(self, post= None):
		if post and 'link' in post['post']:
			if 'thumbnail' in post['post']['picture'] and post['post']['picture']['thumbnail']:
				picture 	=  template.Template('<img src="{{ picture }}">').generate(picture=post['post']['picture']['thumbnail']).decode("utf-8")
			elif 'picture' in post['post']['picture'] and post['post']['picture']['full']:
				picture 	=  template.Template('<img src="{{ picture }}">').generate(picture=post['post']['picture']['full']).decode("utf-8")
			else:
				picture 	= ""
			### seo title generic ###
			if 'seo_title' in post['post']:
				seo_title 	= post['post']['seo_title']
			else:
				seo_title 	= function.seo_encode(post['post']['title'])
			### is public post ###
			if 'type' in post:
				action 	= post['type']
			else:
				action 	= 'private'

			if action in ["private", "trash"]:
				time 	= post['time']
			else:
				time 	= post['public']['time']
			#####
			argv 	= {
				"id" 		: str(post['_id']),
				"picture" 	: picture,
				"link" 		: post['post']['link'],
				"view" 		: "%s://%s/%s/%s/%s/%s.html" % (self.site.request.protocol, self.site.request.host, self.site.db_site['name'], self.module['setting']['server']['page_view'], post['_id'], seo_title),
				"site" 		: urlparse(post['post']['link']).netloc,
				"title"		: post['post']['title'],
				"by" 		: post['user']['first_name'] + ' ' + post['user']['last_name'],
				"view"		: post['view']['count'] if 'view' in post else 0,
				"time"		: time,
			}
		else:
			argv 	= {
				"id" 		: '{{ id }}',
				"picture" 	: '{{ picture }}',
				"link" 		: '{{ link }}',
				"view" 		: '{{ view }}',
				"site" 		: '{{ site }}',
				"title"		: '{{ title }}',
				"by" 		: '{{ by }}',
				"view"		: '{{ view }}',
				"time"		: '{{ time }}',
			}
		return argv
示例#5
0
def work():
    mongo = MongoStruct()
    mongo.init()
    mongodata = []
    text_data = []
    mongo.select(mongodata)
    index = 0
    pagenum = 0
    fnow = None
    tplfile = open("./template/template.html")
    tpl = template.Template(tplfile.read())
    while index < len(mongodata):
        if index % 20 == 0:
            fnow = open("./data/text_" + str(pagenum) + ".html", "w")
            data = {}
            data["pre"] = "/text_" + str(pagenum - 1) + ".html"
            data["next"] = "/text_" + str(pagenum + 1) + ".html"
            data["items"] = text_data
            fnow.write(tpl.generate(data=data))
            fnow.close()
            text_data = []
            pagenum += 1
            print "write %d" % (pagenum)

        text_data.append(mongodata[index])
        index += 1
示例#6
0
 def get_page_content(self, tag_images):
     base = """{% for i in range(len(tag_images)) %}
                 {% set image_all = list(tag_images.keys())[i] %}
                 {% set image_all_arr = image_all.split('/') %}
                 {% set image = image_all_arr[1] if len(image_all_arr) == 2 else image_all %}
                 <tr>
                     <td>{{i}}</td>
                     <td>
                         <a href="/tags/{{image_all}}">{{image_all}}
                             {% if image in online %}
                             <sup id="online"><font color="green">k8s</font></sup></a>
                             {% end %}
                         </td>
                     <td>{{len(tag_images.get(image_all))}}</td>
                     <td>{{tag_images.get(image_all)[0].get("tag")}}</td>
                     <td class="col-6">{{tag_images.get(image_all)[0].get("time")}}</td>
                     {%if user is not None%}
                         <td class="del"><a href="JavaScript:void(0)" rel="/delete/{{list(tag_images.keys())[i]}}">删除</a></td>
                     {% end %}
                 </tr>
                 </a>
               {% end %}"""
     t = template.Template(base)
     return t.generate(tag_images=tag_images,
                       online=get_online(),
                       user=self.current_user)
示例#7
0
    def render(self, base_path, filename):
        """Return the specified file.

        :param str base_path: The base path of the file to render
        :param str filename: The file to render

        """
        source = path.normpath(path.join(self._source, base_path, filename))
        dest = path.normpath(path.join(self._dest, base_path, filename))
        dest_path = path.dirname(dest)
        if not path.exists(dest_path):
            LOGGER.debug('Creating %s', dest_path)
            os.mkdir(dest_path)

        info = os.stat(source)
        file_mtime = datetime.datetime.fromtimestamp(info.st_mtime)

        with open(source, 'r') as handle:
            template_str = handle.read()

        content, data = None, None
        if source.endswith('.json'):
            content = json.loads(template_str)
        elif source.endswith('.yml') or source.endswith('.yaml'):
            content = yaml.load(template_str)

        if content:
            for var in ['template', 'data']:
                if var not in content:
                    LOGGER.error('%r not found in %s, skipping', var, source)
                    return
            template_str = content['template']
            data = content['data']
            extension = '.{}'.format(source.split('.')[:-1])
            dest = '{}.{}'.format(dest[:len(dest) - len(extension)],
                                  content.get('extension', 'html'))

        LOGGER.debug('Writing to %s', dest)
        try:
            renderer = template.Template(template_str, source, self._loader)
        except (SyntaxError, template.ParseError) as err:
            LOGGER.error('Error rendering %s: %r', dest, err)
            return False

        render_filename = filename if base_path == '.' \
            else '{}/{}'.format(base_path, filename)
        with open(dest, 'wb') as handle:
            try:
                handle.write(
                    renderer.generate(base_path=self.base_path,
                                      filename=render_filename,
                                      file_mtime=file_mtime,
                                      static_url=self.static_url,
                                      data=data,
                                      nested_data=modules.NestedData.render))
            except Exception as err:
                LOGGER.error('Error rendering %s: %r', dest, err)
                return False
        return True
示例#8
0
    def __init__(self):
        u"""初始化函数."""
        FILEPATH = os.path.abspath(os.path.dirname(__file__))
        TMPLPATH_DEFINE = '{tmpl}'
        TMPLPATH = FILEPATH + '/template'

        parser = argparse.ArgumentParser(
            description='pyfuncs.genconf.logger_conf_maker')

        parser.add_argument('-i', '--input',
                            default='{tmpl}/logger_default.json',
                            help='输入配置json')

        parser.add_argument('-o', '--output',
                            default='./logging',
                            help='输出目录')

        parser.add_argument('-of', '--output_fmt',
                            default='logging_{0:02d}.ini',
                            help='输出文件名格式')

        parser.add_argument('-t', '--tmpl',
                            default='{tmpl}/logger_template.ini',
                            help='引用模板文件')

        parser.add_argument('-c', '--count',
                            type=int,
                            default=11,
                            help='生成数量')

        parser.add_argument('-e', '--encoding',
                            default='utf8',
                            help='文件编码设置(默认:utf8)')

        args = parser.parse_args()

        self.input = args.input.replace(TMPLPATH_DEFINE, TMPLPATH)
        self.tmpl = args.tmpl.replace(TMPLPATH_DEFINE, TMPLPATH)
        self.count = args.count
        self.output = args.output
        self.output_fmt = args.output_fmt
        self.encoding = args.encoding

        if not os.path.exists(self.input) or not os.path.isfile(self.input):
            raise TypeError('输入配置json无效')

        if not os.path.exists(self.tmpl) or not os.path.isfile(self.tmpl):
            raise TypeError('输入配置tmpl无效')

        if not os.path.exists(self.output) or not os.path.isdir(self.output):
            raise TypeError('输出目录无效')

        with codecs.open(self.tmpl, 'r', encoding=self.encoding) as fs:
            self.tmpl = template.Template(fs.read())

        with codecs.open(self.input, 'r', encoding=self.encoding) as fs:
            self.input = json.loads(fs.read())
示例#9
0
def wg_reconfig(network='net0', hostname=None, can_register=False):
    if hostname is None:
        hostname = run('hostname').strip()

    db = HostsDB()
    host = db.find_host_by_name(hostname)
    if not host and can_register:
        wg_register_host(network=network,
                         hostname=hostname)  # call register host first
        db.load(force=True)
        host = db.find_host_by_name(hostname)
    if not host:
        raise ValueError("Cannot find host!?")
    net = db.find_net_by_name(host['net'])

    assert wg_genkey(network=network) == host['pubkey']

    peers = [
        h for h in db.all_hosts()
        if h['name'] != host['name'] and h['net'] == host['net']
    ]
    for peer in peers:
        # same region?
        if peer.get('port') and peer.get('region') and peer[
                'region'] == host.get('region') and peer.get('regionip'):
            peer['endpoint'] = peer['region_ip'] + ':' + str(peer['port'])
        elif peer.get('port') and peer.get('publicip'):
            peer['endpoint'] = peer['publicip'] + ':' + str(peer['port'])

    from tornado import template
    templ = template.Template(TEMPLATE)
    txt = templ.generate(
        ip4mask=net['ip4'].split('/')[-1],
        ip6mask=net['ip6'].split('/')[-1],
        net=net,
        host=host,
        peers=[h for h in db.all_hosts() if h['name'] != host['name']],
    )

    privfile = '/etc/wireguard/{}.priv'.format(network)
    conffile = '/etc/wireguard/wg-{}.conf'.format(network)
    put(StringIO.StringIO(txt), conffile, use_sudo=True)
    sudo('chown root.root ' + conffile)
    sudo('chmod 0600 ' + conffile)

    # replace the private key
    sudo('''sed -i "s|##REPLACE WITH PRIVATE KEY##|$(cat {})|" {}'''.format(
        privfile, conffile))

    # allow access via firewall if ufw available
    sudo('ufw allow 51820/udp', warn_only=True)

    # reload the config
    # TODO: no interruptions
    sudo('wg-quick down wg-{0} ; wg-quick up wg-{0}'.format(network))
    sudo('systemctl enable wg-quick@wg-{}'.format(network))
示例#10
0
 def _create_template(self, name):
     for root in self.roots:
         path = os.path.join(root, name)
         if os.path.exists(path):
             f = open(path, "rb")
             t = template.Template(f.read(), name=name, loader=self)
             f.close()
             return t
     else:
         raise Exception("Couldn't find template.")
示例#11
0
def complete(ret):
    # coding=utf-8
    """eval "$(bgmi complete)" to complete bgmi in bash"""
    updating_bangumi_names = [
        x["name"] for x in Bangumi.get_updating_bangumi(order=False)
    ]

    all_config = [x for x in bgmi.config.__all__ if not x == "DATA_SOURCE"]

    actions_and_opts = {}
    helper = {}
    for action_dict in actions_and_arguments:
        actions_and_opts[action_dict["action"]] = []
        for arg in action_dict.get("arguments", []):
            if isinstance(arg["dest"], str) and arg["dest"].startswith("-"):
                actions_and_opts[action_dict["action"]].append(arg)
            elif isinstance(arg["dest"], list):
                actions_and_opts[action_dict["action"]].append(arg)
        helper[action_dict["action"]] = action_dict.get("help", "")

    if "bash" in os.getenv("SHELL").lower():  # bash
        template_file_path = os.path.join(os.path.dirname(__file__), "..",
                                          "others", "_bgmi_completion_bash.sh")

    elif "zsh" in os.getenv("SHELL").lower():  # zsh
        template_file_path = os.path.join(os.path.dirname(__file__), "..",
                                          "others", "_bgmi_completion_zsh.sh")

    else:
        import sys

        print("unsupported shell {}".format(os.getenv("SHELL").lower()),
              file=sys.stderr)
        return

    with open(template_file_path) as template_file:
        shell_template = template.Template(template_file.read(), autoescape="")

    template_with_content = shell_template.generate(
        actions=ACTIONS,
        bangumi=updating_bangumi_names,
        config=all_config,
        actions_and_opts=actions_and_opts,
        source=[x["id"] for x in SUPPORT_WEBSITE],
        helper=helper,
        isinstance=isinstance,
        string_types=(str, ),
    )  # type: bytes

    if os.environ.get("DEBUG", False):  # pragma: no cover
        with open("./_bgmi", "wb+") as template_file:
            template_file.write(template_with_content)

    template_with_content = template_with_content.decode("utf-8")
    print(template_with_content)
示例#12
0
文件: cli.py 项目: terry0824/BGmi
def complete(ret):
    # coding=utf-8
    """eval "$(bgmi complete)" to complete bgmi in bash"""
    updating_bangumi_names = [
        x['name'] for x in Bangumi.get_updating_bangumi(order=False)
    ]

    all_config = [x for x in bgmi.config.__all__ if not x == 'DATA_SOURCE']

    actions_and_opts = {}
    helper = {}
    for action_dict in actions_and_arguments:
        actions_and_opts[action_dict['action']] = []
        for arg in action_dict.get('arguments', []):
            if isinstance(arg['dest'],
                          string_types) and arg['dest'].startswith('-'):
                actions_and_opts[action_dict['action']].append(arg)
            elif isinstance(arg['dest'], list):
                actions_and_opts[action_dict['action']].append(arg)
        helper[action_dict['action']] = action_dict.get('help', '')

    if 'bash' in os.getenv('SHELL').lower():  # bash
        template_file_path = os.path.join(os.path.dirname(__file__), '..',
                                          'others', '_bgmi_completion_bash.sh')

    elif 'zsh' in os.getenv('SHELL').lower():  # zsh
        template_file_path = os.path.join(os.path.dirname(__file__), '..',
                                          'others', '_bgmi_completion_zsh.sh')

    else:
        import sys
        print('unsupported shell {}'.format(os.getenv('SHELL').lower()),
              file=sys.stderr)
        return

    with open(template_file_path, 'r') as template_file:
        shell_template = template.Template(template_file.read(), autoescape='')

    template_with_content = shell_template.generate(
        actions=ACTIONS,
        bangumi=updating_bangumi_names,
        config=all_config,
        actions_and_opts=actions_and_opts,
        source=[x['id'] for x in SUPPORT_WEBSITE],
        helper=helper,
        isinstance=isinstance,
        string_types=string_types)  # type: bytes

    if os.environ.get('DEBUG', False):  # pragma: no cover
        with open('./_bgmi', 'wb+') as template_file:
            template_file.write(template_with_content)

    template_with_content = template_with_content.decode('utf-8')
    print(template_with_content)
示例#13
0
 def load(self, name, parent_path=None):
     name = self.resolve_path(name, parent_path=parent_path)
     if name not in self.templates:
         path = os.path.join(self.root, name)
         f = open(path, "r")
         self.templates[name] = template.Template(f.read(),
                                                  name=name,
                                                  loader=self,
                                                  compress_whitespace=False)
         f.close()
     return self.templates[name]
示例#14
0
    def _create_template(self, name):
        """Loads the template from package data.

        :param str name: The relative path to the template file in the package
        :rtype: tornado.template.Template

        """
        LOGGER.debug('Loading %s', path.join(self.root, name))
        return template.Template(pkgutil.get_data(
            __name__.split('.')[0], path.join(self.root, name)),
                                 name=name,
                                 loader=self)
示例#15
0
    def _create_template(self, name):
        """Create an instance of a tornado.template.Template object for the
        given template name.

        :param str name: The name/path to the template
        :rtype: tornado.template.Template

        """
        url = '%s/%s' % (self._base_url, escape.url_escape(name))
        LOGGER.debug('Making HTTP GET request to %s', url)
        response = self._http_client.fetch(url)
        data = json.loads(response.body, ensure_ascii=False)
        return template.Template(data['template'], name=name, loader=self)
示例#16
0
    def _create_template(self, name):

        # Construct the URL
        url = '%s/%s' % (self._base_url, escape.url_escape(name))

        # Fetch the data from couchdb
        self._logger.debug('Making HTTP GET request to %s', url)
        response = self._http_client.fetch(url)

        # Load the data from the JSON string
        data = json.loads(response.body)

        # Return the template
        return template.Template(data['template'], name=name, loader=self)
示例#17
0
class _MainHandler(basic_auth.BasicAuthHandler):
  """Displays the servers being babysat, with status information."""

  _TEMPLATE = template.Template("""
<html>
  <title>Babysitter Status</title>
  <body>Admin: {{ user }}</body>
</html>
""")

  @handler.authenticated()
  def get(self):
    self.write(_MainHandler._TEMPLATE.generate(
        user=self.get_current_user()))
示例#18
0
def config_gen(ret):
    template_file_path = os.path.join(os.path.dirname(__file__), '..',
                                      'others', 'nginx.conf')

    with open(template_file_path, 'r') as template_file:
        shell_template = template.Template(template_file.read(), autoescape='')

    template_with_content = shell_template.generate(
        actions=ACTIONS,
        server_name=ret.server_name,
        os_sep=os.sep,
        front_static_path=bgmi.config.FRONT_STATIC_PATH,
        save_path=bgmi.config.SAVE_PATH)  # type: bytes

    template_with_content = template_with_content.decode('utf-8')
    print(template_with_content)
示例#19
0
def config_gen(ret: Any) -> None:
    template_file_path = os.path.join(os.path.dirname(__file__), "..",
                                      "others", "nginx.conf")

    with open(template_file_path) as template_file:
        shell_template = template.Template(template_file.read(), autoescape="")

    template_with_content = shell_template.generate(
        actions=ACTIONS,
        server_name=ret.server_name,
        os_sep=os.sep,
        front_static_path=bgmi.config.FRONT_STATIC_PATH,
        save_path=bgmi.config.SAVE_PATH,
    )  # type: bytes

    print(template_with_content.decode("utf-8"))
    def test_template_renderer(self):
        # it should trace the Template generation even outside web handlers
        t = template.Template('Hello {{ name }}!')
        value = t.generate(name='world')
        assert value == b'Hello world!'

        traces = self.tracer.writer.pop_traces()
        assert 1 == len(traces)
        assert 1 == len(traces[0])

        template_span = traces[0][0]
        assert 'tornado-web' == template_span.service
        assert 'tornado.template' == template_span.name
        assert 'template' == template_span.span_type
        assert 'render_string' == template_span.resource
        assert 'render_string' == template_span.get_tag('tornado.template_name')
        assert 0 == template_span.error
示例#21
0
    def test_template_renderer(self):
        # it should trace the Template generation even outside web handlers
        t = template.Template("Hello {{ name }}!")
        value = t.generate(name="world")
        assert value == b"Hello world!"

        traces = self.pop_traces()
        assert 1 == len(traces)
        assert 1 == len(traces[0])

        template_span = traces[0][0]
        assert "tornado-web" == template_span.service
        assert "tornado.template" == template_span.name
        assert "template" == template_span.span_type
        assert "render_string" == template_span.resource
        assert "render_string" == template_span.get_tag("tornado.template_name")
        assert 0 == template_span.error
示例#22
0
def main():
    parser = argparse.ArgumentParser(description='nginx_conf_maker.')
    parser.add_argument('--path', help='file path')
    parser.add_argument(
        '--tmpl_path', help='file path default:{pyfunc}/'
        'genconf/template/nginx_template.conf')
    parser.add_argument(
        '--out_path', help='file path default:./output/nginx.conf')
    parser.add_argument(
        '--debug', help='gen debug config default:false')
    parser.add_argument('--encode', help='file encode default:utf8')
    args = parser.parse_args()

    if not args.path:
        print('You must supply a path\n', file=sys.stderr)
        parser.print_help()
        return

    if not args.out_path:
        args.out_path = './output/nginx.conf'

    if not args.tmpl_path:
        pkg_path = os.path.abspath(os.path.dirname(__file__))
        args.tmpl_path = pkg_path + '/template/nginx_template.conf'

    if not args.encode:
        args.encode = 'utf8'

    if not args.debug:
        args.debug = False
    else:
        args.debug = bool(args.debug)

    with codecs.open(args.tmpl_path, encoding=args.encode) as fs:
        template_obj = template.Template(fs.read())
    config_json = open_conf(args.path, args.encode)
    init_config(config_json)

    data = template_obj.generate(
        nginx_servers=config_json['nginx_servers'],
        servers=config_json['servers'],
        # run_mode=config_json['run_mode'],
        debug_config=args.debug
    )
    save_conf(args.out_path, data, args.encode)
def export_cs(model_dict):
    template_path = os.getcwd() + "/templates/DRModel.cs.template"
    output_path = os.getcwd(
    ) + "/output/cs/DR" + model_dict["model_name"] + ".cs"
    with open(template_path, "r", encoding="utf-8") as file:
        t = template.Template(file.read())
    # pprint.pprint(model_dict)
    # 当字段类型为float时,c#代码中自动转化为double,这是因为json在解析float可能是会出现精度丢失,double不会
    # for item in model_dict["data_list"]:
    # 	if item["fieldType"]=="float":
    # 		item["fieldType"]="double"

    s = t.generate(note_name=model_dict["note_name"],
                   model_name=model_dict["model_name"],
                   data_list=model_dict["data_list"]).decode()

    with open(output_path, "w", encoding="utf-8") as file:
        file.write(s)
示例#24
0
    def get(self):
        print("[HTTP] Serving file {}".format(self.path))

        self.set_status(200)
        self.set_header('Content-Type', self.content_type)
        self.set_header('Cache-Control', 'no-cache, no-store, must-revalidate')
        self.set_header('Pragma', 'no-cache')

        with open(self.path, 'rb') as f:
            content = f.read()
            if self.is_template:
                t = template.Template(content)
                content = t.generate(host=HOST,
                                     http_port=HTTP_PORT,
                                     revshell_port=REVSHELL_PORT)
            self.write(content)

        self.finish()
    def test_template_renderer_exception(self):
        # it should trace the Template exceptions generation even outside web handlers
        t = template.Template('{% module ModuleThatDoesNotExist() %}')
        with pytest.raises(NameError):
            t.generate()

        traces = self.tracer.writer.pop_traces()
        assert 1 == len(traces)
        assert 1 == len(traces[0])

        template_span = traces[0][0]
        assert 'tornado-web' == template_span.service
        assert 'tornado.template' == template_span.name
        assert 'template' == template_span.span_type
        assert 'render_string' == template_span.resource
        assert 'render_string' == template_span.get_tag('tornado.template_name')
        assert 1 == template_span.error
        assert 'is not defined' in template_span.get_tag('error.msg')
        assert 'NameError' in template_span.get_tag('error.stack')
示例#26
0
    def test_template_renderer_exception(self):
        # it should trace the Template exceptions generation even outside web handlers
        t = template.Template("{% module ModuleThatDoesNotExist() %}")
        with pytest.raises(NameError):
            t.generate()

        traces = self.pop_traces()
        assert 1 == len(traces)
        assert 1 == len(traces[0])

        template_span = traces[0][0]
        assert "tornado-web" == template_span.service
        assert "tornado.template" == template_span.name
        assert "template" == template_span.span_type
        assert "render_string" == template_span.resource
        assert "render_string" == template_span.get_tag("tornado.template_name")
        assert 1 == template_span.error
        assert "is not defined" in template_span.get_tag("error.msg")
        assert "NameError" in template_span.get_tag("error.stack")
示例#27
0
    def __init__(self, applicationName, modelName, autoload):

        rawTemplate = '''
Ext.define('{{ applicationName }}.store.{{ modelName }}', {
    extend: 'Ext.data.store',
    alias: 'store.{{ modelName.lower() }}'
    model: '{{ applicationName }}.model.{{ modelName }}'{% if autoload %},
    autoLoad: true {% end %}
});
        '''

        t = template.Template(rawTemplate)
        result = t.generate(applicationName=applicationName,
                            modelName=modelName,
                            autoload=autoload)

        lines = str(result).split("\\n")[1:]

        self.__generated = "\n".join(lines[:-1])
示例#28
0
def render(gpus, jobs, users):
    # put UP gpu's first, then sort by gpu number e.g. guppy9 before guppy12
    gpus = sorted([gpu for gpu in gpus.values() if gpu.ngpu > 0],
                  key=lambda gpu:
                  (not gpu.is_up(),
                   int(gpu.name[5:] if gpu.name.startswith("guppy") else 100)))
    # usage stats
    total_gpus = sum([gpu.ngpu for gpu in gpus if gpu.is_up()])
    total_used = sum([gpu.gpu_used() for gpu in gpus if gpu.is_up()])
    # render template
    template = T.Template(open('src/template.html').read())
    output = template.generate(gpus=gpus,
                               jobs=jobs,
                               total_gpus=total_gpus,
                               total_used=total_used,
                               usage_rate=int(
                                   round(100 * total_used / total_gpus)),
                               update_time=datetime.datetime.now())
    open('index.html', 'w').write(output)
示例#29
0
def main():
    parser = argparse.ArgumentParser(description='supervisord_maker.')
    parser.add_argument('--path', help='file path')
    parser.add_argument('--tmpl_path',
                        help='file path default:{pyfunc}/'
                        'genconf/template/supervisord_template.conf')
    parser.add_argument('--out_path',
                        help='file path default:./output/nginx.conf')
    parser.add_argument('--print_desc',
                        help='print_desc',
                        type=bool,
                        default=True)
    parser.add_argument('--encode', help='file encode default:utf8')
    args = parser.parse_args()

    if not args.path:
        print('You must supply a path\n', file=sys.stderr)
        parser.print_help()
        return

    if not args.out_path:
        args.out_path = './output/nginx.conf'

    if not args.tmpl_path:
        pkg_path = os.path.abspath(os.path.dirname(__file__))
        args.tmpl_path = pkg_path + '/template/supervisord_template.conf'

    if not args.encode:
        args.encode = 'utf8'

    with codecs.open(args.tmpl_path, encoding=args.encode) as fs:
        template_obj = template.Template(fs.read())

    config_json = open_conf(args.path, args.encode)
    init_config(config_json)

    data = template_obj.generate(groups=config_json.get('groups', []),
                                 servers=config_json['servers'],
                                 print_desc=args.print_desc,
                                 run_mode=config_json['run_mode'])
    save_conf(args.out_path, data, args.encode)
示例#30
0
    def create_file(self, tpl, outfile):
        t = template.Template(tpl)
        content = t.generate(
            uuid=uuid.uuid1(),  #uuid3(uuid.NAMESPACE_DNS, self.url),
            no_image=self.no_image,
            title=self.feed.feed.title,
            #subtitle = self.feed.feed.subtitle,
            logo_image=self.logo_image,
            entries=self.entries,
            max_index=self.max_index,
            #updated = time.strftime('%Y-%m-%d',self.feed.feed.updated_parsed),
            #info = self.feed.feed.info,
            #author = self.feed.feed.author
            create_time=time.strftime('%Y-%m-%d %H:%M'),
            create_date=time.strftime('%m-%d'))

        outfile = self.data_dir + outfile

        fp = open(outfile, 'wb')
        fp.write(content)
        fp.close()