import odoo import odoo.modules.registry from odoo.tools.misc import str2bool, xlwt from odoo import http from odoo.http import content_disposition, dispatch_rpc, request, \ serialize_exception as _serialize_exception from odoo.exceptions import AccessError _logger = logging.getLogger(__name__) #---------------------------------------------------------- # OpenERP Web web Controllers #---------------------------------------------------------- path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'views')) loader = jinja2.FileSystemLoader(path) env = jinja2.Environment(loader=loader, autoescape=True) env.filters["json"] = json.dumps db_monodb = http.db_monodb class Home(Home): @http.route('/web/login', type='http', auth="none") def web_login(self, redirect=None, **kw): cr = request.cr uid = odoo.SUPERUSER_ID param_obj = request.env['ir.config_parameter'] request.params['disable_footer'] = ast.literal_eval( param_obj.get_param('login_form_disable_footer')) or False
"when": when, }) df = pd.DataFrame(rows) # Number of inbound requests (data-review?) by steward inbound = ( df.query("action == 'request'").groupby("steward").size().sort_values( ascending=False).reset_index(name="requests").to_dict("records")) # Number of granted requests (data-review+) by steward granted = ( df.query("action == 'granted'").groupby("steward").size().sort_values( ascending=False).reset_index(name="granted").to_dict("records")) # Number of data-review requests by requestor requestors = ( df.query("action == 'request'").groupby("requestor").size().reset_index( name="requests").sort_values(["requests", "requestor"], ascending=[False, True]).to_dict("records")) env = jinja2.Environment(loader=jinja2.FileSystemLoader(".")) result = env.get_template("template.html").render( inbound=inbound, granted=granted, requestors=requestors, last_updated=dt.utcnow().isoformat(), ) pathlib.Path("result.html").write_text(result)
""" import cgi import logging import os import random import re import json import jinja2 import webapp2 import threading from google.appengine.api import channel from google.appengine.ext import db jinja_environment = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__))) # Lock for syncing DB operation in concurrent requests handling. # TODO(brave): keeping working on improving performance with thread syncing. # One possible method for near future is to reduce the message caching. LOCK = threading.RLock() def generate_random(length): word = '' for _ in range(length): word += random.choice('0123456789') return word def sanitize(key):
def templates_reset(self): """ This function is called by env.reset() to reset the XML template contents based on Config.lanes_busyness and Config.lanes_busyness_mode :return: None. Just reset the templates. """ # ---------------------------------------------------------------------------- # # 2 : R A N D O M L Y I N I T I A L I Z E X M L s # ---------------------------------------------------------------------------- # new_stance = dict() # This is the dict passed to jinja # 2.2: Init Emergency Start Lane new_stance['ambulance_start_lane'] = random.randint(0, num_lanes-1) new_stance['all_agents_start_position'] = random.randint(41, 250) # TODO: Edit minimum position to depend on starting position new_stance['r1_new_length'] = new_stance['all_agents_start_position'] new_stance['r2_new_length'] = 511 - new_stance['all_agents_start_position'] new_stance['agent_min_gap'] = 2.5 # default new_stance['ambulance_min_gap'] = 2.5 # default new_stance['car_length'] = 2.0 new_stance['agents_data_dicts'] = [] distance_to_finish = self.amb_goal_dist - 10 - 1 - new_stance['all_agents_start_position'] # 10 = self.emer.max_speed max_cars_per_lane = np.floor( distance_to_finish/ # According to this distance (changes in every reset) (new_stance['agent_min_gap'] + new_stance['car_length'] + 5 )) # 5 because it is the max agent velocity #TODO: Do we have to add 5 ? self.max_possible_cars = max_cars_per_lane for lane in range(num_lanes): # [0, 1, 2] for num_lanes = 3 # ------------------------------------------------------------------- # # 1 : C A R S A T E Q U A L D I S T A N C E S # ------------------------------------------------------------------- # if lanes_busyness_mode == 0: # i.e. place cars at equal distances cars_in_this_lane = int(max_cars_per_lane * lanes_busyness[lane]) agent_index = 0 distance_between_cars = distance_to_finish/cars_in_this_lane for car in range(cars_in_this_lane): temp_dict = dict() # agent_data temporary dict to be stored in new_stance['agents_data_dicts'] temp_dict['agent_id'] = self.create_vehicle_id(lane, agent_index) # "RB_" + "L" + str(lane) + "I" + str(agent_index) # 2.1: Init Agent Start Lane temp_dict['agent_start_lane'] = lane # 2.3: Init Agent Start Position temp_dict['departPos'] = distance_to_finish - agent_index * distance_between_cars # random.randint(0, 511 - new_stance['all_agents_start_position']) # distance infront of all_agents_start_position new_stance['agents_data_dicts'].append(temp_dict) agent_index += 1 vehicles_data[lane] = agent_index # number of cars in this lane # ------------------------------------------------------------------- # # 2 : C A R S P R O D U C E D W I T H P R O B A B I L I T Y # ------------------------------------------------------------------- # elif lanes_busyness_mode == 1: # i.e. place cars at equal distances # cars_in_this_lane = int(max_cars_per_lane * lanes_busyness[lane]) agent_index = 0 real_agent_index = 0 # That gets updated only if we actually add the vehicle min_distance_between_cars =(new_stance['agent_min_gap'] # According to this distance (changes in every reset) + new_stance['car_length'] + 5 ) for car in range(int(max_cars_per_lane)): temp_dict = dict() # agent_data temporary dict to be stored in new_stance['agents_data_dicts'] temp_dict['agent_id'] = self.create_vehicle_id(lane, real_agent_index) # "RB_" + "L" + str(lane) + "I" + str(real_agent_index) # 2.1: Init Agent Start Lane temp_dict['agent_start_lane'] = lane # 2.3: Init Agent Start Position temp_dict['departPos'] = distance_to_finish - agent_index * min_distance_between_cars # random.randint(0, 511 - new_stance['all_agents_start_position']) # distance infront of all_agents_start_position # Do we add this car ? add_this_car = random.random() if add_this_car < lanes_busyness[lane]: new_stance['agents_data_dicts'].append(temp_dict) real_agent_index += 1 agent_index += 1 vehicles_data[lane] = real_agent_index # number of cars in this lane # for agent_index in range(int(max_cars_per_lane)): # temp_dict = dict() # agent_data temporary dict to be stored in new_stance['agents_data_dicts'] # # temp_dict['agent_id'] = agent_index # # # 2.1: Init Agent Start Lane # temp_dict['agent_start_lane'] = random.randint(0, num_lanes-1) # # # 2.3: Init Agent Start Position # temp_dict['departPos'] = random.randint(0, 511 - new_stance['all_agents_start_position']) # distance infront of all_agents_start_position # # new_stance['agents_data_dicts'].append(temp_dict) # 2.4: Load Template to template templateLoader = jinja2.FileSystemLoader(searchpath=TEMPLATES_PATH) templateEnv = jinja2.Environment(loader=templateLoader) # 2.5: Put rou template to file rou_template = templateEnv.get_template("route_template.xml") with open(ROUTE_FILE_PATH, "w") as fp: fp.writelines(rou_template.render(data=new_stance)) # 2.6: Put net template to file: net_template = templateEnv.get_template("net_template.xml") with open(NET_FILE_PATH, "w") as fp: fp.writelines(net_template.render(data=new_stance))
import jinja2.exceptions # Import salt libs import salt.utils import salt.utils.templates import salt.utils.validate.net import salt.ext.six as six from salt.ext.six.moves import StringIO # Set up logging log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'rh_ip') ) ) # Define the module's virtual name __virtualname__ = 'ip' def __virtual__(): ''' Confine this module to RHEL/Fedora based distros ''' if __grains__['os_family'] == 'RedHat': return __virtualname__ return False
def render(tpl_path, context): path, filename = os.path.split(tpl_path) return jinja2.Environment( loader=jinja2.FileSystemLoader(path or './') ).get_template(filename).render(context)
import markdown import jinja2 import os from os.path import splitext TEMPLATE_FILE = "word.html" markdown_files = os.listdir('markdown') for file in markdown_files: with open("markdown/%s" % file) as f: content = f.read() title = ' '.join(word.title() for word in file[:-3].split('-')) md = markdown.markdown(content, extensions=['codehilite']) template_loader = jinja2.FileSystemLoader(searchpath="templates") template_env = jinja2.Environment(loader=template_loader) template = template_env.get_template(TEMPLATE_FILE) output = template.render(title=title, content=md) html_filename = splitext(file)[0] + '.html' with open('words/%s' % html_filename, 'w+') as f: f.write(output)
#!/usr/bin/env python import jinja2 import sys import os import subprocess commitHash = subprocess.check_output(['git','rev-parse', 'HEAD']).decode('utf-8')[:-1] templateLoader = jinja2.FileSystemLoader(searchpath="./") templateEnv = jinja2.Environment(loader=templateLoader) templates = [ "advisor/index.html", "advisor/courseplan.html", "catalog/index.html", "labs/index.html", "collections/index.html", "collections/view.html", 'index.html' ] for template_file in templates: template = templateEnv.get_template(template_file) outputText = template.render(antidote_version=commitHash, env=os.environ) path = "../src/%s" % template_file # Needs to be written to be python3 compatible, or we need to ensure this is always called with python2 try: os.makedirs(os.path.dirname(path)) except OSError: pass
def makeZoneFile(self, zone, outfile=None): r = None # sort the record list by record name if it exists for record in zone['records']: if record['name'] == zone['name'] and record['type'] == 'NS': break else: zone['records'].append({ 'name': zone['name'], 'type': 'NS', 'value': self.default_ns }) zone['records'] = sorted(zone['records'], key=lambda k: k['name']) # Split and format TXT records for record in zone['records']: if record['type'] == 'TXT': old_value = record['value'] record['value'] = [] for v in old_value: if v.startswith('"'): record['value'].append(v) else: for start in range(0, len(v), 254): record['value'].append('"' + v[start:start + 254] + '"') if 'soa' not in zone: zone['soa'] = self.default_soa if outfile and os.path.exists(outfile): zf = dns.zone.from_file(outfile, origin=zone['name']) serial = zf.find_rrset(zone['name'] + '.', dns.rdatatype.SOA).items[0].serial else: serial = 1 j2 = jinja2.Environment(loader=jinja2.FileSystemLoader( os.path.dirname(os.path.abspath(self.zone_template))), trim_blocks=True, lstrip_blocks=True) r = j2.get_template(os.path.basename(self.zone_template)).render( zone=zone, serial=self.increaseSerial(serial)) # Ensure that the zone can be understood by dnspython dns.zone.from_text(r, origin=zone['name']) if outfile and r: if os.path.exists(outfile): with open(outfile, 'r') as f: contents = f.read() changed = len( set(r.splitlines()).symmetric_difference( set(contents.splitlines()))) > 2 else: changed = True if changed: self.log.info('writing zone file to {0}'.format(outfile)) with open(outfile, 'w') as f: f.write(r) else: self.log.debug('not writing zone file to {0}'.format(outfile)) return r
def set_directories(self, directories, cache_folder): """Create a template lookup.""" if pyjade is None: req_missing(['pyjade'], 'use this theme') self.lookup.loader = jinja2.FileSystemLoader(directories, encoding='utf-8')
import time from collections import OrderedDict import jinja2 import shutil from homeassistant.util.yaml import Secrets, loader from homeassistant.exceptions import HomeAssistantError from .const import DOMAIN, VERSION _LOGGER = logging.getLogger(__name__) def fromjson(value): return json.loads(value) jinja = jinja2.Environment(loader=jinja2.FileSystemLoader("/")) jinja.filters['fromjson'] = fromjson dwains_dashboard_config = {} dwains_dashboard_translations = {} dwains_dashboard_icons = {} dwains_dashboard_global = {} dwains_dashboard_customize = {} llgen_config = {} LANGUAGES = { "English": "en", "Danish": "da", "German": "de", "Spanish": "es",
_PATH_SUMMARY_TABLE = 'path_summary_table' _CHANNEL_COUNTS_TABLE = 'channel_counts_table' _REPORT_TABLE = 'report_table' _CONVERSIONS_BY_CUSTOMER_ID_TABLE = 'ConversionsByCustomerId' _SESSIONS_BY_CUSTOMER_ID_TABLE = 'SessionsByCustomerId' _PATH_TRANSFORMS_MAP = { 'unique': 'Unique', 'exposure': 'Exposure', 'first': 'First', 'frequency': 'Frequency' } _REPORT_TABLE_PARTITION_EXP_MS = 7776000000 # 90 days VALID_CHANNEL_NAME_PATTERN = re.compile(r'^[a-zA-Z_]\w+$', re.ASCII) env = jinja2.Environment(loader=jinja2.FileSystemLoader( os.path.join(os.path.dirname(__file__), 'templates'))) def _strip_sql(sql: str) -> str: """Returns a copy of sql with empty lines and -- comments stripped. Args: sql: A SQL string. Returns: A copy of sql with empty lines and -- comments removed. """ lines = [] for line in sql.split('\n'): line = re.sub(r'\s*--.*', '', line) if line.strip(): lines.append(line)
# it with the next line. The STIG has terrible formatting in some # places. monospace_strings = ['grep', 'more'] if (key + 1 < len(paragraphs) and any(x in value for x in monospace_strings) and '\n' not in value and not paragraphs[key + 1].startswith('Password')): value = "{0}\n{1}".format( value, '\n '.join(paragraphs[key + 1].split('\n'))) del (paragraphs[key + 1]) return '\n\n'.join(paragraphs) JINJA_ENV = jinja2.Environment( loader=jinja2.FileSystemLoader(METADATA_DIR), trim_blocks=True, keep_trailing_newline=False, ) JINJA_ENV.filters['addmonospace'] = add_monospace def element_flatten(element): """Flatten the element into a single item if it's a single item list.""" # If there's only one result in the list, then return that single result. if isinstance(element, list) and len(element) == 1: return element[0] else: return element
"""Custom configurations for Google App Engine.""" from config import PATHS from google.appengine.api import app_identity from google.appengine.ext import vendor import jinja2 import os import xsrf ROOT = os.path.dirname(__file__) JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader(ROOT), extensions=['jinja2.ext.autoescape', 'jinja2.ext.i18n'], autoescape=True) JINJA_ENVIRONMENT.globals['xsrf_token'] = xsrf.XSRFToken() HOST = str(app_identity.get_default_version_hostname()) JINJA_ENVIRONMENT.globals['BASE_URL'] = ('https://' + HOST) JINJA_ENVIRONMENT.globals['EMAIL_VALIDATION_PATTERN'] = r'[^@]+@[^@]+.[^@]+' email_validation_error = 'Please supply a valid email address.' JINJA_ENVIRONMENT.globals['EMAIL_VALIDATION_ERROR'] = email_validation_error # Key lookup for users and group allows email or unique id. key_lookup_pattern = r'([^@]+@[^@]+.[^@]+|[a-zA-Z0-9]+)' key_lookup_error = 'Please supply a valid email address or unique id.' JINJA_ENVIRONMENT.globals['KEY_LOOKUP_VALIDATION_PATTERN'] = key_lookup_pattern JINJA_ENVIRONMENT.globals['KEY_LOOKUP_VALIDATION_ERROR'] = key_lookup_error
one of the coldest permanently inhabited locales on the planet. """ PLAIN_TEXT_AGENTS = [ "curl", "httpie", "lwp-request", "wget", "python-requests" ] if not os.path.exists(os.path.dirname(LOG_FILE)): os.makedirs(os.path.dirname(LOG_FILE)) logging.basicConfig(filename=LOG_FILE, level=logging.DEBUG) reader = geoip2.database.Reader(GEOLITE) geolocator = Nominatim() my_loader = jinja2.ChoiceLoader([ app.jinja_loader, jinja2.FileSystemLoader(TEMPLATES), ]) app.jinja_loader = my_loader class Limits: def __init__(self): self.intervals = ['min', 'hour', 'day'] self.divisor = { 'min': 60, 'hour': 3600, 'day': 86400, } self.counter = { 'min': {}, 'hour': {},
import os import re import webapp2 import jinja2 from google.appengine.ext import db template_dir = os.path.join(os.path.dirname(__file__), 'templates') jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), autoescape=True) def render_str(template, **params): t = jinja_env.get_template(template) return t.render(params) class BlogHandler(webapp2.RequestHandler): def write(self, *a, **kw): self.response.out.write(*a, **kw) def render_str(self, template, **params): t = jinja_env.get_template(template) return t.render(params) def render(self, template, **kw): self.write(self.render_str(template, **kw)) def render_post(response, post):
from webapp2_extras.routes import PathPrefixRoute sys.path.append(os.path.join(os.path.dirname(__file__), 'pylib')) from url import getAllLocalesTranslationsHtml from url import checkPath sys.path.append(os.path.join(os.path.dirname(__file__), 'common/pylib')) from localeUtil import getLocale from localeUtil import parseAcceptLanguage from misc import isDevServer from misc import isTrack import i18n jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader([ os.path.join(os.path.dirname(__file__), 'app'), os.path.join(os.path.dirname(__file__), 'app/css'), os.path.join(os.path.dirname(__file__), 'app/partials') ]), extensions=['jinja2.ext.i18n'], variable_start_string='{$', variable_end_string='$}') jinja_environment.install_gettext_translations(i18n) def getCommonTemplateValues(self, urlLocale, userLocale): i18n.setLocale(userLocale) template_values = { 'htmlTitle': u'', 'userLocale':
def make_html_files(self): """ make up HTML structure to read the content """ env = jinja2.Environment(loader=jinja2.FileSystemLoader( str(self.templates_dir)), autoescape=True) # build homepage html = env.get_template("home.html").render( debug=str(self.debug).lower(), title=self.title, description=self.description, main_color=self.main_color, secondary_color=self.secondary_color, db_name=f"{self.name}_{self.period}_{uuid.uuid4().hex}_db", db_version=1, nb_items_per_page=self.nb_items_per_page, show_author=self.show_author, show_description=self.show_description, randomize=self.randomize, search_label=_("Search"), search_input_label=_("Keywords…"), close_label=_("Close"), loading_label=_("Loading…"), no_result_text=_("No result for this search request."), backtotop_label=_("Back to Top"), secondary_logo=self.secondary_logo, about_label=_("About this content"), about_content=self.about_content, ) with open(self.build_dir.joinpath("home.html"), "w", encoding="utf-8") as fp: fp.write(html) initjs = env.get_template("init.js").render( debug=str(self.debug).lower(), title=self.title, description=self.description, db_name=f"{self.name}_{self.period}_{uuid.uuid4().hex}_db", db_version=1, nb_items_per_page=self.nb_items_per_page, show_author=self.show_author, show_description=self.show_description, randomize=self.randomize, loading_label=_("Loading…"), ) with open(self.build_dir.joinpath("init.js"), "w", encoding="utf-8") as fp: fp.write(initjs) with open(self.build_dir.joinpath("database.js"), "w", encoding="utf-8") as fp: fp.write("var DATABASE = [\n") for docid, document in enumerate(self.json_collection): fp.write("{},\n".format( str({ "_id": str(docid).zfill(5), "ti": document.get("title") or "Unknown?", "dsc": document.get("description") or "", "aut": document.get("authors") or "", "fp": document.get("files", []), }))) fp.write("];\n")
__author__ = 'christopher' import sys, os, csv, jinja2 data = [line for line in csv.DictReader(open(sys.argv[1], 'rb'))] # Change the default delimiters used by Jinja such that it won't pick up # brackets attached to LaTeX macros. report_renderer = jinja2.Environment( block_start_string = '%{', block_end_string = '%}', variable_start_string = '%{{', variable_end_string = '%}}', loader = jinja2.FileSystemLoader(os.path.abspath('.')) ) template = report_renderer.get_template('report_template.tex') output = file(sys.argv[2], 'w') output.write(template.render(data = data)) output.close()
def main(): parser = argparse.ArgumentParser( description="Optimize HandShape keyboard switch placement") parser.add_argument("--npasses", default=2, type=int, help="Number of optimization passes") parser.add_argument( "--niter", default=100, type=int, help= "Consider the result optimal when it has been stable for this many iterations" ) parser.add_argument( "--fingers", nargs="*", default=["PINKY", "RING", "MIDDLE", "INDEX"], help= "The fingers to optimize (a list of [PINKY, RING, MIDDLLE, and/or INDEX)" ) parser.add_argument( "--save", type=argparse.FileType("wb"), help= "Save the optimization result to a file, can be loaded later to skip the optimization step" ) parser.add_argument( "--load", type=argparse.FileType("rb"), help= "Load the optimization result from a file, this skips the optimization step" ) args = parser.parse_args() if args.load: optimization_results = pickle.load(args.load) finger_names = list(optimization_results.keys()) variables = load_variables(finger_names) else: finger_names = args.fingers variables = load_variables(finger_names) optimization_results = dict() for finger_name in finger_names: print("Calculating %s" % finger_name) finger_dimensions = np.array(variables["%s_FINGER" % finger_name]) finger_pos = np.array(variables["%s_POS" % finger_name]) lengths = np.concatenate((finger_pos[0:1], finger_dimensions[:, 0])) result = optimize_switches(lengths, 3, args.npasses, args.niter) optimization_results[finger_name] = result if args.save: pickle.dump(optimization_results, args.save) for finger_name in finger_names: print("Result for %s" % finger_name) print_result(optimization_results[finger_name]) current_finger = "INDEX" r = optimization_results[current_finger] finger_dimensions = np.array(variables["%s_FINGER" % current_finger]) finger_pos = np.array(variables["%s_POS" % current_finger]) lengths = np.concatenate((finger_pos[0:1], finger_dimensions[:, 0])) template_loader = jinja2.FileSystemLoader(searchpath="./") template_env = jinja2.Environment(loader=template_loader) template = template_env.get_template("keyboard.template") switch_to_press = r.switches[2] hand = { "palm_angle": switch_to_press.finger_angles[0], "pinky": { "angle": np.full(3, 0), }, "ring": { "angle": np.full(3, 0), }, "middle": { "angle": np.full(3, 0), }, "index": { "angle": np.full(3, 0), } } hand["index"]["angle"] = get_finger_angles(switch_to_press) keys = [[s.switch_position[0], s.switch_position[1], -s.switch_angle] for s in r.switches] with open("keyboard.scad", "w") as output_file: output_file.write(template.render(hand=hand, keys=json.dumps(keys)))
def start(self): self.connection_dir = tempfile.mkdtemp( prefix='voila_', dir=self.connection_dir_root ) self.log.info('Storing connection files in %s.' % self.connection_dir) self.log.info('Serving static files from %s.' % self.static_root) self.kernel_spec_manager = KernelSpecManager( parent=self ) self.kernel_manager = AsyncMappingKernelManager( parent=self, connection_dir=self.connection_dir, kernel_spec_manager=self.kernel_spec_manager, allowed_message_types=[ 'comm_open', 'comm_close', 'comm_msg', 'comm_info_request', 'kernel_info_request', 'shutdown_request' ] ) jenv_opt = {"autoescape": True} # we might want extra options via cmd line like notebook server env = jinja2.Environment(loader=jinja2.FileSystemLoader(self.template_paths), extensions=['jinja2.ext.i18n'], **jenv_opt) nbui = gettext.translation('nbui', localedir=os.path.join(ROOT, 'i18n'), fallback=True) env.install_gettext_translations(nbui, newstyle=False) self.contents_manager = LargeFileManager(parent=self) # we create a config manager that load both the serverconfig and nbconfig (classical notebook) read_config_path = [os.path.join(p, 'serverconfig') for p in jupyter_config_path()] read_config_path += [os.path.join(p, 'nbconfig') for p in jupyter_config_path()] self.config_manager = ConfigManager(parent=self, read_config_path=read_config_path) # default server_url to base_url self.server_url = self.server_url or self.base_url self.app = tornado.web.Application( base_url=self.base_url, server_url=self.server_url or self.base_url, kernel_manager=self.kernel_manager, kernel_spec_manager=self.kernel_spec_manager, allow_remote_access=True, autoreload=self.autoreload, voila_jinja2_env=env, jinja2_env=env, static_path='/', server_root_dir='/', contents_manager=self.contents_manager, config_manager=self.config_manager ) self.app.settings.update(self.tornado_settings) handlers = [] handlers.extend([ (url_path_join(self.server_url, r'/api/kernels/%s' % _kernel_id_regex), KernelHandler), (url_path_join(self.server_url, r'/api/kernels/%s/channels' % _kernel_id_regex), ZMQChannelsHandler), ( url_path_join(self.server_url, r'/voila/static/(.*)'), MultiStaticFileHandler, { 'paths': self.static_paths, 'default_filename': 'index.html' } ) ]) # Serving notebook extensions if self.voila_configuration.enable_nbextensions: handlers.append( ( url_path_join(self.server_url, r'/voila/nbextensions/(.*)'), FileFindHandler, { 'path': self.nbextensions_path, 'no_cache_paths': ['/'], # don't cache anything in nbextensions }, ) ) handlers.append( ( url_path_join(self.server_url, r'/voila/files/(.*)'), WhiteListFileHandler, { 'whitelist': self.voila_configuration.file_whitelist, 'blacklist': self.voila_configuration.file_blacklist, 'path': self.root_dir, }, ) ) tree_handler_conf = { 'voila_configuration': self.voila_configuration } if self.notebook_path: handlers.append(( url_path_join(self.server_url, r'/(.*)'), VoilaHandler, { 'notebook_path': os.path.relpath(self.notebook_path, self.root_dir), 'nbconvert_template_paths': self.nbconvert_template_paths, 'config': self.config, 'voila_configuration': self.voila_configuration } )) else: self.log.debug('serving directory: %r', self.root_dir) handlers.extend([ (self.server_url, VoilaTreeHandler, tree_handler_conf), (url_path_join(self.server_url, r'/voila/tree' + path_regex), VoilaTreeHandler, tree_handler_conf), (url_path_join(self.server_url, r'/voila/render/(.*)'), VoilaHandler, { 'nbconvert_template_paths': self.nbconvert_template_paths, 'config': self.config, 'voila_configuration': self.voila_configuration }), ]) self.app.add_handlers('.*$', handlers) self.listen()
2. DEBUG indicates that it is a dev environment, you'll get the very helpful error page from flask when an error occurs. 3. SECRET_KEY will be used to sign cookies. Change it and all your users will have to login again. 4. ADMINS will be used if you need to email information to the site administrators. 5. SQLALCHEMY_DATABASE_URI and DATABASE_CONNECT_OPTIONS are SQLAlchemy connection options (hard to guess) 6. THREADS_PER_PAGE my understanding was 2/core... might be wrong :) 7. CSRF_ENABLED and CSRF_SESSION_KEY are protecting against form post fraud 8. RECAPTCHA_* WTForms comes with a RecaptchaField ready to use... just need to go to recaptcha website and get your public and private key. """ # Base directory _basedir = os.path.abspath(os.path.dirname(__file__)) # Template directory template_dir = _basedir + '/templates/' loader = jinja2.FileSystemLoader(template_dir) environment = jinja2.Environment(loader=loader) DEBUG = False ADMINS = frozenset(['*****@*****.**']) SECRET_KEY = os.urandom(24) # SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(_basedir, 'app.db') UH_DB_USER = os.getenv('UH_DB_USER', 'GuessMyName') UH_DB_PASSWORD = os.getenv('UH_DB_PASSWORD', 'GuessMyPassword') UH_DB_ADDRESS = os.getenv('UH_DB_ADDRESS', 'GuessMyAddress') # this includes hostname:port SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://' + UH_DB_USER + ':' + UH_DB_PASSWORD + '@' + UH_DB_ADDRESS + '/flask_demo_db' DATABASE_CONNECT_OPTIONS = {}
import webapp2 import jinja2 import logging import os import webbrowser from google.appengine.api import users from google.appengine.ext import ndb from google.appengine.api import urlfetch import api import database import time jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader( os.path.dirname(__file__)), extensions=['jinja2.ext.autoescape'], autoescape=True) # @ndb.transactional def readfromDatabase(): response_html = jinja_env.get_template('templates/checklist.html') user = users.get_current_user() logging.info('current user is %s' % (user.nickname())) values = { "wantsList": database.DatabaseEntry.query( database.DatabaseEntry.type == "want", database.DatabaseEntry.username == user.nickname()).fetch(), "needsList": database.DatabaseEntry.query(
from admin.controllers.base import BaseHandler from sharelib.utils import DateTime from datalayer.models.models import User, Buy, Agent import os import jinja2 import json JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), '../../views')), extensions=['jinja2.ext.autoescape'] ) class BuyTransaction(BaseHandler): def get(self): # validate admin is logined or not # if not redirect to login page if self.authenticate() == False: return current_user = self.current_user() users = User.query().fetch() template_values = { 'title': 'Buy Transaction', 'today': DateTime.to_date_string(DateTime.malaysia_today()), 'current_user': current_user, 'users': users, }
import re import random import hashlib import hmac from string import letters import logging import json import webapp2 import jinja2 import time from google.appengine.ext import db from google.appengine.api import memcache template_dir = os.path.join(os.path.dirname(__file__), 'templates') jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), autoescape=False) jinja_env_escaped = jinja2.Environment( loader=jinja2.FileSystemLoader(template_dir), autoescape=True) #password hash using salt def make_salt(length=5): return ''.join(random.choice(letters) for x in range(length)) def make_pw_hash(name, pw, salt=None): if not salt: salt = make_salt() h = hashlib.sha256(name + pw + salt).hexdigest() return '%s,%s' % (salt, h)
# Execute for step in step_list: try: step.execute() except subprocess.CalledProcessError: break # Log to command line for step in step_list: print("Step %s: %s" % (step.name, step.pretty_status)) if step.return_code != 0 and step.return_code is not None: print step.output # Log to on-disk output template_loader = jinja2.FileSystemLoader(searchpath=REPORT_TEMPLATE_DIR) template_env = jinja2.Environment(loader=template_loader) template = template_env.get_template("synchronize-template.html") with open(REPORT_OUTPUT_FILE, "w") as f: f.write( template.render(lastrun_date=datetime.datetime.now(), steps=step_list).encode("utf-8")) # Log through e-mail template = template_env.get_template("synchronize-email-template.txt") email_message = template.render(sender=EMAIL_SENDER_LINE, receiver=EMAIL_RECEIVER_ADDRESSES, lastrun_date=datetime.datetime.now(), steps=step_list) try: smtp = smtplib.SMTP(EMAIL_SERVER)
# import webapp2 import cgi import datetime import jinja2 import os import json from google.appengine.api import mail from google.appengine.ext import db import google.appengine.ext.db from google.appengine.api import users JINJA_ENVIRONMENT = jinja2.Environment(loader=jinja2.FileSystemLoader( os.path.dirname(__file__)), extensions=['jinja2.ext.autoescape'], autoescape=True) measurementOrder = ["chest", "shoulder", "length"] sizeOrder = ["XS", "S", "M", "L", "XL"] class User(db.Expando): userid = db.StringProperty() name = db.StringProperty() email = db.EmailProperty() chest = db.IntegerProperty() shoulder = db.IntegerProperty() length = db.IntegerProperty()
# docker_image_base=f"{DOCKER_REGISTRY}/pytorch/pytorch-linux-xenial-py3-clang5-android-ndk-r19c", # ), # PyTorchLinuxWorkflow( # build_environment="pytorch-linux-xenial-py3.6-clang5-mobile", # docker_image_base=f"{DOCKER_REGISTRY}/pytorch/pytorch-linux-xenial-py3-clang5-asan", # ), # PyTorchLinuxWorkflow( # build_environment="pytorch-linux-xenial-py3.6-clang5-mobile-custom-dynamic", # docker_image_base=f"{DOCKER_REGISTRY}/pytorch/pytorch-linux-xenial-py3-clang5-android-ndk-r19c", # ), # PyTorchLinuxWorkflow( # build_environment="pytorch-linux-xenial-py3.6-clang5-mobile-custom-static", # docker_image_base=f"{DOCKER_REGISTRY}/pytorch/pytorch-linux-xenial-py3-clang5-android-ndk-r19c", # ), # PyTorchLinuxWorkflow( # build_environment="pytorch-linux-xenial-py3.6-clang5-mobile-code-analysis", # docker_image_base=f"{DOCKER_REGISTRY}/pytorch/pytorch-linux-xenial-py3-clang5-android-ndk-r19c", # ), ] if __name__ == "__main__": jinja_env = jinja2.Environment( variable_start_string="!{{", loader=jinja2.FileSystemLoader(str(GITHUB_DIR.joinpath("templates"))), ) workflow_template = jinja_env.get_template("linux_ci_workflow.yml.in") for workflow in WORKFLOWS: print( workflow.generate_workflow_file( workflow_template=workflow_template, jinja_env=jinja_env))
pattern = pattern[1:] pattern = pattern[1:] regexp += ']' else: regexp += re.escape(pattern[0]) pattern = pattern[1:] regexp += "$" return re.compile(regexp, re.I) # Used by render. environment = jinja2.Environment(loader=jinja2.FileSystemLoader(plat.path(''))) def render(always, template, dest, **kwargs): """ Using jinja2, render `template` to the filename `dest`, supplying the keyword arguments as template parameters. """ dest = plat.path(dest) if (not always) and os.path.exists(dest): return template = environment.get_template(template) text = template.render(**kwargs)
import os import webapp2 import jinja2 from google.appengine.api import users import logging #Jinja Loader template_env = jinja2.Environment( loader=jinja2.FileSystemLoader(os.getcwd())) class NavigationHandler(webapp2.RequestHandler): def get(self): url = str(self.request.url) strRouter = url.split("/") strRouter = strRouter[len(strRouter) - 1] if strRouter == "header": template = template_env.get_template('templates/dynamic/navigation/header.html') context = {} self.response.write(template.render(context)) elif strRouter == "sidebar": template = template_env.get_template('templates/dynamic/navigation/sidebar.html') context = {} self.response.write(template.render(context)) elif strRouter == "footer": template = template_env.get_template('templates/dynamic/navigation/footer.html') context = {}