• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python template.Loader类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: watch_redis

def watch_redis(channel, from_address):
    global email_connection

    redis_pool = redis.ConnectionPool()
    conn = redis.StrictRedis(connection_pool=redis_pool)
    pubsub = conn.pubsub()
    pubsub.subscribe(channel)

    for message in pubsub.listen():
        notifier.logger.info(message["data"])
        try:
            message_items = json.loads(message["data"])
        except ValueError:
            notifier.logger.warn("Not a JSON object.")
            continue
        except Exception as e:
            notifier.logger.error(str(e))
            continue

        template_name = message_items.get("template_name", "default")
        if re.search(INVALID_NAME_REGEX, template_name):
            notifier.logger.error("Invalid template name.")
            continue

        subject = message_items.get("subject", "TopPatch Alert!")
        to_addresses = message_items.get("to_addresses", [])
        message_keys = message_items.get("message_keys", [])

        # use templates for both text and HTML
        loader = Loader(TEMPLATE_DIR)
        text_body = loader.load(template_name + ".txt").generate(message_items=message_keys)
        html_body = loader.load(template_name + ".html").generate(message_items=message_keys)

        email_connection.send(from_address, to_addresses, subject, text_body, html_body)
开发者ID:j-lowry,项目名称:vFense,代码行数:34,代码来源:notifierd.py


示例2: get

 def get(self, *args, **kwargs):
     page = int(self.get_query_argument("page", 1))
     nav_type = 2
     hint = "To be continued"
     if page < 1 or page > 10:
         page = 1
     if page == 1:
         nav_type = 1
     if page == 10:
         hint = "EOF"
         nav_type = -1
     loader = Loader(settings.APP_SETTINGS["template_path"])
     article_item_t = loader.load("article_item.html")
     article_item_htmls = []
     for i in range(1, page + 1):
         article_item_htmls.append(escape.json_encode(article_item_t.generate(
             title="This is the title",
             author="Cyandev",
             pub_date="Jul. 16, 2010",
             preview="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
             tag="Fusion",
             id=i
         )))
     self.set_header('Content-Type', 'text/plain')
     self.write(loader.load("fetch_articles.js").generate(htmls=article_item_htmls, hint=hint, nav_type=nav_type, page=page))
开发者ID:unixzii,项目名称:Cyanstack,代码行数:25,代码来源:handlers.py


示例3: gen_db_model

    def gen_db_model(self, schema_name, table_name):
        sql = """ SELECT column_name, column_default, data_type, column_key, is_nullable,
                         character_maximum_length, column_comment
                  FROM information_schema.columns
                  WHERE TABLE_SCHEMA = :schema_name AND
                        TABLE_NAME = :table_name
                  ORDER BY ORDINAL_POSITION"""

        with self.create_session(self._default_db) as session:
            entities = session.execute(sql, dict(schema_name=schema_name, table_name=table_name))
            metas = [GenMeta(entity) for entity in entities if entity[0] != 'pkid']
            model_meta = DbModelMeta()
            model_meta.table_metas = metas
            for meta in metas:
                if model_meta.has_id is False:
                    model_meta.has_id = meta.column_name == 'id'
                    model_meta.is_string_id = meta.column_name == 'id' and \
                                              u'varchar' == meta.data_type
                if model_meta.has_created_at is False:
                    model_meta.has_created_at = meta.column_name == 'created_at'
                if model_meta.has_updated_at is False:
                    model_meta.has_updated_at = meta.column_name == 'updated_at'
                if model_meta.has_is_deleted is False:
                    model_meta.has_is_deleted = meta.column_name == 'is_deleted'
            model_meta.class_name = inflection.singularize(inflection.camelize(table_name))

            template_path = os.path.join(os.path.dirname(__file__))
            t = Loader(template_path, **{}).load('model.tpl')
            print t.generate(**model_meta.__dict__)
开发者ID:yl812708519,项目名称:tornado_test_web,代码行数:29,代码来源:database_gen.py


示例4: get

    def get(self):
        loader = Loader("./");
        bankName = self.get_argument("bank_name");
        state = self.get_argument("state");
        page = int(self.get_argument("page", "1"));
        city = self.get_argument("city", "all");
        whereDict = dict();

        if bankName != "all":
            whereDict[BankTable.COL_NAME] = bankName;
        
        if state == "all":
            pass
        elif state == "accepted":
            whereDict[BankTable.COL_ACCEPTED] = BankTable.FLAG_ACCEPTED;
        elif state == "unaccepted":
            whereDict[BankTable.COL_ACCEPTED] = BankTable.FLAG_UNACCEPTED;
        else:
            raise Exception("postponed option has deprecated!");

        allBanks = db.getBankList(whereDict, city);
        if self.get_argument("isOption", "false") == "true":
            cities = self.extractCities(db.getBankList(whereDict));
            self.write(loader.load("option.html").generate(activedCity=city, cities=cities));
            return;

        banks = allBanks[(page - 1)*settings.PAGE_COUNT: page*settings.PAGE_COUNT];
        pageCount = len(allBanks)/settings.PAGE_COUNT;
        if pageCount*settings.PAGE_COUNT < len(allBanks):
            pageCount += 1;
        
        pages = self.buildPages(page, pageCount);
        self.write(loader.load("table.html").generate(banks=banks, pages=pages, activePage=page, pageCount=pageCount));
开发者ID:ufo22940268,项目名称:PromotionScrachServer,代码行数:33,代码来源:server.py


示例5: users_added_callback

    def users_added_callback(self,users):
        '''
        Server url will be dynamic to work same code on different servers
        in case on user enrollment and iOS profile generation also.
        '''
        loader = Loader("/opt/toppatch/mv/media/app/")
        server_url = environ.get('SERVER_CNAME')
        ses_conn = ses.connect_to_region('us-east-1',
                    aws_access_key_id=environ.get('AWS_SES_ACCESS_KEY_ID'),
                    aws_secret_access_key=environ.get(
                        'AWS_SES_SECRET_ACCESS_KEY'))
        for user in users:

            link = str(server_url) + '/enroll/'+str(user.get('enrollment_id'))
            message = loader.load('user_enroll_mail.html').generate(
                        company_name=user.get('company_name'),
                    user_passwd=user.get('passcode'), activation_link=link)
            # message  = 'Your verification \
            #             link is : {0} and enrollment password is {1} . To ensure \
            #             your device os please open this link in your device \
            #             browser only. :)'.format(
            #                 str(server_url) + '/enroll/'+str(user['enrollment_id']), user['passcode'])
            #message  = message.replace('  ', '')

            try:
                ses_conn.send_email('[email protected]',
                        'MDM Enrollment verification', message,
                         [user['email']], format='html')
            except Exception,err:
                print repr(err)
开发者ID:aman-gautam,项目名称:mv-server,代码行数:30,代码来源:batch_insert.py


示例6: get

 def get(self, *args, **kwargs):
     """
     provide details of cpu and memory usage
     """
     context = {
         'cpu': {
             'user': psutil.cpu_times_percent().user,
             'system': psutil.cpu_times_percent().system,
             'idle': psutil.cpu_times_percent().idle,
             'iowait': psutil.cpu_times_percent().iowait,
             'usage': psutil.cpu_percent()
         },
         'memory': {
             'percent': psutil.virtual_memory().percent,
             'total': psutil.virtual_memory().total,
             'available': psutil.virtual_memory().available,
             'used': psutil.virtual_memory().used,
             'free': psutil.virtual_memory().free,
             'cached': psutil.virtual_memory().cached
         }
     }
     templateRoot = options.TEMPLATE_ROOT
     loader = Loader(templateRoot)
     templateName = 'stats.html'
     response = loader.load(templateName).generate(**context)
     self.write(response)
     self.finish()
开发者ID:lavish205,项目名称:logaggregator,代码行数:27,代码来源:api.py


示例7: send_confirmation

def send_confirmation(user):
    if user.unsubscribed:
        return
    
    loader = Loader('templates/mail')
    text = loader.load('confirm.txt').generate(user=user, config=config.web)
    html = loader.load('confirm.html').generate(user=user, config=config.web)
    
    send(user.email, 'Confirmation instructions', text=text, html=html)
开发者ID:mgway,项目名称:skillbook,代码行数:9,代码来源:mail.py


示例8: run

    def run(self):
        # log = Logger('ActivationWorkerThread')
        # TAG = 'run'
        print 'ActivationWorkerThread'

        ### load html file for rendering ####
        loader = Loader("/opt/toppatch/mv/media/app/")
        t_status = 'alert-danger'

        if self.hash_url:

            salt_key = environ.get('salt_key')
            json_url_key = environ.get('json_url_key')

            danger_signer = TimedJSONWebSignatureSerializer(json_url_key)

            try:
                data_dict = danger_signer.loads(self.hash_url, salt=salt_key)

                company_data = data_dict.get('cmd_hash')
                admin_data = data_dict.get('adm_hash')

                if company_data and admin_data:

                    admin = LoginDBHelper()

                    company_id = company_data
                    admin_id = admin_data
                    status = admin.set_login(admin_id, company_id)

                    if status:
                        message = '''Success! Please visit \
                    https://demo-mdm.toppatch.com and login using your admin \
                    email as username and password used at the time of \
                    Registration.
                        '''
                        message = message.replace('  ', '')
                        t_status = 'alert-success'
                    else:
                        message = "Mr. Intruder U r failed in this attemps.!!!"
                else:
                    message = "Mr. Intruder U r failed in this attemps.!!!"

            except SignatureExpired:
                message = 'Sorry! This link was already expired'

            except BadSignature:
                message = '''Thanks for visiting . Please try agian after \
                          some time to activate the link sent to you.'''

        else:
            message = 'Sorry! This link was already expired'

        self.request.write(loader.load("error_invalid.html").generate(
            message=message, status=t_status))
        tornado.ioloop.IOLoop.instance().add_callback(self.callback)
开发者ID:mobile-vault,项目名称:mv-server,代码行数:56,代码来源:admin_activate.py


示例9: get

    def get(self):
        loader = Loader("../templates")

        api = SDApi(
            URL,
            USERNAME,
            PASSWORD,
            API_KEY
        )

        alerts = api.alerts.getLast()
        devices = api.devices.list()
        self.write(loader.load("index.html").generate(devices=devices['data']['devices'], alerts=alerts['data']['alerts']))
开发者ID:tomwardill,项目名称:Density-Pi,代码行数:13,代码来源:main.py


示例10: get_leader_html

 def get_leader_html(self):
     data = Data()
     leader = data.db.items.find_one(dict(leader={'$exists': True}))
     loader = Loader(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'templates'))
     try:
         return loader.load('item.html').generate(
             id=leader.get('_id', ''),
             name=leader.get('name', ''),
             comment=leader.get('comment', ''),
             price=leader.get('price', ''),
             leader=True
         )
     except TypeError:
         return ''
开发者ID:pupizoid,项目名称:Clothes,代码行数:14,代码来源:webserver.py


示例11: load

def load(**kwargs):
    loader = Loader("skin/guardian")

    def header(title=None):
        return loader.load("header.html").generate(
            static_url=kwargs.get("static_url", None),
            title=title or "",
            stylesheets=kwargs["stylesheets"],
            ).decode("utf-8")
    footer = loader.load("footer.html").generate().decode("utf-8")

    return {
        "header": header,
        "footer": footer,
    }
开发者ID:ianmackinnon,项目名称:mango,代码行数:15,代码来源:__init__.py


示例12: get_cart_html

 def get_cart_html(self):
     data = Data()
     html = ''
     cart = data.db.cart.find_one(dict(_id=self.session.id))
     loader = Loader(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'templates'))
     try:
         items = {r['_id']: r for r in
                  data.db.items.find({'_id': {'$in': map(lambda x: ObjectId(x), cart['iids'])}})}
     except TypeError:
         items = {}
     html += loader.load('cart.html').generate(
         items=items.values(),
         total_price=reduce(lambda res, x: res + int(x['price']), items.values(), 0)
     )
     return html
开发者ID:pupizoid,项目名称:Clothes,代码行数:15,代码来源:webserver.py


示例13: __init__

    def __init__(self):
        self.db = pymongo.Connection(port=settings.DB_PORT)[settings.DB_NAME]
        self.fs = GridFS(self.db)
        self.loader = Loader(
            os.path.join(ROOT_DIR, 'template'),
            autoescape=None,
            namespace={
                'static_url': lambda url: StaticFileHandler.make_static_url({'static_path': STATIC_DIR}, url),
                '_modules': ObjectDict({'Template': lambda template, **kwargs: self.loader.load(template).generate(**kwargs)}),
            },
        )

        router = TornadioRouter(ScribeConnection)
        router.app = self
        socketio = TornadoApplication(router.urls, app=self)
        self.connections = []

        class FooResource(Resource):
            def __call__(self, request):
                socketio(request)

            def __getitem__(self, name):
                return self

        Application.__init__(self, {
            '': HomeResource(self),
            'favicon.ico': StaticFileResource(os.path.join(STATIC_DIR, 'img', 'favicon.ico')),
            'sounds': EditsResource(self),
            'static': StaticFileResource(STATIC_DIR),
            'socket.io': FooResource(),
        })
开发者ID:alekstorm,项目名称:scribe,代码行数:31,代码来源:scribe.py


示例14: get

 def get(self):
     data = Data()
     loader = Loader(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'templates'))
     items = data.db.items.find()
     data.cart_html = self.get_cart_html()
     data.cart_count = data.db.cart.find(dict(_id=self.session.id)).count()
     data.items = ''
     for item in items:
         data.items += loader.load('item.html').generate(
             id=item['_id'],
             name=item['name'],
             comment=item.get('comment', ''),
             price=item['price'],
             leader=False
         )
     self.render('catalogue.html', data=data)
开发者ID:pupizoid,项目名称:Clothes,代码行数:16,代码来源:webserver.py


示例15: __init__

    def __init__(self):
        self.db = pymongo.Connection(port=settings.DB_PORT)[settings.DB_NAME]
        self.loader = Loader(
            os.path.join(ROOT_DIR, 'template'),
            autoescape=None,
            namespace={
                'static_url': lambda url: tornado.web.StaticFileHandler.make_static_url({'static_path': STATIC_DIR}, url),
                '_modules': ObjectDict({'Template': lambda template, **kwargs: self.loader.load(template).generate(**kwargs)}),
            },
        )

        Application.__init__(self, {
            '': HomeResource(self),
            'static': StaticDirectoryResource(STATIC_DIR),
            #'favicon.ico': StaticFileResource(os.path.join(STATIC_DIR, 'favicon.ico')),
            'search': EtsyProductSearchResource(self),
            'scene': SceneContainerResource(self),
            'examples': DictResource({
                'decor': StaticFileResource(os.path.join(HTML_DIR, 'example-decor.html')),
                'outfit': StaticFileResource(os.path.join(HTML_DIR, 'example-outfit.html')),
            }),
        })

        self.etsy = None
        self.etsy = yield gen.Task(EtsyV2, api_key=settings.ETSY_KEYSTRING, env=etsy.env.ProductionEnv)
开发者ID:alekstorm,项目名称:etscene,代码行数:25,代码来源:etscene.py


示例16: TornadoRenderer

class TornadoRenderer(TemplateRenderer):
    """
    Renders Tornado templates.

    :param package_path: if given, looks up the directory containing the given package and fills in
        the ``root_directory`` argument for :class:`~tornado.template.Loader`. The value will be
        interpreted by :func:`~asphalt.templating.util.package_to_directory`.
    :param loader_args: extra arguments to pass to :class:`~tornado.template.Loader`
    """

    __slots__ = 'loader'

    def __init__(self, package_path: str = None, **loader_args):
        assert check_argument_types()
        if package_path:
            loader_args.setdefault('root_directory', package_to_directory(package_path))

        self.loader = Loader(**loader_args)

    def render(self, template: str, **vars) -> str:
        template = self.loader.load(template)
        return template.generate(**vars).decode('utf-8')

    def render_string(self, source: str, **vars) -> str:
        template = Template(source)
        return template.generate(**vars).decode('utf-8')
开发者ID:asphalt-framework,项目名称:asphalt-templating,代码行数:26,代码来源:tornado.py


示例17: create_files

 def create_files(self):
     self.loader = Loader(os.path.join(os.getcwd(),"templates"))
     
     for template, file_name in self.templates:
         temp_file = open(os.path.join(os.getcwd(), self.project_name, file_name), 'w')
         temp_file.write(self.loader.load(template+".plate").generate(project_name=self.project_name))
         temp_file.close()
         logging.debug("[*] Finished generating " + template + " Template!") 
开发者ID:hathcox,项目名称:Fujd-Desktop,代码行数:8,代码来源:Chef.py


示例18: __init__

 def __init__(self, CoreObj):
     self.Core = CoreObj  # Keep Reference to Core Object
     self.Init = False
     self.Sanitiser = sanitiser.HTMLSanitiser()
     self.Loader = Loader(
         self.Core.Config.FrameworkConfigGet('POUTPUT_TEMPLATES_DIR'))
     self.mNumLinesToShow = 15
     self.CounterList = []
开发者ID:0day29,项目名称:owtf,代码行数:8,代码来源:reporter.py


示例19: __init__

class GmailEmailTemplate:
	
	@inject.param( "templateFolder", bindto="bitpostage/templates" )
	def __init__( self, templateFolder ):
		self.loader = Loader( templateFolder )
	
	def generate( self, template, args ):
		return self.loader.load( template ).generate( **args )
开发者ID:streed,项目名称:bitPostage,代码行数:8,代码来源:GmailSmtp.py


示例20: TemplateLoaderTest

class TemplateLoaderTest(unittest.TestCase):
    def setUp(self):
        self.loader = Loader(os.path.join(os.path.dirname(__file__), "templates"))

    def test_utf8_in_file(self):
        tmpl = self.loader.load("utf8.html")
        result = tmpl.generate()
        self.assertEqual(to_unicode(result).strip(), u"H\u00e9llo")
开发者ID:102hailan,项目名称:tornado,代码行数:8,代码来源:template_test.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python template.Template类代码示例发布时间:2022-05-27
下一篇:
Python template.DictLoader类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap