我只是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))

最佳答案

在您的代码段中:

extracted_output = json.dumps(dictionary_extracted)
template = jinja2_environment.get_template('template/post.html')
self.response.write(template.render(extracted_output))
json.dumps返回一个字符串-然后,您只将该字符串传递给template.render ...,它将永远无法工作!

如您在评论中所述(您应该编辑问题以使其更清楚!),如果模板包含的是{{extracted_output}},那么该变量名称必须传递给render,即,最后一条语句必须变为
self.response.write(template.render(extracted_output=extracted_output))

09-25 21:19