Package: cloudmage-jinjautils
CloudMage JinjaUtils Python3 Utility PackageTable of ContentsDescriptionRoad MapPython Version SupportPackage InstallationPackage DependenciesJinjaUtils ClassJinjaUtils Constructor ArgumentsJinjaUtils Attributes and PropertiesJinjaUtils Available MethodsJinjaUtils Class UsageChangeLogContacts and ContributionsDescriptionThis utility package was created to allow quick and easy access method to work with Jinja templates within a python environment. The package will give access to a class that can be imported and instantiated, creating a JinjaUtils instance that will allow the consumer the ability to quickly and easily set jinja options via object properties, load templates including custom templates, render those templates and write the template output to the an output directory/file with little concern around error handling and processing. A few lines of code and a provided template is all that is needed to start producing template driven file creation quickly and easily.Road MapBeyond the initial capabilities of this library, new features will be evaluated and could be added with feature requests, or as additional processes that can be simplified are discovered.Python Version SupportThis library is compatible with Python 3.6 and higher. It may work with earlier versions of Python3 but was not tested against anything earlier then 3.6. As Python 2.x is soon to be end of life, backward compatibility was not taken into consideration.Package InstallationThis library has been published toPyPiand can be installed via normal python package manager conventions such aspiporpoetry.pip3installcloudmage-jinjautilsPackage DependenciesThis package installs and imports the following python modules during installation:jinja2TemplateEnvironmentFileSystemLoaderAdditionally the package takes advantage of the following built in python modules:ossysjsoninspectntpathshutildatetimeJinjaUtils ClassThe JinjaUtils class has the following described methods, properties and attributes accessable to it upon object instantiation. A few object constructor arguments can be provided at the time that the object is instantiated. Object getter property methods are accessed from the object in standard dot notationJinja.verbose, Jinja.template_directory, etc.and Object settter methods are used by assigning a value to the object propertyJinja.template_directory = '/path/to/templates. The class gives the object instance access to the following properties:JinjaUtils Constructor ArgumentsverboseEnables verbose mode.   [true=enablefalse=disable]requiredfalsetypebooldefaultfalse(disabled)logRedirects object standard log messaging to provided log object.requiredfalsetypeobjdefaultNone(log to stdout, stderr if verbose=true)JinjaUtils Attributes and PropertiesThe following attributes/properties are available to an instantiated object instance. Any of the attributes or properties can be accessed with standard object dot notation as in the example:verbose_mode = JinjaUtils.verboseverboseVerbose setting that controls logging level within the object class.   [true=enabled,false=disabled]returnstrueorfalse(enabled or disabled)typeboolinstantiated valuefalsetrim_blocksEnables or disables the Jinja trim_blocks setting used when loading templates by the Jinja FileSystemLoader.returnstrueorfalse(enabled or disabled)typeboolinstantiated valuetruelstrip_blocksEnables or disables the Jinja lstrip_blocks setting used when loading templates by the Jinja FileSystemLoader.returnstrueorfalse(enabled or disabled)typeboolinstantiated valuetruetemplate_directoryGetter property method that returns the string value of the currently configured Jinja template directoryreturnsJinja template directory->/jinja/templatestypestrinstantiated valueNoneavailable_templatesReturns a list of available template files that have been loaded by the Jinja FileSystemLoader located in the configured template directory that are available for use.returnsList of files available in the loaded template library->["template1.j2","template2.j2"typelistinstantiated valueNoneloadReturns the file name of the currently loaded Jinja template that is ready for renderingreturnsLoaded template name->myFile.j2typestrinstantiated valueNonerenderedReturns the currently rendered template object, ready to be written to diskreturnsRendered template objecttypeobjinstantiated valueNonewriteReturnstrueorfalsedepending on if the rendered template was successfully written to diskreturnstrueorfalsevalue signaling a valid write or failed write to disktypeboolinstantiated valuetrueorfalsevalue signaling a valid write or failed writelogThe class logger. Will either write directly to stdout, stderr, or to a lob object if passed into the object constructor during object instantiationreturnsLog Event Streamtypestrinstantiated valueLogs written to stdout, stderrJinjaUtils Available MethodsThe following methods are available to an instantiated object instance. Some of the methods are simply setter methods that run the logic required to discover and then set one of the above instance properties.verboseSetter method forverboseproperty that enables or disables verbose modeparametertyperequiredarg infoverbosebooltrueTrueenables verbose logging,Falsedisables itExamples:# Getter methodverbose_setting=JinjaUtils.verbose# Setter methodJinjaUtils.verbose=Truetrim_blocksSetter method fortrim_blocksproperty that enables or disables the Jinja trim_blocks option during the construction of the Jinja Environment and template loading process via the Jinja FileSystemLoader.parametertyperequiredarg infotrim_blocksbooltrueTrueenables trim_blocks logging,Falsedisables the optionExamples:# Getter methodjinja_trim_blocks_setting=JinjaUtils.trim_blocks# Setter methodJinjaUtils.trim_blocks=Truelstrip_blocksSetter method forlstrip_blocksproperty that enables or disables the Jinja lstrip_blocks option during the construction of the Jinja Environment and template loading process via the Jinja FileSystemLoader.parametertyperequiredarg infolstrip_blocksbooltrueTrueenables lstrip_blocks logging,Falsedisables the optionExamples:# Getter methodjinja_lstrip_blocks=JinjaUtils.lstrip_blocks# Setter methodJinjaUtils.lstrip_blocks=Truetemplate_directorySetter method fortemplate_directoryproperty that is used to specify the location of the Jinja template directory. When this setter method is called, a valid directory path must be provided. The directory path is checked byos.path.exists()and must be a valid directory location path. The method will search the directory path for any files in the given directory location and automatically instruct the Jinja FileSystemLoader to load the templates into the Environment template library where they can be called by the object consumer at any point to be loaded, rendered and written to on disk. This setter will also set the value of the.available_templatesattribute.parametertyperequiredarg infotemplate_directorystrtrueProvided path must be a valid URL directory path.Examples:# Getter methodjinja_template_directory=JinjaUtils.template_directory# Setter methodJinjaUtils.template_directory='/path/to/my/template/directory'loadSetter method forloadproperty. When this method is invoked either a file path argument or template name argument must be provided. If a file name argument is given, the loader will search through the templates that are contained in the currently configured template directory and loaded into the current Jinja Environment by the.template_directorysetter call. To view a list of the available templates a call to the.available_templatesattribute can be made. If a file system path is provided to the loader, then the loader will search the given file path, and if a valid file is found, it will instruct the loader to load the provided file. Once a file has been loaded by the object, it is ready to be rendered with the.renderproperty.parametertyperequiredarg infotemplatestrtrueTemplate file name located in the templates directory or valid file path to template file.Examples:# Getter methodjinja_loaded_template=JinjaUtils.load# Setter methodJinjaUtils.load='/path/to/my/template/directory/template.j2'fortemplateinJinjaUtils.available_templates:print(template)JinjaUtils.load='template.j2'renderThe render method takes an undermined number of keyword arguments representing the template variables and objects that will supply the values to those variables respectively when rendering the template. The keyword example formats such asvariables=dictionaryObject,people=["tom", "susan", tonya"]would be mapped to the template at the time of render and made available to the template. In the given examples, the template may require a dictionary named variables that it will iterate through, or a variable named people that is an expected list that it will use to populate template sections. When therendermethod is called, Jinja will attempt to render the currently loaded template and supply any of keyword arguments that were passed as method arguments at the time that the render method was called.parametertyperequiredarg infonames=names,values=values,etc=4**kwargsfalseCurrently loaded template will be rendered.Examples:print(JinjaUtils.load)# template.j2JinjaUtils.render(names=names,values=values,etc=4)# This will render the currently loaded template2.j2 and pass the names, values, and etc values to itwriteOnce the template has been rendered, it can be written to disk using thewritemethod. The write method takes 2 required arguments consisting of theoutput directoryandoutput file, along with 1 optional argument to turn file backup off. When the write method is used, it will write the currently rendered template to the output directory specified as the output file name specified. If during the write operation it discovers an existing file with the same name in the target directory, by default instead of just overwriting the file callously, the write method will take a copy of the existing file, strip off the original extention to avoid non unique file name conflicts and write the copy appending an extention in the format of_YYYYMMDD_HMS.bak. This timestamp formatted extention will allow easy identification of when the backup of the file was taken. The default file backup feature can be turned off by passing thebackup=Falseoption to the write command when called. If backup is disabled, then calling the write method will simply just overwrite any existing files in the output directory with the output filename that already exist. Provided output_directory argument value must exist and be valid directory paths, which are validated byos.path.exists(), and must not be the path to a file. The provided output_file argument value must be a valid file name, and will be stripped of any trailing path.parametertyperequiredarg infooutput_directorystrtrueMust be valid directory path to existing directory.output_filestrtrueFilename only, paths are stripped using only the file basename .backupboolfalseBool value to enable or disable existing file backups.Default=trueExamples:print(str(JinjaUtils.rendered))JinjaUtils.write(output_directory='/reports',output_file='monthly_report.yaml',backup=True)logMethod to enable logging throughout the class. Log messages are sent to the log method providing the log message, the message type being one of[debug, info, warning, error], and finally the function or method id that is automatically derived within the function or method using the python inspect module. If a log object such as a logger or an already instantiated log object instance was passed to the class constructor during the objects instantiation, then all logs will be written to the provided log object. If no log object was provided during instantiation then alldebug,info, andwarninglogs will be written to stdout, while any encounterederrorlog entries will be written to stderr. Note that debug or verbose mode needs to be enabled to receive the event log stream.argtyperequiredarg infolog_msgstrtrueThe actual message being sent to the log methodlog_typestrtrueThe type of message that is being sent to the log method, one of[debug, info, warning, error]log_idstrtrueA string value identifying the sender method or function, consisting of the method or function nameExamples:defmy_function():__function_id=inspect.stack()[0][3]JinjaUtils.log(f"{__function_id}called.",'info',__function_id)JinjaUtils Class UsageThe following section will show a few examples of how the module can be used to generate documents from available templates quickly and easily.Basic Usagefromcloudmage.jinjautilsimportJinjaUtils# Set template directory, contains weekly_report.j2, monthly_report.j2, annual_report.j2jinja_template_path=os.path.join(os.getcwd(),'templates')jinja_output_path=os.path.join(os.getcwd(),'monthly_reports')# Set data variablemonthly_sales={'week_1':15000,'week_2':1000,'week_3':2000,'week_4':2500}sales_team=['tonya','tom','billy','amanda']# Instantiate JinjaUtils ObjectJinja=JinjaUtils()# Set the template directory, this loads all templates into the Jinja Environment# and constructs the available_templates attribute list valueJinja.template_directory=jinja_template_pathprint(Jinja.available_templates)# prints ['weekly_report.j2', 'monthly_report.j2', 'annual_report.j2']# Load one of the available templatesJinja.load='monthly_report.j2'# Render the templateJinja.render(pnl=monthly_sales,team=sales_team)# Write the rendered template to disk, Backup of existing files is ENABLED by default, so turn it offJinja.write(output_directory=jinja_output_path,output_file='feb_sales.html',backup=False)Optional Verbose Class Constructor Argument:When instantiating the class an optionalverboseargument can be provided. The argument expects a bool value of eitherTrueorFalse. By default verbose is set to False. Ifverbose=Trueis passed during object instantiation, then debug mode is turned on allowing the class to output DEBUG, INFO, and WARNING messages to stdout, and ERROR messages to stderr.fromcloudmage.jinjautilsimportJinjaUtils# Instantiate JinjaUtils ObjectJinja=JinjaUtils(verbose=True)# Load one of the available templatesJinja.load='./templates/annual_sales.j2'# Render the templateJinja.render(total_sales="25,000")# Write the rendered template to diskJinja.write(output_directory='.',output_file='2019-sales.yaml')# Class DEBUG, INFO, and WARNING messages will be printed to stdout, and ERROR messages will be printed to stderrOptional Log Object:When instantiating the class an optionallogargument can also be provided. The argument expects an Logger object to be passed as an input. If passed then all DEBUG, INFO, WARNING, and ERROR messages will be printed to the standard log levels (log.debug(),log.info(),log.warning(),log.error()) and printed to the passed respective logger object method.fromcloudmage.jinjautilsimportJinjaUtils# Define test log class# This is an example log object that simply appends any DEBUG, INFO and ERROR received class messages# to the respective log level list. Normally this would be a logger or custom log object.classLog(object):"""Test Log Object"""def__init__(self):"""Class Constructor"""self.debug_logs=[]self.info_logs=[]self.warning_logs=[]self.error_logs=[]defdebug(self,message):"""Log Debug Messages"""self.debug_logs.append(message)definfo(self,message):"""Log Info Messages"""self.info_logs.append(message)defwarning(self,message):"""Log Warning Messages"""self.warning_logs.append(message)deferror(self,message):"""Log Error Messages"""self.error_logs.append(message)# Instantiate test log classLogger=Log()# Instantiate JinjaUtils ObjectJinja=JinjaUtils(verbose=True,logs=Logger)# Disable trim_blocks, lstrip_blocksJinja.trim_blocks=FalseJinja.lstrip_blocks=False# Load one of the available templatesJinja.load='./templates/team_schedule.j2'# Render the templateJinja.render()# Write the rendered template to diskJinja.write(output_directory='/reports',output_file='Feb_Schedule.yaml',backup=True)foritemsinLogger.debug_logs:print(item)# Prints stored debug logsChangelogTo view the project changelog see:ChangeLog: