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))
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)
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));
def _do_send(self, params, to, subject, template_name): # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = self.config['from'].encode('utf-8', 'ignore') msg['To'] = to # Create the body of the message (a plain-text and an HTML version). loader = Loader('./templates/mail') text = loader.load(template_name + '.txt').generate(**params) html = loader.load(template_name + '.html').generate(**params) # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. msg.attach(part1) msg.attach(part2) # sendmail function takes 3 arguments: sender's address, recipient's address # and message to send - here it is sent as one string. if self.config['dummy']: self.logger.warning( 'WARNING: Not sending e-mail to {0}, subj: {1}'.format( msg['To'], subject)) else: s = smtplib.SMTP(host=self.config['host'].encode( 'utf-8', 'ignore'), port=self.config['port']) s.starttls() s.login(self.config['login'].encode('utf-8', 'ignore'), self.config['password'].encode('utf-8', 'ignore')) s.sendmail(msg['From'], [msg['To'], msg['From']], msg.as_string()) s.quit()
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)
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()
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('*****@*****.**', 'MDM Enrollment verification', message, [user['email']], format='html') except Exception,err: print repr(err)
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)
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(), })
def get(self, path): # Caching strategy. # 1. If we don't have a version parameter, redirect curVersion = self.get_version() try: version = url_escape(self.get_argument('v')) except web.MissingArgumentError: uri = self.request.uri uri += '&' if self.request.query else '?' uri += 'v=%s' % curVersion self.redirect(uri) return # 2. Make sure version is correct if IMAGE_VERSION is not None and version != curVersion: uri = self.request.uri.replace('v=%s' % version, 'v=%s' % curVersion) self.redirect(uri) return if not path: path = 'index.html' loader = Loader(HTML_DIR) section = path.split('.')[0] try: context = getattr(self, section)() except AttributeError: context = {} context['cloud_url'] = CLOUD_HTTP_ADDRESS context['bufferSize'] = get_jack_buffer_size() context['sampleRate'] = get_jack_sample_rate() self.write(loader.load(path).generate(**context))
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')
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) try: ses_conn.send_email('*****@*****.**', 'MDM Enrollment verification', message, [user['email']], format='html') except Exception as err: print repr(err)
def get(self): loader = Loader("./") bl = db.getAvailableBanksWithMark() t = util.getFetchedTime() self.write( loader.load("index.html").generate(availableBanks=bl, fetchedTime=t))
async def get(self): reference = self.get_argument('reference', None) #if not reference: send error page feedbacks = await FeedbackService.get_all_feedback(reference) loader = Loader(self.get_template_path()) self.write( loader.load('feedback_table.html').generate(feedbacks=feedbacks, reference=reference))
def homepage(biothings, args): loader = Loader(templates.__path__[0]) template = loader.load("home.html") return template.generate(alert='Front Page Not Configured.', title='Biothings API', contents=biothings.handlers.keys(), support=biothings.metadata.types, url='http://biothings.io/')
def generate_credentials(): loader = Loader("static/auth") my_cred_file = loader.load("google_secret_format.txt") result = my_cred_file.generate().decode("utf-8") % ( conf.GOOGLE_CLIENT_ID, conf.GOOGLE_PROJECT_ID, conf.GOOGLE_CLIENT_SECRET, conf.BASE_URL + "/docs/") with open(conf.CLIENT_SECRETS_FILE, "w") as cred_json: cred_json.write(result)
class Template: def __init__(self, template_path, **kwargs): self.loader = Loader(template_path, **kwargs) def render(self, template, **kwargs): temp = self.loader.load(template) return temp.generate(**kwargs)
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")
def __init__(self, **kwargs): mandatory_args = ["username", "password", "host", "port"] for x in mandatory_args: if kwargs.get(x, False) == False: raise ValueError("%s must be provided" % (x)) self.__dict__[x] = kwargs[x] loader = Loader("templates/email") self.EMAIL_HTML_TEMPLATE = loader.load("document_send_email.html")
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 )
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)
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)
def __create_handler__(self, handler_name): loader = Loader(os.path.join(os.getcwd(), "templates", "bake")) temp_file = open( os.path.join(self.project_helper.get_handler_folder(), handler_name + self.HANDLER_QUALIFIER + '.py'), 'w') temp_file.write( loader.load("base_handler.plate").generate( handler_name=handler_name)) temp_file.close() logging.debug("[*] Finished generating " + temp_file.name)
def generate_string(self, file_template, template_values, file_values): loader = Loader(os.path.join(os.getcwd(), 'templates')) ret = loader.load(file_template, parent_path='./') try: content = ret.generate().replace(template_values, file_values) except TypeError: logging.error("template_values or file_values is not bytes.") pass else: return content
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'))
def generate_export_file(self, job_id): main_info = yield self.job_dao.query_job_base_info(job_id) if main_info['status'] not in [ type_define.STATUS_JOB_REJECTED, type_define.STATUS_JOB_COMPLETED ]: self.finish_with_error(error_codes.EC_SYS_ERROR, '%s未归档') filename = 'job_%s_%s.html' % (job_id, main_info['title'].decode('utf-8')) dir_path = 'res/download/job_export' net_path = self.get_res_file_path(filename, dir_path) file_path = self.get_res_file_path(filename, dir_path, True) if os.path.isfile(file_path): raise gen.Return([net_path, file_path, filename]) status_map = { type_define.STATUS_JOB_PROCESSING: '处理中', type_define.STATUS_JOB_COMPLETED: '已完成', type_define.STATUS_JOB_CANCEL: '已撤回', type_define.STATUS_JOB_REJECTED: '未通过', } main_info['status'] = status_map[main_info['status']] branch_id = self.get_argument('branch_id', None) node_list = yield self.job_dao.query_job_node_list(job_id, branch_id) for item in node_list: attachment_type = [ [ 'has_attachment', type_define.TYPE_JOB_ATTACHMENT_NORMAL, 'attachment' ], [ 'has_img', type_define.TYPE_JOB_ATTACHMENT_IMG, 'img_attachment' ], ] for _type in attachment_type: if item[_type[0]]: attachment = yield self.job_dao.query_node_attachment_list( item['id'], _type[1]) item[_type[2]] = attachment content = self.abstract_job_content(item['content']) content = self.html_to_text(content) item['content'] = content if node_list[0]['rec_set']: rec_set = yield self.job_dao.query_uid_set(node_list[0]['rec_set']) else: rec_set = None loader = Loader(self.get_template_path(), autoescape=None) result = loader.load('base_job_export.html').generate( rec_set=rec_set, main_info=main_info, node_list=node_list, ) fid = codecs.open(file_path, 'w', encoding='utf-8') fid.write(result.decode('utf-8')) raise gen.Return([net_path, file_path, filename])
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)
class TemplateRenderer(object): # Flask-like HTML render function, without thread local. def __init__(self, path): self.loader = TemplateLoader(path) def __call__(self, template, **data): return Response( body=self.loader.load(template).generate(**data), headers={'Content-Type': 'text/html; charset=UTF-8'}, )
async def get(self): handlers = [] for x in self.application.handlers_api: # FIXME url = x.reverse().replace('?', '') handlers.append({'name': x.name, 'url': url}) if handlers: handlers = sorted(handlers, key=lambda k: k['name']) loader = Loader('politicos_api/templates') content = loader.load('routes.html').generate(handlers=handlers) await self.write(content)
def render_template(template_name, **kwargs): global template_loader if template_loader is None or True: # XXX: enable template caching template_loader = Loader('templates') return template_loader.load(template_name).generate( **kwargs, lc = lc.get_dict(), conf = conf.configuration, comp = competition, )
class DynamicOverviewHandler(tornado.web.RequestHandler): def initialize(self, **kwargs): kwargs.update(dict(time=time.asctime())) self.loader = Loader(kwargs.get("template_path")) self.kwargs = kwargs @tornado.web.asynchronous def get(self): self.set_header("Content-Type", "application/json; charset=UTF-8") self.write(self.loader.load("index-json.js").generate(**self.kwargs)) self.finish()
def confirm_registration(self): try: print("ConfirmRegData:", self.request.data) Confirm_Data.clear_expired_rows() confirm_table = Confirm_Data() loader = Loader("templates") return loader.load("base.html").generate() return "OK" except Exception as e: raise e
def registration(self): print("ConfReg:", self.request.data) if "t" not in self.request.data: raise Exception("There is no token in request") confirm_data_table = Confirm_Data() confirm = confirm_data_table.get_data_by_token(self.request.data["t"]) if confirm is None: raise Exception("Confirm registration token not find") print("RegData:", ) loader = Loader("templates") return loader.load("base.html").generate()
def write_page(response, new_name, new_width, new_height, new_max_players, new_error): loader = Loader('templates/') page = loader.load('newgame.html').generate( app=App.instance, name=new_name, width=new_width, height=new_height, max_players=new_max_players, error=new_error) response.write(page)
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'))
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))
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']))
def run_template(filename): import os.path from tornado.template import Loader from .stats import table_rows, json_stats s = Stats(filename) loader = Loader(os.path.join(os.path.dirname(__file__), 'templates')) template = loader.load('viz.html') output = template.generate(profile_name=filename, table_rows=table_rows(s), callees=json_stats(s)) with open(filename + '.html', 'w') as f: f.write(output)
def display(self, tpl, **kwargs): #self.render(tpl, **kwargs) ''' 先用loader来实现,避免每次模板改动要重新启动服务''' try: loader = Loader(config.setting['template']) self.write(loader.load(tpl).generate(**kwargs)) except Exception, e: self.write(str(e))
class BaseView: default_loader = default_loader = Loader(os.path.join(os.path.split(os.path.abspath(__file__))[0], 'templates')) def __init__(self, loader=None): self.loader = Loader(loader) if isinstance(loader, str) else loader or BaseView.default_loader def merge_format(self, column_format1, column_format2={}): """ 合并单行的column格式(不带column名). 如果没有进行合并, 返回column_format, 否则返回一个全新的dict. """ if not column_format2: return column_format1 return dict(column_format1, **column_format2) def generate(self, template, **kwargs): return self.loader.load(template).generate(**kwargs)
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 ''
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)
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
def get(self): display_content = load_schedule() if display_content['result'] == 'fail': pass elif display_content['display_type'] == 'image': self.render('show-image.html', img_info=display_content) elif display_content['display_type'] == 'text': from tornado.template import Loader loader = Loader('template') print( loader.load('show-text.html').generate( text_info=display_content)) self.render('show-text.html', text_info=display_content) elif display_content['display_type'] == 'news': self.render('show-news.html', news_info=display_content)
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, }
def get(self, *args, **kwargs): """ view logs that are indexed into elastic search """ doc_type = self.get_query_argument('service', None) query = self.get_query_argument('query', None) context = search_log(doc_type, query) templateRoot = options.TEMPLATE_ROOT loader = Loader(templateRoot) templateName = 'logs.html' response = loader.load(templateName).generate(**context) # writeObjToResponse(self, object=context, status=200) self.write(response) self.finish()
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)
def get(self, *args, **kwargs): data = Data() data.items = '' data.cart = '' 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.leader = self.get_leader_html() for item in items: data.items += loader.load('item.html').generate( id=item.get('_id', ''), name=item.get('name', ''), comment=item.get('comment', ''), price=item.get('price', ''), leader=False ) self.render('main.html', data=data)
class PresentationAdminHandler(tornado.web.RequestHandler): def prepare(self): print "this is the controller " print dir(self.request), "\n=======", self.request.host def get(self, name,): #if not entry: raise tornado.web.HTTPError(404) r = redis.StrictRedis(host='localhost', port=6379, db=0) presentation = r.get(name) print "name : ", name, "presentation : ", presentation if presentation : dummy_poll = { "qid" : 1234 , "question" : "what species are you?", "answers" : [ {"aid" : 2, "answer" : "reptile"}, {"aid" : 22, "answer" : "lemur"}, {"aid" : 24, "answer" : "coder"}, ] } self.loader = Loader(os.path.join(os.path.dirname(__file__), "templates")) tmpl = self.loader.load("partial_poll.html") rendered_dummy_poll = tmpl.generate(poll = dummy_poll) self.render("presentation_admin.html", host=self.request.host, slug=name, presentation=presentation, poll=rendered_dummy_poll)
def run(self): log = Logger('PassVerifyerThread') tag = 'run' print 'In PassVerify\'s POST' loader = Loader("/opt/toppatch/mv/media/app/") passwd = str(self.request.get_argument('password', None)) enrollment_id = self.request.get_argument('hidden', None) log.e(tag, 'enrollment id : ' + enrollment_id) ### check type of enrollment id ### try: enrollment_id = int(enrollment_id) invalid_enrollment_id = False enrollment_id = str(enrollment_id) except ValueError: invalid_enrollment_id = True # No enrollment ID sent if enrollment_id is None or invalid_enrollment_id: # print 'Some Error in enrollID not present corresponding\ # to the password or of invalid format' log.e(tag, 'Some Error in program deviceID not present \ corresponding to the password or of invalid format') self.request.write(loader.load("error_invalid.html").generate( message='Invalid link, Mr. intruder. :D ;)', status='alert-danger')) tornado.ioloop.IOLoop.instance().add_callback(self.callback) # Password not found elif passwd is None: redirect_url = ''' /enroll/{0}?err=Try+again+with+correct+password'''.format(enrollment_id) self.request.redirect(redirect_url) log.i(tag, 'password is incorrect') tornado.ioloop.IOLoop.instance().add_callback(self.callback) # Enrollent ID and Password found else: enrollment = EnrollmentDBHelper() ret_dict = enrollment.get_enrollment(enrollment_id) # print ret_dict ret = None if ret_dict is not None: ret = str(ret_dict[c.ENROLLMENT_TABLE_PASSWORD]) else: log.e(tag, 'Enrollment password cannot be reterived') if ret is None: log.e( tag, 'DB did not sent the password from Enrollment table') self.request.write(loader.load("error_invalid.html").generate( message='Invalid link, Mr. intruder. :D ;)', status='alert-danger')) tornado.ioloop.IOLoop.instance().add_callback(self.callback) else: # Password matched if ret == passwd: print 'download the profile' # Now find out the browser details # Create the profile to download thread = CreateProfileThread(enrollment_id) thread.start() thread.join() filename = enrollment_id + '.mobileconfig' signed_filename = 'mdm_' + enrollment_id + '.mobileconfig' log.i(tag, 'Downloading the iOS profile') log.i(tag, 'Signing the iOS profile') sign_command = """ openssl smime \ -sign \ -signer /etc/ssl/star_toppatch_com.pem \ -inkey /etc/ssl/star_toppatch_com.key \ -certfile /opt/toppatch/assets/ios/DigiCertPersonal_chain.pem \ -nodetach \ -outform der \ -in {0} \ -out {1} """.format(filename, signed_filename) os.system(sign_command) f = file(signed_filename, 'rb') self.request.set_header( 'Content-Type', 'application/x-apple-aspen-config; chatset=utf-8') self.request.set_header( 'Content-Disposition', 'attachment; filename=' + filename + '') self.request.write(f.read()) tornado.ioloop.IOLoop.instance().add_callback( self.callback) # Delete the file from server after download 'Delay can be # introduced'. os.remove(filename) os.remove(signed_filename) else: redirect_url = ''' /enroll/{0}?err=Try+again+with+correct+password'''.format(enrollment_id) self.request.redirect(redirect_url) tornado.ioloop.IOLoop.instance().add_callback( self.callback) log.i(tag, 'Incorrect Password for enrollment')
def get(self, *args, **kwargs): _fields = ["client_id", "redirect_uri", "state", "scope", "response_type"] _request_dict = {} for _field in _fields: _request_dict[_field] = self.get_query_argument(_field, default=None) if _request_dict.get("response_type") != "code": logging.error("response_type not code") self.send_error(501) return if _request_dict.get("client_id") == None: logging.error("no client_id") self.send_error(400) return _redis = self.application.redis _key = ApiInfo.__tablename__ + ".api_key." + _request_dict.get("client_id") _api = _redis.get(_key) if _api == None: logging.error("no api_key:%s" % _request_dict.get("client_id")) self.send_error(404) return _api = json.loads(_api) _app_uuid = _api[0] _api_uuid = _api[1] _api_level = _api[2] _api_code = str(uuid.uuid1()) _api_code = hashlib.sha1(_api_code).hexdigest() _api_code = base64.b64encode(_api_code) _api_token = str(uuid.uuid1()) _api_token = hashlib.sha1(_api_token).hexdigest() _api_token = base64.b64encode(_api_token) _row = ApiTokenData(uuid=str(uuid.uuid1()), api_code=_api_code, api_token=_api_token, app_uuid=_app_uuid, api_uuid=_api_uuid, api_level=_api_level) _row.async_add(_redis) _row.create_redis_keys(_redis) if _request_dict.get("redirect_uri") != None: loader = Loader(os.path.abspath(os.path.dirname(__file__)) + "/static/templates") login_form = loader.load("login_form.html").generate(**{ "state": _request_dict.get("state"), "redirect_uri": _request_dict.get("redirect_uri"), "token_data_uuid": _row.uuid }) self.write(login_form) return if _request_dict.get("redirect_uri") == None: self.set_header("Content-Type", "application/json") self._header() _return = { "state": _request_dict.get("state"), "code": _row.api_code, } self.write(json.dumps(_return)) return return
def get(self): loader = Loader("./"); self.write(loader.load("index.html").generate());
def get(self): files = file_manager.getAllFiles(); loader = Loader("./"); self.write(loader.load("file_list.html").generate(files=files));
async def get(self): loader = Loader('politicos_api/templates') await self.write(loader.load('developers.html').generate())