diff options
Diffstat (limited to 'rss.py')
-rw-r--r-- | rss.py | 68 |
1 files changed, 68 insertions, 0 deletions
@@ -0,0 +1,68 @@ | |||
1 | #!/usr/bin/env python | ||
2 | # -*- coding: utf-8 -*- | ||
3 | # Created by [email protected] at 2015-07-30 | ||
4 | |||
5 | import os | ||
6 | import argparse | ||
7 | import yaml | ||
8 | |||
9 | import jinja2 | ||
10 | |||
11 | |||
12 | class FilePathLoader(jinja2.BaseLoader): | ||
13 | """ Custom Jinja2 template loader which just loads a single template file """ | ||
14 | |||
15 | def __init__(self, cwd): | ||
16 | self.cwd = cwd | ||
17 | |||
18 | def get_source(self, environment, template): | ||
19 | # Path | ||
20 | filename = os.path.join(self.cwd, template) | ||
21 | |||
22 | # Read | ||
23 | try: | ||
24 | with open(filename, 'r') as f: | ||
25 | contents = f.read() | ||
26 | except IOError: | ||
27 | raise jinja2.TemplateNotFound(filename) | ||
28 | |||
29 | # Finish | ||
30 | uptodate = lambda: False | ||
31 | return contents, filename, uptodate | ||
32 | |||
33 | |||
34 | def render_template(cwd, template_path, context): | ||
35 | env = jinja2.Environment(loader=FilePathLoader(cwd)) | ||
36 | |||
37 | return env \ | ||
38 | .get_template(template_path) \ | ||
39 | .render(context) | ||
40 | |||
41 | |||
42 | def main(): | ||
43 | parser = argparse.ArgumentParser() | ||
44 | |||
45 | parser.add_argument('--dir', default='.', help='Template directory') | ||
46 | parser.add_argument('--data', nargs='*', help='One or more YAML data file') | ||
47 | parser.add_argument('--template', help='Template file to process') | ||
48 | parser.add_argument('--body', help='Body content') | ||
49 | args = parser.parse_args() | ||
50 | |||
51 | context = dict() | ||
52 | for data_f in args.data if args.data else []: | ||
53 | key, filename = data_f.split(':') | ||
54 | if filename: | ||
55 | context[key] = yaml.load(open(filename).read()) | ||
56 | else: | ||
57 | context[key] = {'_': True} | ||
58 | if args.body: | ||
59 | context['body'] = open(args.body).read() | ||
60 | |||
61 | return render_template( | ||
62 | args.dir, | ||
63 | args.template, | ||
64 | context | ||
65 | ) | ||
66 | |||
67 | if __name__ == '__main__': | ||
68 | print(main()) | ||