try: import simplejson as json except ImportError: import json import urlparse from urllib import urlencode _logger = logging.getLogger(__name__) if hasattr(sys, 'frozen'): # When running on compiled windows binary, we don't have access to package loader. path = os.path.realpath( os.path.join(os.path.dirname(__file__), '..', 'views')) loader = jinja2.FileSystemLoader(path) else: loader = jinja2.PackageLoader('yuancloud.addons.wx_weblink', "views") env2 = jinja2.Environment(loader=loader, autoescape=True) env2.filters["json"] = simplejson.dumps class ShareTimeLine(http.Controller): def exec_signature(self, url, officalaccount): app_id = officalaccount['wx_appid'] app_sercert = officalaccount['wx_appsecret'] public_sdk = wx_public_sdk.wx_public_sdk(app_id, app_sercert) js_api_ticket = public_sdk.get_jsapi_ticket() print js_api_ticket jssign = js_sign.js_sign(js_api_ticket, url) result = jssign.gen_js_sign() result['appid'] = app_id
def __init__(self): self.__environment = jinja2.Environment( loader=jinja2.PackageLoader('dynserver.resources', 'email'))
# You should have received a copy of the GNU Affero General Public # License along with this program. If not, see # <https://www.gnu.org/licenses/>. import os import os.path as op from xml.etree import ElementTree as ET from dataclasses import dataclass, field from typing import List import jinja2 from lxml.etree import parse env = jinja2.Environment(loader=jinja2.PackageLoader('unown', 'templates')) @dataclass class Post: id: str author: str date: str content: str attach: str = None @dataclass class Thread: title: str content: str
def render_sphinx_template( template_name, package='zaf.builtin.docgen', template_dir='templates', **kwargs): import jinja2 env = jinja2.Environment(loader=jinja2.PackageLoader(package, template_dir), ) env.filters['ref'] = create_reference return env.get_template(template_name).render(**kwargs)
from config import settings from salmon.routing import Router from salmon.server import Relay, SMTPReceiver from salmon import view import logging import logging.config import jinja2 logging.config.fileConfig("config/logging.conf") # the relay host to actually send the final message to settings.relay = Relay(host=settings.relay_config['host'], port=settings.relay_config['port'], debug=1) # where to listen for incoming messages settings.receiver = SMTPReceiver(settings.receiver_config['host'], settings.receiver_config['port']) Router.defaults(**settings.router_defaults) Router.load(settings.handlers) Router.RELOAD=True Router.LOG_EXCEPTIONS=True Router.UNDELIVERABLE_QUEUE=queue.Queue(settings.UNDELIVERABLES) view.LOADER = jinja2.Environment( loader=jinja2.PackageLoader(settings.template_config['dir'], settings.template_config['module']))
def generate_all_menus_jinja(dbd_file, *, jinja_env=None, template='menus.jinja2'): """ Generate the module `caproto.server.menus` given an EPICS .dbd file, and optionally a Jinja environment and template filename By default, the jinja environment and template is the one provided with caproto. Parameters ---------- dbd_file : str or pathlib.Path Path to the EPICS dbd file jinja_env : jinja2.Environment, optional The jinja environment template : str, optional The template to use to generate the source """ try: import jinja2 from caproto.tests.dbd import DbdFile except ImportError as ex: raise ImportError(f'An optional/testing dependency is missing: {ex}') if jinja_env is None: jinja_env = jinja2.Environment( loader=jinja2.PackageLoader("caproto.server", "records"), trim_blocks=True, lstrip_blocks=True, ) dbd_file = DbdFile.parse_file(dbd_file) record_template = jinja_env.get_template(template) menus = dict(dbd_file.menus) def fix_item_name(menu_name, name): try: return MENU_FIXES[name] except KeyError: ... orig_name = name if name.startswith(menu_name + '_'): name = name[len(menu_name) + 1:] elif name.startswith(menu_name): name = name[len(menu_name):] if name == 'None': return 'none' name = name.rstrip("_") if name[0] in '0123456789': name = f'choice_{name}' if not name.isidentifier(): return orig_name return name all_dtypes = [('base', None)] + list(dbd_file.record_dtypes.items()) for record_type, dtypes in all_dtypes: if not dtypes: # TODO: caproto has issues with empty enums dtypes = ('Soft Channel', ) menus[f'dtyp_{record_type}'] = [ (get_attr_name_from_dbd_prompt(record_type, None, dtype), dtype) for dtype in dtypes ] for menu_name, items in list(menus.items()): menus[menu_name] = [(fix_item_name(menu_name, item_name), string_value) for item_name, string_value in items] return record_template.render(menus=menus, unsupported_menus=[ menu for menu in MENU_UNSUPPORTED if menu not in menus ])
import jinja2 import webapp2 import urllib2 import json from connexus.common import * from connexus.ndb_model import * from geopy.distance import vincenty JINJA_ENVIRONMENT = jinja2.Environment(loader=jinja2.PackageLoader( 'connexus', 'templates'), extensions=['jinja2.ext.autoescape'], autoescape=True) # [START MobileNearby] class MobileNearby(webapp2.RequestHandler): def get(self): in_long = self.request.get('long') in_lat = self.request.get('lat') page = self.request.get('p') if page == "": page = 1 else: page = int(page) stream_images = StreamImage.query().fetch() if stream_images is None: self.response.headers['Content-Type'] = 'application/json'
def new(package, author, email, title, license, output_dir): """Creates a folder structure for a new Bob/BEAT package.""" if "/" not in package: raise RuntimeError('PACKAGE should be specified as "group/name"') group, name = package.split("/") # creates the rst title, which looks like this: # ======= # Title # ======= rst_title = (("=" * (2 + len(title))) + "\n " + title + "\n" + ("=" * (2 + len(title)))) # the jinja context defines the substitutions to be performed today = datetime.datetime.today() context = dict( package=package, group=group, name=name, author=author, email=email, title=title, rst_title=rst_title, license=license, year=today.strftime("%Y"), date=today.strftime("%c"), ) # copy the whole template structure and de-templatize the needed files if output_dir is None: output_dir = os.path.join(os.path.realpath(os.curdir), name) logger.info("Creating structure for %s at directory %s", package, output_dir) if os.path.exists(output_dir): raise IOError("The package directory %s already exists - cannot " "overwrite!" % output_dir) logger.info("mkdir %s", output_dir) os.makedirs(output_dir) # base jinja2 engine env = jinja2.Environment( loader=jinja2.PackageLoader("bob.devtools", "templates"), autoescape=jinja2.select_autoescape(["html", "xml"]), ) # other standard files simple = [ ".flake8", ".gitignore", ".gitlab-ci.yml", ".pre-commit-config.yaml", "doc/conf.py", "doc/index.rst", "doc/links.rst", "MANIFEST.in", "README.rst", "requirements.txt", "setup.py", "version.txt", ] for k in simple: render_template(env, k, context, output_dir) # handles the license file if license == "gplv3": render_template(env, "COPYING", context, output_dir) else: render_template(env, "LICENSE", context, output_dir) # creates the base python module structure template_dir = pkg_resources.resource_filename( __name__, os.path.join("..", "templates")) logger.info("Creating base %s python module", group) shutil.copytree(os.path.join(template_dir, "pkg"), os.path.join(output_dir, group)) # copies specific images to the right spot copy_file(os.path.join("doc", "img", "%s-favicon.ico" % group), output_dir) copy_file(os.path.join("doc", "img", "%s-128x128.png" % group), output_dir) copy_file(os.path.join("doc", "img", "%s-logo.png" % group), output_dir) # finally, render the conda recipe template-template! # this one is special since it is already a jinja2 template conda_env = jinja2.Environment( loader=jinja2.PackageLoader("bob.devtools", "templates"), autoescape=jinja2.select_autoescape(["html", "xml"]), block_start_string="(%", block_end_string="%)", variable_start_string="((", variable_end_string="))", comment_start_string="(#", comment_end_string="#)", ) render_template(conda_env, os.path.join("conda", "meta.yaml"), context, output_dir)
def __init__(self, package='aodncore.pipeline', package_path='templates'): super().__init__() self._package = package self._loader = jinja2.PackageLoader(package, package_path) self._env = jinja2.Environment(loader=self._loader)
related_types = {clong_desc: (int_desc,), int_desc: (clong_desc,)} class AlternativeTypeBase(object): # TODO: Base class for alternative types pass class AlternativeIntOrClong(AlternativeTypeBase): # TODO: Base class for alternative type int or clong. pass env = jinja2.Environment( loader=jinja2.PackageLoader("nuitka.tools.specialize", "templates"), trim_blocks=True, lstrip_blocks=True, ) env.undefined = jinja2.StrictUndefined types = ( int_desc, str_desc, unicode_desc, float_desc, tuple_desc, list_desc, bytes_desc, long_desc,
import pickle import shutil import jinja2 from ..ert import create_ert_setup, run_ert_subprocess _TEMPLATE_ENVIRONMENT = jinja2.Environment( loader=jinja2.PackageLoader("flownet", "templates"), undefined=jinja2.StrictUndefined, ) def run_flownet_prediction(config, args): """ Create prediction ERT setup, and runs it. Args: config: A configsuite instance. args: The argparse namespace given by the user Returns: Nothing """ with open(args.ahm_folder / "network.pickled", "rb") as fh: network = pickle.load(fh) with open(args.ahm_folder / "schedule.pickled", "rb") as fh: schedule = pickle.load(fh)
"""Kernel watchdog system. """ import codecs import io import logging import os import jinja2 import pkg_resources from treadmill import fs from treadmill import subproc _LOGGER = logging.getLogger(__name__) _JINJA2_ENV = jinja2.Environment(loader=jinja2.PackageLoader(__name__)) class KernelWatchdog(object): """Kernel watchdog.""" def __init__(self, root, reboot_script): """ :param root: watchdog base directory :param reboot_script: reboot script """ self.root = root self.reboot_script = reboot_script self.pid_file = '/var/run/watchdog.pid' self.config_file = os.path.join(self.root, 'watchdog.conf') self.script_directory = os.path.join(self.root, 'script')
import jinja2 import pkg_resources __all__ = [ 'config', 'sge', 'condor', 'user_msgs', ] _web_tmpl_loader = jinja2.Environment(loader=jinja2.PrefixLoader({ 'web': jinja2.PackageLoader('starcluster.templates', 'web'), })) get_web_template = _web_tmpl_loader.get_template _tmpl_loader = jinja2.Environment( loader=jinja2.PackageLoader('starcluster', 'templates')) get_template = _tmpl_loader.get_template def get_resource(pkg_data_path, stream=True): pkg_res_meth = pkg_resources.resource_filename if stream: pkg_res_meth = pkg_resources.resource_stream return pkg_res_meth('starcluster.templates', pkg_data_path) TemplateNotFound = jinja2.TemplateNotFound
import os import sys import jinja2 from odoo import http, tools from odoo.addons.web.controllers.main import Database, Binary from odoo.addons.web.controllers import main from odoo.modules import get_resource_path from odoo.http import request if hasattr(sys, 'frozen'): # When running on compiled windows binary, we don't have access to package loader. path = os.path.realpath( os.path.join(os.path.dirname(__file__), '..', 'views')) loader = jinja2.FileSystemLoader(path) else: loader = jinja2.PackageLoader('odoo.addons.web_debrand', "views") env = main.jinja2.Environment(loader=loader, autoescape=True) env.filters["json"] = json.dumps db_monodb = http.db_monodb class BinaryCustom(Binary): @http.route([ '/web/binary/company_logo', '/logo', '/logo.png', ], type='http', auth="none") def company_logo(self, dbname=None, **kw): imgname = 'logo'
def run(hxl_release, hashtag_categories_url, hashtags_url, attribute_categories_url, attributes_url): """Run the processes to generate the HTML dictionary.""" # Set up Jinja2 template environment for rendering HTML env = jinja2.Environment( loader=jinja2.PackageLoader('gen-hxl-dict', 'templates'), autoescape=jinja2.select_autoescape(['html', 'xml']), trim_blocks=True, lstrip_blocks=True ) env.filters['linkify'] = linkify logging.info("Reading hashtag category definitions from {}...".format(hashtag_categories_url)) category_data = hxl.data(hashtag_categories_url).sort('#meta+category') for row in category_data: hashtag_category_titles.add(row.get('#meta+category')) hashtag_categories.append(row) logging.info("Reading hashtag definitions from {}...".format(hashtags_url)) hashtag_data = hxl.data(hashtags_url) for row in hashtag_data: hashtag_release = row.get('#meta+release') if hashtag_release: try: if float(hashtag_release) <= hxl_release: process_hashtag_def(row) except ValueError: logging.error("Bad release %s (%s)", hashtag_release, row.get('#valid_tag')) logging.info("Reading attribute category definitions from {}...".format(attribute_categories_url)) category_data = hxl.data(attribute_categories_url).sort('#meta+category') for row in category_data: attribute_category_titles.add(row.get('#meta+category')) attribute_categories.append(row) logging.info("Reading attribute definitions from {}...".format(attributes_url)) attribute_data = hxl.data(attributes_url) for row in attribute_data: attribute_release = row.get('#meta+release') if attribute_release: try: if float(attribute_release) <= hxl_release: process_attribute_def(row) except ValueError: logging.error("Bad release %s (%s)", attribute_release, row.get('#valid_attribute')) logging.info("Generating output...") template = env.get_template('dictionary.html') print( template.render( now=datetime.datetime.utcnow(), hashtag_defs=hashtag_defs, hashtag_categories=hashtag_categories, hashtags_by_category=hashtags_by_category, hashtag_attribute_map=hashtag_attribute_map, attribute_defs=attribute_defs, attribute_categories=attribute_categories, attributes_by_category=attributes_by_category, attribute_hashtag_map=attribute_hashtag_map, index_items = sorted(list(hashtag_defs.keys()) + list(attribute_defs.keys()), key=lambda key: key[1:]) ))
def __init__(self, book): self.book = book package_loader = jinja2.PackageLoader('gitenberg', 'templates') self.env = jinja2.Environment(loader=package_loader)
def set_package_loader(app): aiohttp_jinja2.setup(app, loader=jinja2.PackageLoader("tests.contrib.aiohttp.app", "templates"))
import os import asyncio import aiohttp_jinja2 import jinja2 from datetime import datetime, timedelta from aiohttp import web from pymongo import MongoClient from app.models import Subscription APP_DIR = os.path.dirname(os.path.realpath(__file__)) STATIC_DIR = os.path.join(APP_DIR, 'static') loop = asyncio.get_event_loop() app = web.Application(loop=loop) aiohttp_jinja2.setup(app, loader=jinja2.PackageLoader('static', './')) @aiohttp_jinja2.template('index.html') async def index(request): return async def add_entry(request): data = await request.json() data['data']['offset'] = datetime.today() - timedelta(hours=24) sub = Subscription(data['data']) try: sub.m.save() return web.json_response(status=200, data={'ok': True}) except:
def to_stream(self, filename, dcontext=None, **context): if not context and isinstance(dcontext, dict): context = dcontext tmpl = self._get_template(filename) return tmpl.stream(context) def get_global(self, name): return self.env.globals[name] def set_global(self, name, value): self.env.globals[name] = value def get_filter(self, name): return self.env.filters[name] def set_filter(self, name, value): self.env.filters[name] = value def get_test(self, name): return self.env.tests[name] def set_test(self, name, value): self.env.tests[name] = value def add_extension(self, ext): self.env.add_extension(ext) default_loader = jinja2.PackageLoader('shake', 'default_views') default_render = Render(loader=default_loader)
from trove.openstack.common import log as logging from trove.openstack.common import loopingcall CONF = cfg.CONF LOG = logging.getLogger(__name__) import_class = importutils.import_class import_object = importutils.import_object import_module = importutils.import_module bool_from_string = strutils.bool_from_string execute = processutils.execute isotime = timeutils.isotime CONF = cfg.CONF ENV = jinja2.Environment(loader=jinja2.ChoiceLoader([ jinja2.FileSystemLoader(CONF.template_path), jinja2.PackageLoader("trove", "templates") ])) def create_method_args_string(*args, **kwargs): """Returns a string representation of args and keyword args. I.e. for args=1,2,3 and kwargs={'a':4, 'b':5} you'd get: "1,2,3,a=4,b=5" """ # While %s turns a var into a string but in some rare cases explicit # repr() is less likely to raise an exception. arg_strs = [repr(arg) for arg in args] arg_strs += [ '%s=%s' % (repr(key), repr(value)) for (key, value) in kwargs.items() ] return ', '.join(arg_strs)
from openerp.tools import ustr from openerp import http from PIL import Image from io import BytesIO import cStringIO from openerp.http import request, serialize_exception as _serialize_exception _logger = logging.getLogger(__name__) if hasattr(sys, 'frozen'): # When running on compiled windows binary, we don't have access to package loader. path = os.path.realpath( os.path.join(os.path.dirname(__file__), '..', 'views')) loader = jinja2.FileSystemLoader(path) else: loader = jinja2.PackageLoader('openerp.addons.registro_mercantil', "views") env = jinja2.Environment(loader=loader, autoescape=True) env.filters["json"] = simplejson.dumps # 1 week cache for asset bundles as advised by Google Page Speed BUNDLE_MAXAGE = 60 * 60 * 24 * 7 class psController(http.Controller): @http.route('/registro_mercantil/web', type='http', auth='user') def a(self, binary, tipo, **k): cr, uid, context, session = request.cr, request.uid, request.context, request.session print str( k
def load_query(self, source): env = jinja2.Environment( loader=jinja2.PackageLoader(self.__module__, '.')) template = env.get_template(source) return template.render(task=self, **self.variables)
def render(context): env = jinja2.Environment(loader=jinja2.PackageLoader( thenewboston_node.business_logic.docs.__name__, 'templates')) template = env.get_template('blockchain-format.rst') return template.render(context)
MEMCACHE_MECHANISM = True # AppEngine Email APPENGINE_EMAIL = os.environ.get('APPENGINE_EMAIL', '') CALENDAR_MECHANISM = False MAX_INSTANCES = os.environ.get('MAX_INSTANCES', '3') # Users with authorized domain will automatically get Creator role. AUTHORIZED_DOMAIN = os.environ.get('AUTHORIZED_DOMAIN', "") ACCESS_TOKEN = os.environ.get('ACCESS_TOKEN', '') JINJA2 = jinja2.Environment(loader=jinja2.PackageLoader('ggrc', 'templates')) EMAIL_DIGEST = JINJA2.get_template("notifications/email_digest.html") EMAIL_DAILY = JINJA2.get_template("notifications/view_daily_digest.html") EMAIL_PENDING = JINJA2.get_template("notifications/view_pending_digest.html") EMAIL_IMPORT_EXPORT = JINJA2.get_template("notifications/import_export.html") EMAIL_BULK_CHILD_SYNC_SUCCEEDED = JINJA2.get_template( "notifications/bulk_child_sync_succeded.html") EMAIL_BULK_CHILD_SYNC_FAILED = JINJA2.get_template( "notifications/bulk_child_sync_failed.html") EMAIL_BULK_CHILD_SYNC_EXCEPTION = JINJA2.get_template( "notifications/bulk_child_sync_exception.html") EMAIL_BULK_SYNC_SUCCEEDED = JINJA2.get_template( "notifications/bulk_sync_succeded.html") EMAIL_BULK_SYNC_FAILED = JINJA2.get_template( "notifications/bulk_sync_failed.html") EMAIL_BULK_SYNC_EXCEPTION = JINJA2.get_template(
import jinja2 from sanic import response from .util import get_banner j2 = jinja2.Environment( loader=jinja2.PackageLoader(__name__, "templates"), autoescape=jinja2.select_autoescape(["html", "xml"]), ) j2.globals.update({"len": len, "get_banner": get_banner}) def renderpost_filter(t, show_thread_link=False): return jinja2.Markup( j2.get_template("post.html").render(show_thread_link=show_thread_link, **t) ) j2.filters.update({"renderpost": renderpost_filter}) def render_template(name, **kwargs): return response.html(j2.get_template(name).render(**kwargs))
import jinja2 import os import simplejson import sys import openerp import openerp.modules.registry from openerp.tools import topological_sort from openerp import http from openerp.http import request, serialize_exception as _serialize_exception if hasattr(sys, 'frozen'): # When running on compiled windows binary, we don't have access to package loader. path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'views')) loader = jinja2.FileSystemLoader(path) else: loader = jinja2.PackageLoader('openerp.addons.web', "views") env = jinja2.Environment(loader=loader, autoescape=True) env.filters["json"] = simplejson.dumps db_monodb = http.db_monodb def module_installed_bypass_session(dbname): loadable = http.addons_manifest.keys() modules = {} try: registry = openerp.modules.registry.RegistryManager.get(dbname) with registry.cursor() as cr: m = registry.get('ir.module.module') # TODO The following code should move to ir.module.module.list_installed_modules() domain = [('state','=','installed'), ('name','in', loadable)]
def create_unit_from_template(template_type, no_edit, **kwargs): """Function for creating a module in the perun developer directory from template This function serves as a generator of modules and packages of units and algorithms for perun. According to the template_type this loads a concrete set of templates, (if needed) creates a the target directory and then initializes all of the needed modules. If no_edit is set to true, all of the created modules, and the registration point (i.e. file, where new modules has to be registered) are opened in the editor set in the general.config key (which is looked up recursively). :param str template_type: name of the template set, that will be created :param bool no_edit: if set to true, then external editor will not be called to edit the files :param dict kwargs: additional parameters to the concrete templates :raises ExternalEditorErrorException: When anything bad happens when processing newly created files with editor """ def template_name_filter(template_name): """Helper function for filtering functions which starts with the template_type name :param str template_name: name of the template set :return: true if the function starts with template_type """ return template_name.startswith(template_type) # Lookup the perun working dir according to the current file perun_dev_dir = os.path.abspath( os.path.join(os.path.split(__file__)[0], "..")) if not os.path.isdir(perun_dev_dir) \ or not os.access(perun_dev_dir, os.W_OK)\ or template_type not in os.listdir(perun_dev_dir): log.error("cannot use {} as target developer directory".format( perun_dev_dir) + " (either not writeable or does not exist)\n\n" + "Perhaps you are not working from perun dev folder?") # Initialize the jinja2 environment and load all of the templates for template_type set env = jinja2.Environment(loader=jinja2.PackageLoader('perun', 'templates'), autoescape=True) list_of_templates = env.list_templates(filter_func=template_name_filter) # Specify the target dir (for packages we create a new directory) if "__init__" in "".join(list_of_templates): # We will initialize it in the isolate package target_dir = os.path.join(perun_dev_dir, template_type, kwargs['unit_name']) store.touch_dir(target_dir) else: target_dir = os.path.join(perun_dev_dir, template_type) print("Initializing new {} module in {}".format(template_type, target_dir)) # Iterate through all of the templates and create the new files with rendered templates successfully_created_files = [] for template_file in list_of_templates: # Specify the target filename of the template file template_filename, _ = os.path.splitext(template_file) template_filename = kwargs['unit_name'] if '.' not in template_filename else \ template_filename.split('.')[1] template_filename += ".py" successfully_created_files.append(template_filename) print("> creating module '{}' from template".format(template_filename), end='') # Render and write the template into the resulting file with open(os.path.join(target_dir, template_filename), 'w') as template_handle: template_handle.write( env.get_template(template_file).render(**kwargs)) print(' [', end='') log.cprint('DONE', 'green', attrs=['bold']) print(']') # Add the registration point to the set of file successfully_created_files.append( os.path.join( perun_dev_dir, { 'check': os.path.join('check', '__init__.py'), 'postprocess': os.path.join('utils', '__init__.py'), 'collect': os.path.join('utils', '__init__.py'), 'view': os.path.join('utils', '__init__.py') }.get(template_type, 'nowhere'))) print("Please register your new module in {}".format( successfully_created_files[-1])) # Unless specified in other way, open all of the files in the w.r.t the general.editor key if not no_edit: editor = config.lookup_key_recursively('general.editor') print("Opening created files and registration point in {}".format( editor)) try: utils.run_external_command([editor] + successfully_created_files[::-1]) except Exception as inner_exception: raise ExternalEditorErrorException(editor, str(inner_exception))
# TODO: Config file corpus_file = "{root}/corpus/test_corpus.csv".format(root=root_folder) cs_agent = "webtest" cs_ip = "127.0.0.1:1024" solr_url = "http://*****:*****@app.route('/') def base(): ''' Index - Just a button to perform the test ''' return open('{root}/static/templates/index.html'.format(root=root_folder), 'r').read() @app.route('/test') def test_corpus(): '''
def main(tsproj_project, *, name=None, prefix=None, template_filename='stcmd_default.cmd', plc_name=None, dbd=None, db_path='.', only_motor=False, binary_name='ads', delim=':', template_path='.', debug=False, allow_errors=False, hashbang='../../bin/rhel7-x86_64/adsIoc'): jinja_loader = jinja2.ChoiceLoader([ jinja2.PackageLoader("pytmc", "templates"), jinja2.FileSystemLoader(template_path), ]) jinja_env = jinja2.Environment( loader=jinja_loader, trim_blocks=True, lstrip_blocks=True, ) if not name: name = pathlib.Path(tsproj_project).stem if not prefix: prefix = name.upper() jinja_env.filters.update( **jinja_filters(delim=delim, prefix=prefix, name=name)) template = jinja_env.get_template(template_filename) project = parse(tsproj_project) symbols = separate_by_classname(project.find(Symbol)) additional_db_files = [] try: plc, = project.plcs except ValueError: by_name = project.plcs_by_name if not plc_name: raise RuntimeError(f'Only single PLC projects supported. ' f'Use --plc and choose from {list(by_name)}') try: plc = project.plcs_by_name[plc_name] except KeyError: raise RuntimeError(f'PLC project {plc_name!r} not found. ' f'Projects: {list(by_name)}') symbols = separate_by_classname(plc.find(Symbol)) if not only_motor: other_records = db.process(plc.tmc, dbd_file=dbd) if not other_records: logger.info('No additional records from pytmc found in %s', plc.tmc.filename) else: db_filename = f'{plc.filename.stem}.db' db_path = pathlib.Path(db_path) / db_filename logger.info('Found %d additional records; writing to %s', len(other_records), db_path) with open(db_path, 'wt') as db_file: db_file.write('\n\n'.join(rec.render() for rec in other_records)) additional_db_files.append({'file': db_filename, 'macros': ''}) ams_id = plc.ams_id target_ip = plc.target_ip if not allow_errors: if not ams_id: raise RuntimeError('AMS ID unset. Try --allow-errors if this is ' 'not an issue.') if not target_ip: raise RuntimeError('IP address unset. Try --allow-errors if this ' 'is not an issue.') try: nc, = list(project.find(NC, recurse=False)) except Exception: nc = None template_args = dict( hashbang=hashbang, binary_name=binary_name, name=name, prefix=prefix, delim=delim, user=getpass.getuser(), motor_port='PLC_ADS', asyn_port='ASYN_PLC', plc_ams_id=ams_id, plc_ip=target_ip, plc_ads_port=plc.port, additional_db_files=additional_db_files, symbols=symbols, nc=nc, ) stashed_exception = None try: rendered = template.render(**template_args) except Exception as ex: stashed_exception = ex rendered = None if not debug: if stashed_exception is not None: raise stashed_exception print(rendered) else: message = ['Variables: project, symbols, plc, template. '] if stashed_exception is not None: message.append(f'Exception: {type(stashed_exception)} ' f'{stashed_exception}') util.python_debug_session(namespace=locals(), message='\n'.join(message))
def write(self, mdata, fname, options=None): ''' Write simulation model in VRML format ''' self._options = options fpath, fext = os.path.splitext(fname) basename = os.path.basename(fpath) dirname = os.path.dirname(fname) if mdata.name is None or mdata.name == '': mdata.name = basename # convert revolute2 joint to two revolute joints (with a link # in between) for j in mdata.joints: if j.jointType == model.JointModel.J_REVOLUTE2: logging.info( "converting revolute2 joint to two revolute joints") nl = model.LinkModel() nl.name = j.name + "_REVOLUTE2_LINK" nl.matrix = j.getmatrix() nl.trans = None nl.rot = None nl.mass = 0.001 # assign very small mass mdata.links.append(nl) nj = copy.deepcopy(j) nj.name = j.name + "_SECOND" nj.jointType = model.JointModel.J_REVOLUTE nj.parent = nl.name nj.child = j.child nj.axis = j.axis2 mdata.joints.append(nj) j.jointType = model.JointModel.J_REVOLUTE j.child = nl.name # check for same names in visuals or collisions usednames = {} for l in mdata.links: for v in l.visuals: if v.name in usednames: v.name = l.name + "-visual" if v.name in usednames: v.name = l.name + "-visual-" + str( uuid.uuid1()).replace('-', '') usednames[v.name] = True for c in l.collisions: if c.name in usednames: c.name = l.name + "-collision" if c.name in usednames: c.name = l.name + "-collision-" + str( uuid.uuid1()).replace('-', '') usednames[c.name] = True # find root joint (including local peaks) self._roots = utils.findroot(mdata) # render the data structure using template loader = jinja2.PackageLoader(self.__module__, 'template') env = jinja2.Environment(loader=loader, extensions=['jinja2.ext.do']) self._linkmap['world'] = model.LinkModel() for m in mdata.links: self._linkmap[m.name] = m # render shape vrml file for each links shapefilemap = {} for l in mdata.links: shapes = copy.copy(l.visuals) if options is not None and options.usecollision: shapes = copy.copy(l.collisions) if options is not None and options.useboth: shapes.extend(copy.copy(l.collisions)) for v in shapes: logging.info('writing shape of link: %s, type: %s' % (l.name, v.shapeType)) if v.shapeType == model.ShapeModel.SP_MESH: template = env.get_template('vrml-mesh.wrl') if isinstance(v.data, model.MeshTransformData): v.data.pretranslate() m = {} m['children'] = [v.data] shapefname = (mdata.name + "-" + l.name + "-" + v.name + ".wrl").replace('::', '_') with open(os.path.join(dirname, shapefname), 'w') as ofile: ofile.write( template.render({ 'name': v.name, 'ShapeModel': model.ShapeModel, 'mesh': m })) shapefilemap[v.name] = shapefname # render main vrml file for each bodies template = env.get_template('vrml.wrl') roots = [] modelfiles = {} for root in self._roots: if root == 'world': for r in utils.findchildren(mdata, root): roots.append((r.child, "fixed")) else: roots.append((root, "free")) for r in roots: logging.info('writing model for %s' % r[0]) if len(roots) == 1: mfname = fname else: mfname = (mdata.name + "-" + r[0] + ".wrl").replace('::', '_') self.renderchildren(mdata, r[0], r[1], os.path.join(dirname, mfname), shapefilemap, template) modelfiles[mfname] = self._linkmap[r[0]] # render openhrp project template = env.get_template('openhrp-project.xml') with open(fname.replace('.wrl', '-project.xml'), 'w') as ofile: ofile.write(template.render({ 'models': modelfiles, })) # render choreonoid project template = env.get_template('choreonoid-project.yaml') with open(fname.replace('.wrl', '-project.cnoid'), 'w') as ofile: ofile.write(template.render({ 'models': modelfiles, }))