【问题标题】:how to render django template from code instead of file on Google App Engine如何从代码而不是 Google App Engine 上的文件呈现 django 模板
【发布时间】:2013-03-04 04:43:18
【问题描述】:

我正在编写一个将一些 html 呈现到 Django 模板的 Google App Engine 网络应用程序。我想使用文件或仅使用一些与文件中的非常相似的 json 来呈现模板。是否可以使用 Django 将其呈现为读取并存储在数据库中的文件? oldAPI.HTML 只是 api.html 的旧版本,但有一些小的变化。将 Django 渲染到 api-html 文件可以正常工作。

我知道您不能在 GAE 上存储文件,我如何动态地使用 Django 来呈现存储在内存中的 HTML?

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))

【问题讨论】:

标签: python django google-app-engine django-templates webapp2


【解决方案1】:

为了“在内存中”渲染模板,您需要做一些事情:

App 引擎设置

首先,您需要确保为 Django 正确设置了所有内容。 on the Third-party libraries page 有很多信息,但为了您的利益,我将其包含在此处。

main.py 或(无论您的脚本处理程序是什么)中,您需要添加以下行:

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

不要忘记在您的app.yaml 中包含django

libraries:
    - name: django
      version: "1.2"

代码设置

首先,您需要创建一个Template 对象,如Google App Engine template documentation 中所示。例如:

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`!

【讨论】:

  • 当我尝试这个时,我得到了错误: AssertionError: settings has not been configured in this thread。我还需要启用某种设置吗?
  • 您可能需要在与app.yaml 相同的文件夹中创建一个简单的settings.py 文件。 This article 有一个您可以使用的示例 settings.py 文件。我知道这篇文章已经过时了,但是那个信息应该仍然是相关的。
【解决方案2】:

您可以在 Django 中使用 template.Template(my_text) 从文本中实例化模板。

【讨论】:

  • 我收到 AssertionError: settings has not been configured in this thread 当我尝试从文本实例化模板时。尝试使用 html 和 template.Template("hello world")
  • 也许只是尝试使用StringIO?
  • 使用它的语法是什么?
【解决方案3】:

不幸的是,没有 (builtin) 方法可以这样做,但您可以从函数 google.appengine.ext.webapp.template._load_user_django(使用 Python 2.5 的 GAE)或 google.appengine.ext.webapp.template._load_internal_django(使用 Python 2.7 的 GAE)和编写您自己的包装器,覆盖设置和渲染,就像 GAE 源代码一样。

【讨论】:

    猜你喜欢
    • 2014-12-14
    • 2012-06-09
    • 1970-01-01
    • 2019-05-17
    • 2011-11-13
    • 2012-03-23
    • 2011-08-06
    • 2011-12-19
    • 2010-12-07
    相关资源
    最近更新 更多