本文整理汇总了Python中tornado.template.Loader.load方法的典型用法代码示例。如果您正苦于以下问题:Python Loader.load方法的具体用法?Python Loader.load怎么用?Python Loader.load使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tornado.template.Loader
的用法示例。
在下文中一共展示了Loader.load方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: watch_redis
# 需要导入模块: from tornado.template import Loader [as 别名]
# 或者: from tornado.template.Loader import load [as 别名]
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)
示例2: get
# 需要导入模块: from tornado.template import Loader [as 别名]
# 或者: from tornado.template.Loader import load [as 别名]
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))
示例3: get
# 需要导入模块: from tornado.template import Loader [as 别名]
# 或者: from tornado.template.Loader import load [as 别名]
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));
示例4: send_confirmation
# 需要导入模块: from tornado.template import Loader [as 别名]
# 或者: from tornado.template.Loader import load [as 别名]
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)
示例5: ScribeApplication
# 需要导入模块: from tornado.template import Loader [as 别名]
# 或者: from tornado.template.Loader import load [as 别名]
class ScribeApplication(Application):
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(),
})
示例6: get
# 需要导入模块: from tornado.template import Loader [as 别名]
# 或者: from tornado.template.Loader import load [as 别名]
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()
示例7: users_added_callback
# 需要导入模块: from tornado.template import Loader [as 别名]
# 或者: from tornado.template.Loader import load [as 别名]
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)
示例8: TornadoRenderer
# 需要导入模块: from tornado.template import Loader [as 别名]
# 或者: from tornado.template.Loader import load [as 别名]
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')
示例9: EtsceneApplication
# 需要导入模块: from tornado.template import Loader [as 别名]
# 或者: from tornado.template.Loader import load [as 别名]
class EtsceneApplication(Application):
@gen.engine
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)
示例10: TemplateLoaderTest
# 需要导入模块: from tornado.template import Loader [as 别名]
# 或者: from tornado.template.Loader import load [as 别名]
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")
示例11: __init__
# 需要导入模块: from tornado.template import Loader [as 别名]
# 或者: from tornado.template.Loader import load [as 别名]
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 )
示例12: send_alert
# 需要导入模块: from tornado.template import Loader [as 别名]
# 或者: from tornado.template.Loader import load [as 别名]
def send_alert(user_id, alert, alert_value):
user = db.get_email_attributes(user_id)
if user.unsubscribed:
return
alert.email_description = alert.email_description.replace('REPLACE_TRIGGER', str(alert.option_1_value))
alert.email_description = alert.email_description.replace('REPLACE_ACTUAL', str(alert_value))
if int(alert.interval) > 1440:
alert.interval = "%d day(s)" % (int(alert.interval)/1440) # minutes to days
else:
alert.interval = "%d hour(s)" % (int(alert.interval)/60) # minutes to hours
loader = Loader('templates/mail')
text = loader.load('alert.txt').generate(user=user, alert=alert, config=config.web)
html = loader.load('alert.html').generate(user=user, alert=alert, config=config.web)
send(user.email, 'Character alert: ' + alert.name , text=text, html=html)
示例13: run
# 需要导入模块: from tornado.template import Loader [as 别名]
# 或者: from tornado.template.Loader import load [as 别名]
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)
示例14: get
# 需要导入模块: from tornado.template import Loader [as 别名]
# 或者: from tornado.template.Loader import load [as 别名]
def get(self, data):
log = Logger('CheckInHandler Get')
tag = 'Profile get method'
user_agent = self.request.headers['User-Agent']
if 'iPad' in user_agent or 'iPhone OS' in user_agent:
loader = Loader("/opt/toppatch/mv/media/app/")
self.write(loader.load("enroll_form.html").generate(temp_enroll=data))
elif 'Android' in user_agent:
self.redirect('/android_profile.apk')
log.i(tag,'Downloading the Android APK')
else:
log.i(tag,'Incorrect browser used in passverify')
loader = Loader("/opt/toppatch/mv/media/app/")
self.write(loader.load("error_invalid.html").generate(
message='Please use Android or iOS device to open this link',
status='alert-danger'))
示例15: parse_install_operation_data
# 需要导入模块: from tornado.template import Loader [as 别名]
# 或者: from tornado.template.Loader import load [as 别名]
def parse_install_operation_data(oper_data, oper_type, oper_plugin, threshold):
try:
loader = Loader(TEMPLATE_DIR)
subject = 'TopPatch Alert'
if oper_plugin == RV_PLUGIN:
if oper_type == INSTALL or oper_type == UNINSTALL:
if threshold == 'fail':
message = 'Operation %s Failed' % (oper_type.capitalize())
msg_body = (
loader.load('apps_install.html')
.generate(message_items=oper_data, message=message)
)
elif threshold == 'pass':
message = 'Operation %s Passed' % (oper_type.capitalize())
msg_body = (
loader.load('apps_install.html')
.generate(message_items=oper_data, message=message)
)
elif oper_plugin == CORE_PLUGIN:
if oper_type == REBOOT or oper_type == SHUTDOWN:
if threshold == 'fail':
message = 'Operation %s Failed' % (oper_type.capitalize())
msg_body = (
loader.load('agent_base.html')
.generate(message_items=oper_data, message=message)
)
elif threshold == 'pass':
message = 'Operation %s Passed' % (oper_type.capitalize())
msg_body = (
loader.load('agent_base.html')
.generate(message_items=oper_data, message=message)
)
return(subject, msg_body)
except Exception as e:
logger.exception(e)