bogen
bogen

Reputation: 10432

how to render django template from code instead of file on Google App Engine

I am writing a Google App Engine webapp that renders some html to a Django template. I want to either render the template using either a file or just some json thats very similar to that in file. Is it possible to use Django to render this to a file that is read in and stored in database? The oldAPI.HTML is just an old version of api.html but with some small changes. Rendering Django to the api-html file works fine.

I understand that you can't store files on GAE, how can i dynamically use Django to render to HTML stored in memory?

path = ""
oldAPI = APIVersion().get_by_key_name(version)
if oldAPI is None:
    path = os.path.join(os.path.dirname(__file__), "api.html")
template_values = {
            'responseDict': responseDict,
            }
        if path:
            self.response.out.write(template.render(path, template_values))
        else:
            self.response.out.write(template.render(oldAPI.html,template_values))

Upvotes: 6

Views: 2117

Answers (3)

NT3RP
NT3RP

Reputation: 15370

In order to render a template 'in memory', there are a few things you'll need to do:

App Engine Setup

First of all, you'll need to ensure that everything is set up correctly for Django. There's a lot of information on the Third-party libraries page, but I'll include it here for your benefit.

In main.py, or (whatever your script handler is), you'll need to add the following lines:

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from google.appengine.dist import use_library
use_library('django', '1.2') # Change to a different version as you like

Don't forget to include django in your app.yaml:

libraries:
    - name: django
      version: "1.2"

Code Setup

Second of all, you'll need to create a Template object, as denoted in the Google App Engine template documentation. For example:

from google.appengine.ext.webapp import template

# Your code...
template_string = "Hello World"
my_template = template.Template(template_string)

# `context` is optional, but will be useful!
# `context` is what will contain any variables, etc. you use in the template
rendered_output = template.render(context)

# Now, do what you like with `rendered_output`!

Upvotes: 4

gioi
gioi

Reputation: 1483

Unfortunately, there's no (builtin) way to do so, but you can get inspired from the function google.appengine.ext.webapp.template._load_user_django (GAE with Python 2.5) or google.appengine.ext.webapp.template._load_internal_django (GAE with Python 2.7) and write your very own wrapper overriding settings and rendering like GAE source does.

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599490

You can instantiate a template from text in Django with just template.Template(my_text).

Upvotes: 2

Related Questions