summaryrefslogtreecommitdiff
path: root/planet/shell/dj.py
blob: 96bcd3b6f1cc9e07e4664aabb8873b59aca36be7 (plain)
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
import os.path
import urlparse
import datetime

import tmpl
from planet import config

def DjangoPlanetDate(value):
    return datetime.datetime(*value[:6])

# remap PlanetDate to be a datetime, so Django template authors can use 
# the "date" filter on these values
tmpl.PlanetDate = DjangoPlanetDate

def run(script, doc, output_file=None, options={}):
    """process a Django template file"""

    # this is needed to use the Django template system as standalone
    # I need to re-import the settings at every call because I have to 
    # set the TEMPLATE_DIRS variable programmatically
    from django.conf import settings
    settings._wrapped=None
    try:
        settings.configure(
            DEBUG=True, TEMPLATE_DEBUG=True, 
            TEMPLATE_DIRS=(os.path.dirname(script),)
            )
    except EnvironmentError:
        pass
    from django.template import Context
    from django.template.loader import get_template

    # set up the Django context by using the default htmltmpl 
    # datatype converters
    context = Context()
    context.update(tmpl.template_info(doc))
    context['Config'] = config.planet_options()
    t = get_template(script)

    if output_file:
        reluri = os.path.splitext(os.path.basename(output_file))[0]
        context['url'] = urlparse.urljoin(config.link(),reluri)
        f = open(output_file, 'w')
        ss = t.render(context)
        if isinstance(ss,unicode): ss=ss.encode('utf-8')
        f.write(ss)
        f.close()
    else:
        # @@this is useful for testing purposes, but does it 
        # belong here?
        return t.render(context)