import jinja2 from oslo_config import cfg from oslo_log import log as logging import six import webob from werkzeug import exceptions from octavia.common import constants as consts from octavia.common import exceptions as octavia_exceptions from octavia.common import utils CONF = cfg.CONF LOG = logging.getLogger(__name__) j2_env = jinja2.Environment(autoescape=True, loader=jinja2.FileSystemLoader( os.path.dirname(os.path.realpath(__file__)) + consts.AGENT_API_TEMPLATES)) class BaseOS(object): PACKAGE_NAME_MAP = {} def __init__(self, os_name): self.os_name = os_name @classmethod def _get_subclasses(cls): for subclass in cls.__subclasses__(): for sc in subclass._get_subclasses(): yield sc yield subclass
import webapp2 import jinja2 import os from google.appengine.ext import ndb env = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__))) class Message(ndb.Model): content = ndb.StringProperty("content") created_time = ndb.DateTimeProperty(auto_now_add=True) class Home(webapp2.RequestHandler): def get(self): messages = Message.query().order(-Message.created_time).fetch() templateVars = {'messages': messages} template = env.get_template("templates/home.html") self.response.write(template.render(templateVars)) def post(self): content = self.request.get('content') message = Message() message.content = content message.put() app = webapp2.WSGIApplication([ ("/", Home),
s = '' for d in os.environ: s += "<pre><p>" + str(d).rjust(28) + " | " + str( os.environ[d]) + "</p></pre>" return s main.urls += [ "/test", "Test", ] application = web.application(main.urls, globals()) store = MemcacheStore(memcache) session = web.session.Session(application, store, initializer={ 'username': '', 'login': 0, "lang": '' }) jjenv = jinja2.Environment(loader=jinja2.FileSystemLoader('templates'), extensions=["jinja2.ext.do", 'jinja2.ext.i18n']) jjenv.filters['filesizeformat'] = fix_filesizeformat app = application.wsgifunc() web.config.debug = IsRunInLocal main.session = session main.jjenv = jjenv
from flask import Flask, request, redirect, render_template import cgi import os import jinja2 template_dir = os.path.join(os.path.dirname(__file__), 'templates') jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape=True) app = Flask(__name__) app.config['DEBUG'] = True @app.route("/") def index(): return render_template('home.html') @app.route("/validate", methods=['POST']) def validate(): username = request.form['username'] password = request.form['password'] verify_password = request.form['verify_password'] email = request.form['email'] error_check = False username_error = '' password_error = '' verify_password_error = '' email_error = ''
return mc def parse_args(): parser = argparse.ArgumentParser(description='MQtt Radar by adrian.brzezinski (at) adrb.pl') parser.add_argument('-c', '--config', help='Yaml config file', default='config.yaml') parser.add_argument('-d', '--debug', help='Set debugging level', action='count') return parser.parse_args() if __name__ == '__main__': args = parse_args() DEBUG = args.debug # Initialize jinja2 templating J2ENV = jinja2.Environment(loader=jinja2.FileSystemLoader(os.getcwd()), trim_blocks=True) J2ENV.filters['b64decode'] = base64.b64decode J2ENV.filters['b64encode'] = base64.b64encode J2ENV.filters['remove_punctation'] = filter_remove_punctation J2ENV.filters['pathescape'] = filter_pathescape # Load config file try: with open(args.config, 'r') as f: CONFIG = yaml.load(f) except IOError as e: print("ERROR: %s (%s) - %s" % (e.strerror, e.errno, e.filename)) sys.exit(1) # Initialize mqtt connection
'https://i.kym-cdn.com/entries/icons/mobile/000/023/732/damngina.jpg', 'https://i.imgflip.com/7m181.jpg', 'https://i.kym-cdn.com/entries/icons/original/000/027/475/Screen_Shot_2018-10-25_at_11.02.15_AM.png', 'https://i.kym-cdn.com/entries/icons/original/000/024/062/jerry.jpg', 'https://www.dailydot.com/wp-content/uploads/2019/03/Unsettled_Tom.jpg', 'https://i.redd.it/9qivj9l5mdb31.jpg', 'https://video-images.vice.com/articles/5ae37ca3d7a39f000a7328ad/lede/1524858049454-Screen_Shot_2018-03-28_at_113259_AM.jpeg?crop=0.5625xw%3A1xh%3Bcenter%2Ccenter&resize=650%3A*&output-quality=55', 'https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/mocking-spongebob-1556133078.jpg', 'https://mondrian.mashable.com/uploads%252Fcard%252Fimage%252F748607%252F73afa0f3-7ef2-4a95-9384-d882abd6b684.png%252F950x534__filters%253Aquality%252880%2529.png?signature=Sg4DErLyhoUELvQhvVxjV60xPsc=&source=https%3A%2F%2Fblueprint-api-production.s3.amazonaws.com', 'http://thinkingmeme.com/wp-content/uploads/2018/02/Roll-Safe-Think-About-It.jpg', 'https://media2.giphy.com/media/9JmaNq2uwAab01xKIV/giphy.gif', 'https://media0.giphy.com/media/l1taVz9esdyGNiUVi/giphy.gif' ] jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader( os.path.dirname(__file__)), extensions=['jinja2.ext.autoescape'], autoescape=True) class MainPage(webapp2.RequestHandler): def get(self): index_template = jinja_env.get_template('templates/index.html') self.response.write(index_template.render()) class MemePage(webapp2.RequestHandler): def post(self): lines = self.request.get('line[]', allow_multiple=True) template_ctx = { "bg_image": random.choice(memeBackgrounds), "lines": lines
import jinja2 jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader('template')) jinja_var = {'users': ['User 1', 'User 2', 'User 3']} template = jinja_env.get_template('layout.html') print(template.render(jinja_var))
'Mitigations': 'Mitigations', 'ThirdPartyTools': 'Third Party Tools', 'Responsibility': 'Responsibility', 'PotentialImpacts': 'Potential Impacts', 'FalsePositives': 'False Positives', 'Documentable': 'Documentable' } if uglyname in prettynames: return prettynames[uglyname] else: return uglyname # Get Jinja configured properly jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(SCRIPT_DIR)) jinja_env.filters['prettydesc'] = description_tag_prettify # Read in the giant XCCDF file with open("{0}/{1}".format(SCRIPT_DIR, XCCDF_FILE), 'r') as f: tree = etree.parse(f) # Set our default namespace for this XML document namespaces = {'x': 'http://checklists.nist.gov/xccdf/1.1'} # Get the document title/version title = tree.xpath("/x:Benchmark/x:title", namespaces=namespaces)[0].text version = tree.xpath("/x:Benchmark/x:plain-text", namespaces=namespaces)[0].text # Loop through the groups and extract information about rules
node['ipv4'] = elem['ipv4'] except socket.error: # IPv4 is not numeric, let's try resolving try: print "RESOLVING", elem['ipv4'] node['ipv4'] = socket.gethostbyname(elem['ipv4']) except socket.error: print "Could not resolve ipv4: %s, skipping!" % elem['ipv4'] continue if 'status_udp' in elem and elem['status_udp']: nodes.append(node) if 'tcp_ports' in elem and elem['tcp_ports'] and \ 'status_tcp' in elem and elem['status_tcp']: for port in elem['tcp_ports']: relay = dict(node) try: relay['port'] = int(port) except ValueError: continue tcp_relays.append(relay) env = jinja2.Environment(loader=Loader()) env.filters['toxtoc'] = toxtoc template = env.get_template('tox_bootstrap_template') tox_bootstrap_h = template.render(nodes=nodes, now=datetime.datetime.now(), json_url=json_url, relays=tcp_relays) open('tox_bootstrap.h', 'w').write(tox_bootstrap_h)
import copy import glob import jinja2 import jinja2.ext import os import shutil import subprocess import yaml import json import sys import generatehelpers # For list.append in Jinja templates Jinja2 = jinja2.Environment(loader=jinja2.FileSystemLoader(searchpath="."), extensions=['jinja2.ext.do']) def populate(filename, config, delimiter, overwrite=False): fragments = glob.glob(os.path.join('oqs-template', filename, '*.fragment')) if overwrite == True: source_file = os.path.join('oqs-template', filename, os.path.basename(filename) + '.base') contents = generatehelpers.file_get_contents(source_file) else: contents = generatehelpers.file_get_contents(filename) for fragment in fragments: identifier = os.path.splitext(os.path.basename(fragment))[0] if filename == 'README.md':
import os from markdown2 import markdown import jinja2 as j import shutil print(os.getcwd()) env = j.Environment(loader=j.FileSystemLoader("templates")) template = env.get_template("test.html") recipe_template = env.get_template("recipe.html") table_template = env.get_template("table.html") imgpath = "./recipes-ssg/img" for bla in os.listdir(imgpath): shutil.copyfile(os.path.join(os.getcwd() + imgpath, bla), os.path.join("./img/", bla)) src = open("recipes-ssg/a.md", "r") base = open("myrecipes/index.html", "w") #title = markdown("#"+"welcome to my recipe site!") mdpath = "./recipes-ssg/mds" f = list() f2 = list() for md in os.listdir(os.path.join(mdpath + "/recipes")): f.append(markdown(open(os.path.join(mdpath + "/recipes/" + md)).read()))
import os import jinja2 import webapp2 from handlers import BaseHandler from models import User JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader( [os.path.join(os.path.dirname(__file__),"../../templates/users"), os.path.join(os.path.dirname(__file__),"../../templates/layouts")])) TEMPLATE = JINJA_ENVIRONMENT.get_template('set_password.html') class SetPasswordHandler(BaseHandler.BaseHandler): def get(self, email_endpoint): if not self.legacy: self.redirect("/#/users/set_password") if self.session.get('user'): del self.session['user'] if self.session.get('role'): del self.session['role'] template_values = { "message": self.request.get("message"), "form": User.UserConfirmationForm(), "email_endpoint": email_endpoint } language = None if "language" in self.request.cookies:
'phsen': { 'module': 'mi.instrument.sunburst.sami2_ph.ooicore.driver', 'klass': 'InstrumentDriver' }, 'ppsdn': { 'module': 'mi.instrument.mclane.ras.ppsdn.driver', 'klass': 'InstrumentDriver' }, 'rasfl': { 'module': 'mi.instrument.mclane.ras.rasfl.driver', 'klass': 'InstrumentDriver' } } loader = jinja2.FileSystemLoader(searchpath="templates") env = jinja2.Environment(loader=loader, trim_blocks=True, lstrip_blocks=True) super_template = env.get_template('driver_supervisor.jinja') def create_tc_dict(csv_file): tc_dict = {} with open(csv_file) as fh: for row in DictReader(fh): name = create_tc_name(row) inst_name = row['instrument'] if name is not None: tc_dict[name] = row tc_dict[name].update(instruments[inst_name]) return tc_dict
def jinja2(self): return jinja2.Environment(loader=jinja2.FileSystemLoader( os.path.dirname(__file__) + '/templates'), extensions=['jinja2.ext.autoescape'], autoescape=True)
from flask import Flask, request, redirect import helpers from caesar import encrypt import cgi import os import jinja2 template_dir = os.path.join(os.path.dirname(__file__), 'templates') jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir)) app = Flask(__name__) app.config['DEBUG'] = True @app.route("/") def index(): template = jinja_env.get_template('form.html') return template.render() @app.route("/", methods=['POST']) def caesar(): rot = int(request.form.get('rot', 0)) text = request.form.get('text', '') encryptedText = encrypt(text, rot) template = jinja_env.get_template('form.html') return template.render(text=encryptedText) app.run()
try: return jinja2.Markup.escape(jinja_loader.get_source(env, name)[0]) except Exception as e: logging.exception(e) # include the literal (unescaped) contents of a file def include_file_raw(name): try: return jinja2.Markup(jinja_loader.get_source(env, name)[0]) except Exception as e: logging.exception(e) env = jinja2.Environment( loader=jinja_loader, extensions=['jinja2.ext.autoescape'], autoescape=True, trim_blocks=True, variable_start_string='{{{', variable_end_string='}}}') env.globals['include_file'] = include_file env.globals['include_file_raw'] = include_file_raw # memcache logic: maintain a separate cache for each explicit # app version, so staged versions of the docs can have new nav # structures, redirects without affecting other deployed docs. # CURRENT_VERSION_ID format is version.hash, where version is the # app version passed to the deploy script. MEMCACHE_PREFIX = 'no_version/' if 'CURRENT_VERSION_ID' in os.environ: MEMCACHE_PREFIX = os.environ.get('CURRENT_VERSION_ID').split('.')[0] + '/'
), "Map": ( lambda reader: f"new Gson().getAdapter(Map.class).read({reader})", lambda writer, value: f"new Gson().getAdapter(Map.class).write({writer}, {value})", ), "Object": ( lambda reader: f"new Gson().getAdapter(Object.class).read({reader})", lambda writer, value: f"new Gson().getAdapter(Object.class).write({writer}, {value})", ), } env = jinja2.Environment( loader=jinja2.PackageLoader("codegen", "templates"), trim_blocks=True, lstrip_blocks=True, ) adapter = env.get_template("./adapter.java") builder = env.get_template("./builder.java") adapters = nativeTypes all_classes = set() root = sys.argv[1] def walk(clazz): with open(f"{root}/{clazz}.java") as source: ast = javalang.parse.parse("\n".join(source.readlines()))
import os import re from datetime import datetime import six import jinja2 import sphinx.quickstart env = jinja2.Environment() __here__ = os.path.dirname(os.path.abspath(__file__)) def render(to_render, settings): if isinstance(to_render, six.string_types): return env.from_string(to_render).render(settings) else: with open(os.path.join(__here__, *to_render)) as template_file: return env.from_string(template_file.read()).render(settings) def create_plugin(plugins_dir, plugin, **settings): assert ' ' not in plugin, "plugins probably shouldn't have spaces; but either way we aren't specifically handling spaces" module = plugin.replace('-', '_') plugin = plugin.replace('_', '-') settings.update({ 'plugin': plugin, 'module': module, 'generated_date': datetime.utcnow() })
subprocess.check_call( [sys.executable, "-m", "virtualenv", env_path]) print("Installing `jinja2` into bootstrap environment...") subprocess.check_call([join(bin_path, "pip"), "install", "jinja2"]) python_executable = join(bin_path, "python") if not os.path.samefile(python_executable, sys.executable): print("Re-executing with: {0}".format(python_executable)) os.execv(python_executable, [python_executable, __file__]) import jinja2 import subprocess jinja = jinja2.Environment(loader=jinja2.FileSystemLoader( join(base_path, "ci", "templates")), trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=True) tox_environments = [ line.strip() # WARNING: 'tox' must be installed globally or in the project's virtualenv for line in subprocess.check_output( ['tox', '--listenvs'], universal_newlines=True).splitlines() ] tox_environments = [ line for line in tox_environments if line not in ['clean', 'report', 'docs', 'check'] ] template_vars = {'tox_environments': tox_environments}
import datetime import jinja2 import os import webapp2 from google.appengine.api import users import models template_env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.getcwd())) class MainPage(webapp2.RequestHandler): def get(self): current_time = datetime.datetime.now() user = users.get_current_user() login_url = users.create_login_url(self.request.path) logout_url = users.create_logout_url(self.request.path) userprefs = models.get_userprefs() if userprefs: current_time += datetime.timedelta(0, 0, 0, 0, 0, userprefs.tz_offset) template = template_env.get_template('home.html') context = { 'current_time': current_time, 'user': user, 'login_url': login_url, 'logout_url': logout_url, 'userprefs': userprefs
This sample is used on this page: https://cloud.google.com/appengine/docs/python/ndb/ For more information, see README.md """ # [START all] import os from google.appengine.ext import ndb import webapp2 import jinja2 JINJA_ENVIRONMENT = jinja2.Environment(loader=jinja2.FileSystemLoader( os.path.join(os.path.dirname(__file__), 'views', 'books')), extensions=['jinja2.ext.autoescape'], autoescape=True) class Book(ndb.Model): name = ndb.StringProperty() def greetings(self): return Greeting.query(ancestor=self.key).fetch() @classmethod def list(cls, limit=20): return cls.query().order(cls.name).fetch(limit) class Greeting(ndb.Model):
from googleapiclient import mimeparse #Modelos from user import User from contactList import ContactList from blob import UserFile from googleapiclient.http import MediaIoBaseUpload from oauth2client.client import GoogleCredentials import cloudstorage as gcs import dicttoxml # Defino el entorno de Jinja2 JINJA_ENVIRONMENT = jinja2.Environment(loader=jinja2.FileSystemLoader('views'), extensions=['jinja2.ext.autoescape'], autoescape=True) USERS_INDEX_NAME = 'users' MESSAGES_INDEX_NAME = 'messages' # [START handlers] ######################################################################################################################## # HANDLERS ######################################################################################################################## class MainHandler(webapp2.RequestHandler): def get(self):
import os import jinja2 from jinja2 import FileSystemLoader e = jinja2.Environment(loader=FileSystemLoader('tpls')) def getPGTypeFieldName(colName): return colName[colName.find('_') + 1:] def getSProcName(schema, table): return table def getTypeName(table): return "t_" + table.name def getFieldNameForTable(table): return table.name def create_pg_type(table): t = e.get_template('sql/type_definition.sql') colSource = [] for f in table.fields: type = f.type if f.maxLength is not None and f.maxLength > 0:
import jinja2 import webapp2 from google.appengine.api import users from google.appengine.ext import ndb from model import Page site_name = 'GAE Site' master_id = 'master' JINJA_ENV = jinja2.Environment(loader=jinja2.FileSystemLoader('templates'), extensions=['jinja2.ext.autoescape']) JINJA_ENV.line_statement_prefix = '@' JINJA_ENV.filters['q'] = lambda (value): value.replace('\'', '\\\'') JINJA_ENV.globals['logout_url'] = lambda: users.create_logout_url('/') JINJA_ENV.globals['master_id'] = master_id class PublicHandler(webapp2.RequestHandler): master_key = ndb.Key(Page, master_id) def get(self, page_id=''): if page_id: page = Page.get_by_id(page_id, parent=self.master_key) else: page = Page.get_first_child(self.master_key, False) if page: return self._get_page(page) else: self.redirect('/_add?type=post') def get_file(self, file_id):
import json import sys import yaml import jinja2 data = yaml.load(open('macros.yaml'), Loader=yaml.CLoader) refs = json.load(open('reduced.json')) loader = jinja2.FileSystemLoader(searchpath='./') env = jinja2.Environment(loader=loader) template = env.get_template('sd6.tmpl') print( template.render(lang_macros=data['language'], lib_macros=data['library'], attr_macros=data['attributes'], refs=refs))
import urllib import os import pytz from google.appengine.api import users from google.appengine.ext import ndb import webapp2 import jinja2 import random # Tell program where your templates are JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__) + "/templates"), extensions=['jinja2.ext.autoescape'], autoescape=True) def datetimeformat(value, format='(%d-%m-%Y) %H:%M:%S'): return value.strftime(format) JINJA_ENVIRONMENT.filters['datetimeformat'] = datetimeformat DEFAULT_HOSPITAL_NAME = 'SGH' # We set a parent key on the 'Greetings' to ensure that they are all # in the same entity group. Queries across the single entity group # will be consistent. However, the write rate should be limited to # ~1/second.
def render(full_filename, context): # (3) path, filename = os.path.split(full_filename) template = jinja2.Environment( loader=jinja2.FileSystemLoader(path or './')).get_template(filename) return template.render(context)
'auto_bodytype': 'mini-van', \ 'min_year': 2009, \ 'max_price': 5000\ }) # exclude stuff we don't want -for tickets - we don't want these terms csales = [] # Connecting to the database file for result in cl_e.get_results(sort_by='newest'): csales.append(result) # print('1):', all_rows) # templateLoader = jinja2.FileSystemLoader(searchpath="/") templateEnv = jinja2.Environment(loader=templateLoader) # TEMPLATE_FILE = os.environ["PWD"] + '/carsearch.jinja' template = templateEnv.get_template(TEMPLATE_FILE) # templateVars = { "title": "Car Search", "description": "A simple inquiry of function.", "favorites": csales } # outputText = template.render(templateVars) # print(outputText) f = open("mechspc.html", "a")
import json import datetime import jinja2 import yaml from bottle import route, run, hook, response try: STARTPAGE_VERSION = int(os.getenv('SNIPPETS_STARTPAGE_VERSION', 4)) except ValueError: raise Exception('Invalid startpage version: {}'.format(os.getenv('SNIPPETS_STARTPAGE_VERSION'))) jinja_env = jinja2.Environment( loader=jinja2.FileSystemLoader('templates'), autoescape=True, ) def escapejs(value): _js_escapes = { ord(u'\\'): u'\\u005C', ord(u'\''): u'\\u0027', ord(u'"'): u'\\u0022', ord(u'>'): u'\\u003E', ord(u'<'): u'\\u003C', ord(u'&'): u'\\u0026', ord(u'='): u'\\u003D', ord(u'-'): u'\\u002D', ord(u';'): u'\\u003B', ord(u'\u2028'): u'\\u2028',
import os import jinja2 import webapp2 import src.pages.base as base JINJA_ENV = jinja2.Environment( loader=jinja2.FileSystemLoader(base.BASE_PATH), extensions=['jinja2.ext.autoescape'], autoescape=True) class FunWithCoffeeScriptAndBackbone3(webapp2.RequestHandler): """ Displays article Fun with CoffeeScript and Backbone.js (Part 2) """ def get(self): template = JINJA_ENV.get_template('articles/fun_with_coffeescript_and_backbone/fun_with_coffeescript_and_backbone_3.html') self.response.write(template.render()) # # app = webapp2.WSGIApplication([('/articles/fun_with_coffeescript_and_backbone_3', FunWithCoffeeScriptAndBackbone3)])