本文整理汇总了Python中tornado.template.Loader类的典型用法代码示例。如果您正苦于以下问题:Python Loader类的具体用法?Python Loader怎么用?Python Loader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Loader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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))
示例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__)
示例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));
示例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)
示例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()
示例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)
示例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)
示例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']))
示例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 ''
示例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,
}
示例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
示例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(),
})
示例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)
示例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)