This repository was archived by the owner on Sep 29, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdefault.py
More file actions
919 lines (727 loc) · 29.6 KB
/
default.py
File metadata and controls
919 lines (727 loc) · 29.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
# -*- coding: utf-8 -*-
import utils as jinjaUtils
from wrap import ListWrapper, SkelListWrapper
from server import utils, request, errors, securitykey
from server.skeleton import Skeleton, BaseSkeleton, RefSkel, skeletonByKind
from server.bones import *
from collections import OrderedDict
from jinja2 import Environment, FileSystemLoader, ChoiceLoader
import os, logging, codecs
class Render( object ):
"""
The core jinja2 render.
This is the bridge between your ViUR modules and your templates.
First, the default jinja2-api is exposed to your templates. See http://jinja.pocoo.org/ for
more information. Second, we'll pass data das global variables to templates depending on the
current action.
- For list() we'll pass `skellist` - a :py:class:`server.render.jinja2.default.SkelListWrapper` instance
- For view(): skel - a dictionary with values from the skeleton prepared for use inside html
- For add()/edit: a dictionary as `skel` with `values`, `structure` and `errors` as keys.
Third, a bunch of global filters (like urlencode) and functions (getEntry, ..) are available to templates.
See the ViUR Documentation for more information about functions and data available to jinja2 templates.
Its possible for modules to extend the list of filters/functions available to templates by defining
a function called `jinjaEnv`. Its called from the render when the environment is first created and
can extend/override the functionality exposed to templates.
"""
listTemplate = "list"
viewTemplate = "view"
addTemplate = "add"
editTemplate = "edit"
addSuccessTemplate = "add_success"
editSuccessTemplate = "edit_success"
deleteSuccessTemplate = "delete_success"
listRepositoriesTemplate = "list_repositories"
listRootNodeContentsTemplate = "list_rootNode_contents"
addDirSuccessTemplate = "add_dir_success"
renameSuccessTemplate = "rename_success"
copySuccessTemplate = "copy_success"
reparentSuccessTemplate = "reparent_success"
setIndexSuccessTemplate = "setindex_success"
cloneSuccessTemplate = "clone_success"
__haveEnvImported_ = False
class KeyValueWrapper:
"""
This holds one Key-Value pair for
selectOne/selectMulti Bones.
It allows to directly treat the key as string,
but still makes the translated description of that
key available.
"""
def __init__( self, key, descr ):
self.key = key
self.descr = _( descr )
def __str__( self ):
return( unicode( self.key ) )
def __repr__( self ):
return( unicode( self.key ) )
def __eq__( self, other ):
return( unicode( self ) == unicode( other ) )
def __lt__( self, other ):
return( unicode( self ) < unicode( other ) )
def __gt__( self, other ):
return( unicode( self ) > unicode( other ) )
def __le__( self, other ):
return( unicode( self ) <= unicode( other ) )
def __ge__( self, other ):
return( unicode( self ) >= unicode( other ) )
def __trunc__( self ):
return( self.key.__trunc__() )
def __init__(self, parent=None, *args, **kwargs ):
super( Render, self ).__init__(*args, **kwargs)
if not Render.__haveEnvImported_:
# We defer loading our plugins to this point to avoid circular imports
import env
Render.__haveEnvImported_ = True
self.parent = parent
def getTemplateFileName( self, template, ignoreStyle=False ):
"""
Returns the filename of the template.
This function decides in which language and which style a given template is rendered.
The style is provided as get-parameters for special-case templates that differ from
their usual way.
It is advised to override this function in case that
:func:`server.render.jinja2.default.Render.getLoaders` is redefined.
:param template: The basename of the template to use.
:type template: str
:param ignoreStyle: Ignore any maybe given style hints.
:type ignoreStyle: bool
:returns: Filename of the template
:rtype: str
"""
validChars = "abcdefghijklmnopqrstuvwxyz1234567890-"
if "htmlpath" in dir( self ):
htmlpath = self.htmlpath
else:
htmlpath = "html"
if not ignoreStyle\
and "style" in request.current.get().kwargs\
and all( [ x in validChars for x in request.current.get().kwargs["style"].lower() ] ):
stylePostfix = "_"+request.current.get().kwargs["style"]
else:
stylePostfix = ""
lang = request.current.get().language #session.current.getLanguage()
fnames = [ template+stylePostfix+".html", template+".html" ]
if lang:
fnames = [ os.path.join( lang, template+stylePostfix+".html"),
template+stylePostfix+".html",
os.path.join( lang, template+".html"),
template+".html" ]
for fn in fnames: #check subfolders
prefix = template.split("_")[0]
if os.path.isfile(os.path.join(os.getcwd(), htmlpath, prefix, fn)):
return ( "%s/%s" % (prefix, fn ) )
for fn in fnames: #Check the templatefolder of the application
if os.path.isfile( os.path.join( os.getcwd(), htmlpath, fn ) ):
self.checkForOldLinePrefix( os.path.join( os.getcwd(), htmlpath, fn ) )
return( fn )
for fn in fnames: #Check the fallback
if os.path.isfile( os.path.join( os.getcwd(), "server", "template", fn ) ):
self.checkForOldLinePrefix( os.path.join( os.getcwd(), "server", "template", fn ) )
return( fn )
raise errors.NotFound( "Template %s not found." % template )
def checkForOldLinePrefix(self, fn):
"""
This method checks the given template for lines starting with "##" - the old, now unsupported
Line-Prefix. Bail out if such prefixes are used. This is a temporary safety measure; will be
removed after 01.05.2017.
:param fn: The filename to check
:return:
"""
if not "_safeTemplatesCache" in dir( self ):
self._safeTemplatesCache = [] #Scan templates at most once per instance
if fn in self._safeTemplatesCache:
return #This template has already been checked and looks okay
tplData = open( fn, "r" ).read()
for l in tplData.splitlines():
if l.strip(" \t").startswith("##"):
raise SyntaxError("Template %s contains unsupported Line-Markers (##)" % fn )
self._safeTemplatesCache.append( fn )
return
def getLoaders(self):
"""
Return the list of Jinja2 loaders which should be used.
May be overridden to provide an alternative loader
(e.g. for fetching templates from the datastore).
"""
if "htmlpath" in dir( self ):
htmlpath = self.htmlpath
else:
htmlpath = "html/"
return ChoiceLoader([FileSystemLoader(htmlpath), FileSystemLoader("server/template/")])
def renderBoneStructure(self, bone):
"""
Renders the structure of a bone.
This function is used by :func:`renderSkelStructure`.
can be overridden and super-called from a custom renderer.
:param bone: The bone which structure should be rendered.
:type bone: Any bone that inherits from :class:`server.bones.base.baseBone`.
:return: A dict containing the rendered attributes.
:rtype: dict
"""
# Base bone contents.
ret = {
"descr": _(bone.descr),
"type": bone.type,
"required":bone.required,
"params":bone.params,
"visible": bone.visible,
"readOnly": bone.readOnly
}
if bone.type == "relational" or bone.type.startswith("relational."):
if isinstance(bone, hierarchyBone):
boneType = "hierarchy"
elif isinstance(bone, treeItemBone):
boneType = "treeitem"
else:
boneType = "relational"
ret.update({
"type": bone.type,
"module": bone.module,
"multiple": bone.multiple,
"format": bone.format,
"using": self.renderSkelStructure(bone.using()) if bone.using else None,
"relskel": self.renderSkelStructure(RefSkel.fromSkel(skeletonByKind(bone.kind), *bone.refKeys))
})
elif bone.type == "select" or bone.type.startswith("select."):
ret.update({
"values": OrderedDict([(k, _(v)) for (k, v) in bone.values.items()]),
"multiple": bone.multiple
})
elif bone.type == "date" or bone.type.startswith("date."):
ret.update({
"date": bone.date,
"time": bone.time
})
elif bone.type == "numeric" or bone.type.startswith("numeric."):
ret.update({
"precision": bone.precision,
"min": bone.min,
"max": bone.max
})
elif bone.type == "text" or bone.type.startswith("text."):
ret.update({
"validHtml": bone.validHtml,
"languages": bone.languages
})
elif bone.type == "str" or bone.type.startswith("str."):
ret.update({
"languages": bone.languages,
"multiple": bone.multiple
})
elif bone.type == "captcha" or bone.type.startswith("captcha."):
ret.update({
"publicKey": bone.publicKey,
})
return ret
def renderSkelStructure(self, skel):
"""
Dumps the structure of a :class:`server.db.skeleton.Skeleton`.
:param skel: Skeleton which structure will be processed.
:type skel: server.db.skeleton.Skeleton
:returns: The rendered dictionary.
:rtype: dict
"""
res = OrderedDict()
for key, bone in skel.items():
if "__" in key or not isinstance(bone, baseBone):
continue
res[key] = self.renderBoneStructure(bone)
if key in skel.errors:
res[key]["error"] = skel.errors[ key ]
else:
res[key]["error"] = None
return res
def renderBoneValue(self, bone, skel, key):
"""
Renders the value of a bone.
This function is used by :func:`collectSkelData`.
It can be overridden and super-called from a custom renderer.
:param bone: The bone which value should be rendered.
:type bone: Any bone that inherits from :class:`server.bones.base.baseBone`.
:return: A dict containing the rendered attributes.
:rtype: dict
"""
if bone.type == "select" or bone.type.startswith("select."):
skelValue = skel[key]
if isinstance(skelValue, list):
return [
Render.KeyValueWrapper(val, bone.values[val]) if val in bone.values else val
for val in skelValue
]
elif skelValue in bone.values:
return Render.KeyValueWrapper(skelValue, bone.values[skelValue])
return skelValue
elif bone.type=="relational" or bone.type.startswith("relational."):
if isinstance(skel[key], list):
tmpList = []
for k in skel[key]:
refSkel = bone._refSkelCache
refSkel.setValuesCache(k["dest"])
if bone.using is None:
tmpList.append(self.collectSkelData(refSkel))
else:
usingSkel = bone._usingSkelCache
if k["rel"]:
usingSkel.setValuesCache(k["rel"])
usingData = self.collectSkelData(usingSkel)
else:
usingData = None
tmpList.append({
"dest": self.collectSkelData(refSkel),
"rel": usingData
})
return tmpList
elif isinstance(skel[key], dict):
refSkel = bone._refSkelCache
refSkel.setValuesCache(skel[key]["dest"])
if bone.using is None:
return self.collectSkelData(refSkel)
else:
usingSkel = bone._usingSkelCache
if skel[key]["rel"]:
usingSkel.setValuesCache(skel[key]["rel"])
usingData = self.collectSkelData(usingSkel)
else:
usingData = None
return {
"dest": self.collectSkelData(refSkel),
"rel": usingData
}
else:
return None
else:
return skel[key]
return None
def collectSkelData(self, skel):
"""
Prepares values of one :class:`server.db.skeleton.Skeleton` or a list of skeletons for output.
:param skel: Skeleton which contents will be processed.
:type skel: server.db.skeleton.Skeleton
:returns: A dictionary or list of dictionaries.
:rtype: dict | list
"""
if isinstance(skel, list):
return [self.collectSkelData(x) for x in skel]
res = {}
for key, bone in skel.items():
val = self.renderBoneValue(bone, skel, key)
res[key] = val
if isinstance(res[key], list):
res[key] = ListWrapper(res[key])
return res
def add(self, skel, tpl=None, params=None, *args, **kwargs):
"""
Renders a page for adding an entry.
The template must construct the HTML-form on itself; the required information
are passed via skel.structure, skel.value and skel.errors.
A jinja2-macro, which builds such kind of forms, is shipped with the server.
Any data in \*\*kwargs is passed unmodified to the template.
:param skel: Skeleton of the entry which should be created.
:type skel: server.db.skeleton.Skeleton
:param tpl: Name of a different template, which should be used instead of the default one.
:type tpl: str
:param params: Optional data that will be passed unmodified to the template
:type params: object
:return: Returns the emitted HTML response.
:rtype: str
"""
if not tpl and "addTemplate" in dir( self.parent ):
tpl = self.parent.addTemplate
tpl = tpl or self.addTemplate
template = self.getEnv().get_template(self.getTemplateFileName(tpl))
skel = skel.clone() # Fixme!
skeybone = baseBone(descr="SecurityKey", readOnly=True, visible=False)
skel.skey = skeybone
skel["skey"] = securitykey.create()
if "nomissing" in request.current.get().kwargs and request.current.get().kwargs["nomissing"]=="1":
if isinstance(skel, BaseSkeleton):
super(BaseSkeleton, skel).__setattr__( "errors", {} )
return template.render(skel={ "structure":self.renderSkelStructure(skel),
"errors":skel.errors,
"value":self.collectSkelData(skel) },
params = params, **kwargs)
def edit(self, skel, tpl=None, params=None, **kwargs):
"""
Renders a page for modifying an entry.
The template must construct the HTML-form on itself; the required information
are passed via skel.structure, skel.value and skel.errors.
A jinja2-macro, which builds such kind of forms, is shipped with the server.
Any data in \*\*kwargs is passed unmodified to the template.
:param skel: Skeleton of the entry which should be modified.
:type skel: server.db.skeleton.Skeleton
:param tpl: Name of a different template, which should be used instead of the default one.
:type tpl: str
:param params: Optional data that will be passed unmodified to the template
:type params: object
:return: Returns the emitted HTML response.
:rtype: str
"""
if not tpl and "editTemplate" in dir( self.parent ):
tpl = self.parent.editTemplate
tpl = tpl or self.editTemplate
template = self.getEnv().get_template(self.getTemplateFileName(tpl))
skel = skel.clone() # Fixme!
skeybone = baseBone(descr="SecurityKey", readOnly=True, visible=False)
skel.skey = skeybone
skel["skey"] = securitykey.create()
if "nomissing" in request.current.get().kwargs and request.current.get().kwargs["nomissing"]=="1":
if isinstance(skel, BaseSkeleton):
super(BaseSkeleton, skel).__setattr__("errors", {})
return template.render( skel={"structure": self.renderSkelStructure(skel),
"errors": skel.errors,
"value": self.collectSkelData(skel) },
params=params, **kwargs )
def addItemSuccess(self, skel, tpl = None, params = None, *args, **kwargs):
"""
Renders a page, informing that the entry has been successfully created.
:param skel: Skeleton which contains the data of the new entity
:type skel: server.db.skeleton.Skeleton
:param tpl: Name of a different template, which should be used instead of the default one.
:type tpl: str
:param params: Optional data that will be passed unmodified to the template
:type params: object
:return: Returns the emitted HTML response.
:rtype: str
"""
if not tpl:
if "addSuccessTemplate" in dir( self.parent ):
tpl = self.parent.addSuccessTemplate
else:
tpl = self.addSuccessTemplate
template = self.getEnv().get_template( self.getTemplateFileName( tpl ) )
res = self.collectSkelData( skel )
return template.render({ "skel":res }, params=params, **kwargs)
def editItemSuccess(self, skel, tpl = None, params = None, *args, **kwargs):
"""
Renders a page, informing that the entry has been successfully modified.
:param skel: Skeleton which contains the data of the modified entity
:type skel: server.db.skeleton.Skeleton
:param tpl: Name of a different template, which should be used instead of the default one.
:type tpl: str
:param params: Optional data that will be passed unmodified to the template
:type params: object
:return: Returns the emitted HTML response.
:rtype: str
"""
if not tpl:
if "editSuccessTemplate" in dir(self.parent):
tpl = self.parent.editSuccessTemplate
else:
tpl = self.editSuccessTemplate
template = self.getEnv().get_template( self.getTemplateFileName( tpl ) )
res = self.collectSkelData( skel )
return template.render(skel=res, params=params, **kwargs)
def deleteSuccess(self, skel, tpl = None, params = None, *args, **kwargs):
"""
Renders a page, informing that the entry has been successfully deleted.
The provided parameters depend on the application calling this:
List and Hierarchy pass the id of the deleted entry, while Tree passes
the rootNode and path.
:param params: Optional data that will be passed unmodified to the template
:type params: object
:param tpl: Name of a different template, which should be used instead of the default one.
:type tpl: str
:return: Returns the emitted HTML response.
:rtype: str
"""
if not tpl:
if "deleteSuccessTemplate" in dir(self.parent):
tpl = self.parent.deleteSuccessTemplate
else:
tpl = self.deleteSuccessTemplate
template = self.getEnv().get_template( self.getTemplateFileName( tpl ) )
return template.render(params=params, **kwargs)
def list( self, skellist, tpl=None, params=None, **kwargs ):
"""
Renders a list of entries.
Any data in \*\*kwargs is passed unmodified to the template.
:param skellist: List of Skeletons with entries to display.
:type skellist: server.db.skeleton.SkelList
:param tpl: Name of a different template, which should be used instead of the default one.
:param: tpl: str
:param params: Optional data that will be passed unmodified to the template
:type params: object
:return: Returns the emitted HTML response.
:rtype: str
"""
if not tpl and "listTemplate" in dir( self.parent ):
tpl = self.parent.listTemplate
tpl = tpl or self.listTemplate
try:
fn = self.getTemplateFileName( tpl )
except errors.HTTPException as e: #Not found - try default fallbacks FIXME: !!!
tpl = "list"
template = self.getEnv().get_template( self.getTemplateFileName( tpl ) )
resList = []
for skel in skellist:
resList.append( self.collectSkelData(skel) )
return template.render(skellist=SkelListWrapper(resList, skellist), params=params, **kwargs)
def listRootNodes(self, repos, tpl=None, params=None, **kwargs ):
"""
Renders a list of available repositories.
:param repos: List of repositories (dict with "key"=>Repo-Key and "name"=>Repo-Name)
:type repos: list
:param tpl: Name of a different template, which should be used instead of the default one.
:param: tpl: str
:param params: Optional data that will be passed unmodified to the template
:type params: object
:return: Returns the emitted HTML response.
:rtype: str
"""
if "listRepositoriesTemplate" in dir( self.parent ):
tpl = tpl or self.parent.listTemplate
if not tpl:
tpl = self.listRepositoriesTemplate
try:
fn = self.getTemplateFileName( tpl )
except errors.HTTPException as e: #Not found - try default fallbacks FIXME: !!!
tpl = "list"
template = self.getEnv().get_template( self.getTemplateFileName( tpl ) )
return template.render(repos=repos, params=params, **kwargs)
def view( self, skel, tpl=None, params=None, **kwargs ):
"""
Renders a single entry.
Any data in \*\*kwargs is passed unmodified to the template.
:param skel: Skeleton to be displayed.
:type skellist: server.db.skeleton.Skeleton
:param tpl: Name of a different template, which should be used instead of the default one.
:param: tpl: str
:param params: Optional data that will be passed unmodified to the template
:type params: object
:return: Returns the emitted HTML response.
:rtype: str
"""
if not tpl and "viewTemplate" in dir( self.parent ):
tpl = self.parent.viewTemplate
tpl = tpl or self.viewTemplate
template = self.getEnv().get_template( self.getTemplateFileName( tpl ) )
if isinstance( skel, Skeleton ):
res = self.collectSkelData( skel )
else:
res = skel
return template.render(skel=res, params=params, **kwargs)
## Extended functionality for the Tree-Application ##
def listRootNodeContents( self, subdirs, entries, tpl=None, params=None, **kwargs):
"""
Renders the contents of a given RootNode.
This differs from list(), as one level in the tree-application may contains two different
child-types: Entries and folders.
:param subdirs: List of (sub-)directories on the current level
:type repos: list
:param entries: List of entries of the current level
:type entries: server.db.skeleton.SkelList
:param tpl: Name of a different template, which should be used instead of the default one
:param: tpl: str
:param params: Optional data that will be passed unmodified to the template
:type params: object
:return: Returns the emitted HTML response.
:rtype: str
"""
if "listRootNodeContentsTemplate" in dir( self.parent ):
tpl = tpl or self.parent.listRootNodeContentsTemplate
else:
tpl = tpl or self.listRootNodeContentsTemplate
template= self.getEnv().get_template( self.getTemplateFileName( tpl ) )
return template.render(subdirs=subdirs, entries=[self.collectSkelData( x ) for x in entries], params=params, **kwargs)
def addDirSuccess(self, rootNode, path, dirname, params=None, *args, **kwargs ):
"""
Renders a page, informing that the directory has been successfully created.
:param rootNode: RootNode-key in which the directory has been created
:type rootNode: str
:param path: Path in which the directory has been created
:type path: str
:param dirname: Name of the newly created directory
:type dirname: str
:param params: Optional data that will be passed unmodified to the template
:type params: object
:return: Returns the emitted HTML response.
:rtype: str
"""
tpl = self.addDirSuccessTemplate
if "addDirSuccessTemplate" in dir( self.parent ):
tpl = self.parent.addDirSuccessTemplate
template = self.getEnv().get_template( self.getTemplateFileName( tpl ) )
return template.render(rootNode=rootNode, path=path, dirname=dirname, params=params)
def renameSuccess(self, rootNode, path, src, dest, params=None, *args, **kwargs ):
"""
Renders a page, informing that the entry has been successfully renamed.
:param rootNode: RootNode-key in which the entry has been renamed
:type rootNode: str
:param path: Path in which the entry has been renamed
:type path: str
:param src: Old name of the entry
:type src: str
:param dest: New name of the entry
:type dest: str
:param params: Optional data that will be passed unmodified to the template
:type params: object
:return: Returns the emitted HTML response.
:rtype: str
"""
tpl = self.renameSuccessTemplate
if "renameSuccessTemplate" in dir( self.parent ):
tpl = self.parent.renameSuccessTemplate
template = self.getEnv().get_template( self.getTemplateFileName( tpl ) )
return template.render(rootNode=rootNode, path=path, src=src, dest=dest,params=params)
def copySuccess(self, srcrepo, srcpath, name, destrepo, destpath, type, deleteold, params=None, *args, **kwargs ):
"""
Renders a page, informing that an entry has been successfully copied/moved.
:param srcrepo: RootNode-key from which has been copied/moved
:type srcrepo: str
:param srcpath: Path from which the entry has been copied/moved
:type srcpath: str
:param name: Name of the entry which has been copied/moved
:type name: str
:param destrepo: RootNode-key to which has been copied/moved
:type destrepo: str
:param destpath: Path to which the entries has been copied/moved
:type destpath: str
:param type: "entry": Copy/Move an entry, everything else: Copy/Move an directory
:type type: str
:param deleteold: "0": Copy, "1": Move
:type deleteold: str
:param params: Optional data that will be passed unmodified to the template
:type params: object
:return: Returns the emitted HTML response.
:rtype: str
"""
tpl = self.copySuccessTemplate
if "copySuccessTemplate" in dir( self.parent ):
tpl = self.parent.copySuccessTemplate
template = self.getEnv().get_template( self.getTemplateFileName( tpl ) )
return template.render(srcrepo=srcrepo, srcpath=srcpath, name=name, destrepo=destrepo, destpath=destpath, type=type, deleteold=deleteold, params=params)
def reparentSuccess(self, obj, tpl=None, params=None, **kwargs ):
"""
Renders a page informing that the item was successfully moved.
:param obj: ndb.Expando instance of the item that was moved.
:type obj: ndb.Expando
:param tpl: Name of a different template, which should be used instead of the default one
:type tpl: str
:param params: Optional data that will be passed unmodified to the template
:type params: object
"""
if not tpl:
if "reparentSuccessTemplate" in dir( self.parent ):
tpl = self.parent.reparentSuccessTemplate
else:
tpl = self.reparentSuccessTemplate
template = self.getEnv().get_template( self.getTemplateFileName( tpl ) )
return template.render(repoObj=obj, params=params, **kwargs)
def setIndexSuccess(self, obj, tpl=None, params=None, *args, **kwargs ):
"""
Renders a page informing that the items sortindex was successfully changed.
:param obj: ndb.Expando instance of the item that was changed
:type obj: ndb.Expando
:param tpl: Name of a different template, which should be used instead of the default one
:type tpl: str
:param params: Optional data that will be passed unmodified to the template
:type params: object
:return: Returns the emitted HTML response.
:rtype: str
"""
if not tpl:
if "setIndexSuccessTemplate" in dir( self.parent ):
tpl = self.parent.setIndexSuccessTemplate
else:
tpl = self.setIndexSuccessTemplate
template = self.getEnv().get_template( self.getTemplateFileName( tpl ) )
return template.render( skel=obj, repoObj=obj, params=params, **kwargs )
def cloneSuccess(self, tpl=None, params=None, *args, **kwargs ):
"""
Renders a page informing that the items sortindex was successfully changed.
:param obj: ndb.Expando instance of the item that was changed
:type obj: ndb.Expando
:param tpl: Name of a different template, which should be used instead of the default one
:type tpl: str
:param params: Optional data that will be passed unmodified to the template
:type params: object
:return: Returns the emitted HTML response.
:rtype: str
"""
if not tpl:
if "cloneSuccessTemplate" in dir( self.parent ):
tpl = self.parent.cloneSuccessTemplate
else:
tpl = self.cloneSuccessTemplate
template = self.getEnv().get_template( self.getTemplateFileName( tpl ) )
return template.render(params=params, **kwargs)
def renderEmail(self, skel, tpl, dests, params=None,**kwargs ):
"""
Renders an email.
:param skel: Skeleton or dict which data to supply to the template.
:type skel: server.db.skeleton.Skeleton | dict
:param tpl: Name of the email-template to use. If this string is longer than 100 characters,
this string is interpreted as the template contents instead of its filename.
:type tpl: str
:param dests: Destination recipients.
:type dests: list | str
:param params: Optional data that will be passed unmodified to the template
:type params: object
:return: Returns a tuple consisting of email header and body.
:rtype: str, str
"""
headers = {}
user = utils.getCurrentUser()
if isinstance(skel, BaseSkeleton):
res = self.collectSkelData( skel )
elif isinstance(skel, list) and all([isinstance(x, BaseSkeleton) for x in skel]):
res = [ self.collectSkelData( x ) for x in skel ]
else:
res = skel
if len(tpl)<101:
try:
template = self.getEnv().from_string( codecs.open( "emails/"+tpl+".email", "r", "utf-8" ).read() )
except Exception as err:
logging.exception(err)
template = self.getEnv().get_template( tpl+".email" )
else:
template = self.getEnv().from_string( tpl )
data = template.render(skel=res, dests=dests, user=user, params=params, **kwargs)
body = False
lineCount=0
for line in data.splitlines():
if lineCount>3 and body is False:
body = "\n\n"
if body != False:
body += line+"\n"
else:
if line.lower().startswith("from:"):
headers["from"]=line[ len("from:"):]
elif line.lower().startswith("subject:"):
headers["subject"]=line[ len("subject:"): ]
elif line.lower().startswith("references:"):
headers["references"]=line[ len("references:"):]
else:
body="\n\n"
body += line
lineCount += 1
return( headers, body )
def getEnv(self):
"""
Constucts the Jinja2 environment.
If an application specifies an jinja2Env function, this function
can alter the environment before its used to parse any template.
:returns: Extended Jinja2 environment.
:rtype: jinja2.Environment
"""
def mkLambda(func, s):
return lambda *args, **kwargs: func(s, *args, **kwargs)
if not "env" in dir(self):
loaders = self.getLoaders()
self.env = Environment(loader=loaders, extensions=["jinja2.ext.do", "jinja2.ext.loopcontrols"])
# Translation remains global
self.env.globals["_"] = _
self.env.filters["tr"] = _
# Import functions.
for name, func in jinjaUtils.getGlobalFunctions().items():
self.env.globals[name] = mkLambda(func, self)
# Import filters.
for name, func in jinjaUtils.getGlobalFilters().items():
self.env.filters[name] = mkLambda(func, self)
# Import extensions.
for ext in jinjaUtils.getGlobalExtensions():
self.env.add_extension(ext)
# Import module-specific environment, if available.
if "jinjaEnv" in dir(self.parent):
self.env = self.parent.jinjaEnv(self.env)
return self.env