【问题标题】:Google App Engine JSON Property ErrorGoogle App Engine JSON 属性错误
【发布时间】:2015-09-04 14:10:58
【问题描述】:

我只是 python/json 的初学者。我有一个 html 文档,基本上允许人们输入 (1) 类名和 (1) prereq。在我的 post 方法中,我尝试创建一个新字典,添加(键)类名和(值)prereq。但是我收到了这个回溯错误:

Traceback (most recent call last):
File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-  .5.2\webapp2.py", line 1535, in __call__
rv = self.handle_exception(request, response, e)
File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2- 2.5.2\webapp2.py", line 1529, in __call__
rv = self.router.dispatch(request, response)
File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1102, in __call__
return handler.dispatch()
File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 572, in dispatch
return self.handle_exception(e, self.app.debug)
File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "C:\Users\Desktop\classes\main.py", line 27, in post
self.response.write(template.render(extracted_output))
File "C:\Program Files (x86)\Google\google_appengine\lib\jinja2-2.6\jinja2\environment.py", line 889, in render
vars = dict(*args, **kwargs)
ValueError: dictionary update sequence element #0 has length 1; 2 is   required

另一个问题是当我创建一个新的Class_Name 对象时,class_title 是否自动成为JsonProperty

class Class_Name(ndb.Model):
    class_title = ndb.JsonProperty()

def post(self):
    classname = self.request.get('classname')
    prereq = self.request.get('prereq')
    new_dictionary = {}
    new_dictionary [classname] = prereq
    new_class = Class_Name(class_title = new_dictionary )
    new_class.put()
    dictionary_extracted = new_class.class_title
    extracted_output = json.dumps(dictionary_extracted)
    template = jinja2_environment.get_template('template/post.html')
    self.response.write(template.render(extracted_output))

【问题讨论】:

  • template.render 需要字典或 kwargs 来定义模板变量,但您传递了 json 字符串。模板需要什么变量名?
  • 对于我的'template/post.html',我所做的就是打印像这样的字典 {{extracted_output}}

标签: json google-app-engine compiler-errors paas


【解决方案1】:

在你的代码 sn-p:

extracted_output = json.dumps(dictionary_extracted)
template = jinja2_environment.get_template('template/post.html')
self.response.write(template.render(extracted_output))

json.dumps 返回一个 string —— 然后你只是将那个 string 传递给 template.render... 这永远无法工作!

如果,正如您在评论中所说(您应该编辑您的问题以使其更清晰!),您的模板包含的是 {{extracted_output}},那么该变量 name 必须传递给 @987654325 @,即最后一条语句必须变成

self.response.write(template.render(extracted_output=extracted_output))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-22
    • 2014-06-30
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 2013-04-09
    • 2011-08-11
    • 2015-07-25
    相关资源
    最近更新 更多