【发布时间】:2010-05-18 13:38:32
【问题描述】:
在编码了大约 6-9 个月之后。在阅读了一些代码或阅读了最佳实践之后,我可能多次改变了我的编码风格。但是我还没有解决的一件事就是为什么要填充 template_dict。
到目前为止,我将 template_dict 传递给许多方法(更改/修改它)并返回。结果是每个方法都将 template_dict 作为第一个参数并返回它,在我看来这似乎不是最好的解决方案。
一个想法是有一个方法来处理所有的变化。但是我很好奇是否有最佳实践?还是“做你想做的事”之类的?
我认为非常难看的两件事是作为参数发送并在所有方法中返回它。而只是var名称在代码中被写了xxx次:)
..弗雷德里克
编辑:
为了演示我对 template_dict 的意思(我认为这是一个通用术语,我从 django 模板方法的 google 实现中得到它)。
我有一个通过 render.template 方法传递给模板的 dict:
template.render(path, template_dict) #from google.appengine.ext.webapp import template
我需要操作这个 template_dict 以便将数据/字典/列表发送到视图(html 文件)。如果我没记错的话。
因此,考虑到这一点,我的代码通常最终看起来像这样:
## Main.py file to handle the request and imports classes.
from models import data
from util import foo
class MainHandler(webapp.RequestHandler):
template_dict = { 'lang' : 'en' }
## reads all current keys and returns dict w/ new keys, if needed
template_dict = data.getData(template_dict)
if 'unsorted_list' in template_dict:
template_dict = util.foo(template_dict)
## and so on....
path = os.path.join(os.path.dirname(__file__), 'templates', file)
self.response.out.write(template.render(path, template_dict))
在我的大多数应用程序中,许多返回和集合不会出现在 main.py 中,而是出现在其他类和方法中。
但你应该做大体的想法。
【问题讨论】:
-
什么是'template_dict'?你谈论它好像它是 Django 的一个众所周知的部分,但我从未听说过或使用它。显示一些代码来演示它的作用。
-
我假设他指的是您在 render_to_response 方法中传递给模板的字典......但我无法想象为什么您必须将它传递给多个方法。我同意,需要代码示例。
-
@Daniel 和 Chris:我会更新一些代码来说明我的意思。
-
这似乎与 Django 没有任何关系。您正在使用 GAE 自己的迷你框架 webapp。适当更改标题和标签。
-
@Daniel:没错。但由于谷歌使用 djangos 模板和上下文(来自 django.template)从文件中渲染它的模板,然后将 Context 应用于它以替换匹配字典中的所有 django 标签。这是否也适用于 django 用户?
标签: python google-app-engine web-applications