Debian Codegraph @

stetl/filters/templatingfilter.py

raw
1 #!/usr/bin/env python
2 #
3 # Transformation of any input using Python Templating as
4 # meant in: https://wiki.python.org/moin/Templating.
5 # A TemplatingFilter typically is configured with a template file.
6 # The input is typically the Template context, the variables to be substituted.
7 # The output is a string passed to the next Filter or Output.
8 #
9 # Author:Just van den Broecke
10 import os
11
12 from stetl.util import Util, ogr, osr
13 from stetl.component import Config
14 from stetl.filter import Filter
15 from stetl.packet import FORMAT
16 from string import Template
17
18 log = Util.get_log("templatingfilter")
19
20
21 class TemplatingFilter(Filter):
22 """
23 Abstract base class for specific template-based filters.
24 See https://wiki.python.org/moin/Templating
25 Subclasses implement a specific template language like Python string.Template, Mako, Genshi, Jinja2,
26
27 consumes=FORMAT.any, produces=FORMAT.string
28 """
29
30 # Start attribute config meta
31 # Applying Decorator pattern with the Config class to provide
32 # read-only config values from the configured properties.
33
34 @Config(ptype=str, default=None, required=False)
35 def template_file(self):
36 """
37 Path to template file. One of template_file or template_string needs to be configured.
38 """
39 pass
40
41 @Config(ptype=str, default=None, required=False)
42 def template_string(self):
43 """
44 Template string. One of template_file or template_string needs to be configured.
45 """
46 pass
47
48 # End attribute config meta
49
50 # Constructor
51 def __init__(self, configdict, section, consumes=FORMAT.any, produces=FORMAT.string):
52 Filter.__init__(self, configdict, section, consumes, produces)
53
54 def init(self):
55 log.info('Init: templating')
56 if self.template_file is None and self.template_string is None:
57 # If no file present nor template_string error:
58 err_s = 'One of template_file or template_string needs to be configured'
59 log.error(err_s)
60 raise ValueError('One of template_file or template_string needs to be configured')
61
62 self.create_template()
63
64 def exit(self):
65 log.info('Exit: templating')
66 self.destroy_template()
67
68 def create_template(self):
69 '''
70 To be overridden in subclasses.
71 '''
72 pass
73
74 def destroy_template(self):
75 pass
76
77 def invoke(self, packet):
78 if packet.data is None:
79 return packet
80 return self.render_template(packet)
81
82 def render_template(self, packet):
83 pass
84
85
86 class StringTemplatingFilter(TemplatingFilter):
87 """
88 Implements Templating using Python's internal string.Template.
89 A template string or file should be configured. The input record
90 contains the actual values to be substituted in the template string as a record (key/value pairs).
91 Output is a regular string.
92
93 consumes=FORMAT.record or FORMAT.record_array, produces=FORMAT.string
94 """
95
96 @Config(ptype=bool, default=False, required=False)
97 def safe_substitution(self):
98 """
99 Apply safe substitution? With this method, string.Template.safe_substitute will be invoked, instead of
100 string.Template.substitute. If placeholders are missing from mapping and keywords, instead of raising an
101 exception, the original placeholder will appear in the resulting string intact.
102 """
103 pass
104
105 def __init__(self, configdict, section):
106 TemplatingFilter.__init__(self, configdict, section, consumes=[FORMAT.record, FORMAT.record_array])
107
108 def create_template(self):
109 # Init once
110 if self.template_file is not None:
111 # Get template string from file content, otherwise assume template_string is populated
112 log.info('Init: reading template file %s ..." % self.template_file')
113 template_fp = open(self.template_file, 'r')
114 self.template_string = template_fp.read()
115 template_fp.close()
116 log.info("template file read OK: %s" % self.template_file)
117
118 # Create a standard Python string.Template
119 self.template = Template(self.template_string)
120
121 def render_template(self, packet):
122 if self.safe_substitution:
123 if type(packet.data) is list:
124 packet.data = [self.template.safe_substitute(item) for item in packet.data]
125 else:
126 packet.data = self.template.safe_substitute(packet.data)
127 else:
128 if type(packet.data) is list:
129 packet.data = [self.template.substitute(item) for item in packet.data]
130 else:
131 packet.data = self.template.substitute(packet.data)
132
133 return packet
134
135
136 class Jinja2TemplatingFilter(TemplatingFilter):
137 """
138 Implements Templating using Jinja2. Jinja2 http://jinja.pocoo.org,
139 is a modern and designer-friendly templating language for Python
140 modelled after Django’s templates. A 'struct' format as input provides
141 a tree-like structure that could originate from a JSON file or REST service.
142 This input struct provides all the variables to be inserted into the template.
143 The template itself can be configured in this component as a Jinja2 string or -file.
144 An optional 'template_search_paths' provides a list of directories from which templates
145 can be fethced. Default is the current working directory. Via the optional 'globals_path'
146 a JSON structure can be inserted into the Template environment. The variables in this
147 globals struture are typically "boilerplate" constants like: id-prefixes, point of contacts etc.
148
149 consumes=FORMAT.struct, produces=FORMAT.string
150 """
151
152 # Start attribute config meta
153 # Applying Decorator pattern with the Config class to provide
154 # read-only config values from the configured properties.
155
156 @Config(ptype=str, default=None, required=False)
157 def template_search_paths(self):
158 """
159 List of directories where to search for templates, default is current working directory only.
160 """
161 pass
162
163 @Config(ptype=str, default=None, required=False)
164 def template_globals_path(self):
165 """
166 One or more JSON files or URLs with global variables that can be used anywhere in template.
167 Multiple files will be merged into one globals dictionary
168 """
169 pass
170
171 # End attribute config meta
172
173 json_package = None
174 ogr_package = ogr
175 osr_package = osr
176
177 def __init__(self, configdict, section):
178 TemplatingFilter.__init__(self, configdict, section, consumes=[FORMAT.struct, FORMAT.geojson_collection])
179
180 def create_template(self):
181 try:
182 from jinja2 import Environment, FileSystemLoader
183 except Exception as e:
184 log.error(
185 'Cannot import modules from Jinja2, err= %s; You probably need to install Jinja2 first, see http://jinja.pocoo.org',
186 str(e))
187 raise e
188
189 import json
190
191 Jinja2TemplatingFilter.json_package = json
192
193 # Check for a file with global variables configured in json format
194 # TODO get globals in other formats like XML and possibly from a web service
195 template_globals = None
196 if self.template_globals_path is not None:
197 globals_path_list = self.template_globals_path.strip().split(',')
198
199 for file_path in globals_path_list:
200
201 try:
202 log.info('Read JSON file with globals from: %s', file_path)
203 # Globals can come from local file or remote URL
204 if file_path.startswith('http'):
205 from urllib.request import urlopen
206
207 fp = urlopen(file_path)
208 globals_struct = json.loads(fp.read().decode('utf-8'))
209 else:
210 with open(file_path) as data_file:
211 globals_struct = json.load(data_file)
212
213 # First file: starts a globals dict, additional globals are merged into that dict
214 if template_globals is None:
215 template_globals = globals_struct
216 else:
217 template_globals.update(globals_struct)
218
219 except Exception as e:
220 log.error('Cannot read JSON file, err= %s', str(e))
221 raise e
222
223 # Load and Init Template once
224 loader = FileSystemLoader(self.template_search_paths or [os.getcwd()])
225 self.jinja2_env = Environment(loader=loader, extensions=['jinja2.ext.do'], lstrip_blocks=True, trim_blocks=True)
226
227 # Register additional Filters on the template environment by updating the filters dict:
228 self.add_env_filters(self.jinja2_env)
229
230 if self.template_file is not None:
231 # Get template string from file content and pass optional globals into context
232 self.template = self.jinja2_env.get_template(self.template_file, globals=template_globals)
233 log.info("template file read and template created OK: %s" % self.template_file)
234 elif self.template_string is None:
235 # If no file present, template_string should have been configured
236 self.template = self.jinja2_env.from_string(self.template_string, globals=template_globals)
237
238 def render_template(self, packet):
239 packet.data = self.template.render(packet.data)
240 return packet
241
242 def add_env_filters(self, jinja2_env):
243 '''Register additional Filters on the template environment by updating the filters dict:
244 Somehow min and max of list are not present so add them as well.
245 '''
246 jinja2_env.filters['maximum'] = max
247 jinja2_env.filters['minimum'] = min
248 jinja2_env.filters['geojson2gml'] = Jinja2TemplatingFilter.geojson2gml_filter
249
250 @staticmethod
251 def import_ogr():
252 if Jinja2TemplatingFilter.ogr_package is None:
253 log.error(
254 'Cannot import Python ogr package; You probably need to install GDAL/OGR Python bindings, see https://pypi.python.org/pypi/GDAL')
255 raise ImportError
256
257 @staticmethod
258 def create_spatial_ref(crs):
259 # "crs": {
260 # "type": "EPSG",
261 # "properties": {
262 # "code": "4326"
263 # }
264 spatial_ref = Jinja2TemplatingFilter.osr_package.SpatialReference()
265 if type(crs) is dict and crs['type'] == 'EPSG':
266 # from the GeoJSON source data, though in future deprecated
267 spatial_ref.ImportFromEPSG(int(crs['properties']['code']))
268 elif type(crs) is str:
269 # Like "EPSG:4326"
270 spatial_ref.SetFromUserInput(crs)
271 elif type(crs) is int:
272 # Like 4326
273 spatial_ref.ImportFromEPSG(crs)
274 return spatial_ref
275
276 @staticmethod
277 def geojson2gml_filter(value, source_crs=4326, target_crs=None, gml_id=None, gml_format='GML2', gml_longsrs='NO'):
278 """
279 Jinja2 custom Filter: generates any GML geometry from a GeoJSON geometry.
280 By specifying a target_crs we can even reproject from the source CRS.
281 The gml_format=GML2|GML3 determines the general GML form: e.g. pos/posList
282 or coordinates. gml_longsrs=YES|NO determines the srsName format like EPSG:4326 or
283 urn:ogc:def:crs:EPSG::4326 (long).
284 """
285 # Import Python OGR lib once
286 Jinja2TemplatingFilter.import_ogr()
287
288 try:
289 # Create an OGR geometry from a GeoJSON string
290 geojson_str = Jinja2TemplatingFilter.json_package.dumps(value)
291 geom = Jinja2TemplatingFilter.ogr_package.CreateGeometryFromJson(geojson_str)
292
293 # Create and assign CRS from source CRS
294 source_spatial_ref = Jinja2TemplatingFilter.create_spatial_ref(source_crs)
295 geom.AssignSpatialReference(source_spatial_ref)
296
297 # Optional: reproject Geometry from source CRS to target CRS
298 if target_crs is not None:
299 target_spatial_ref = Jinja2TemplatingFilter.create_spatial_ref(target_crs)
300 transform = Jinja2TemplatingFilter.osr_package.CoordinateTransformation(source_spatial_ref,
301 target_spatial_ref)
302 geom.Transform(transform)
303
304 # Generate the GML Geometry elements as string, GMLID is optional
305 options = ['FORMAT=%s' % gml_format, 'GML3_LONGSRS=%s' % gml_longsrs]
306 if gml_id is not None:
307 options.append('GMLID=%s' % gml_id)
308
309 gml_str = geom.ExportToGML(options=options)
310 except Exception as e:
311 gml_str = 'Failure in CreateGeometryFromJson or ExportToGML, err= %s; check your data and Stetl log' % str(
312 e)
313 log.error(gml_str)
314
315 return gml_str