是否可以通过对象的字典更新Google App Engine数据存储中的条目?

0 投票
2 回答
958 浏览
提问于 2025-04-15 13:29

我试了下面的代码,但没有成功:

class SourceUpdate(webapp.RequestHandler):
  def post(self):
    id = int(self.request.get('id'))
    source = Source.get_by_id(id)
    for property in self.request.arguments():
      if property != 'id':
        source.__dict__[property] = self.request.get(property)
    source.put()
    self.redirect('/source')

我已经发送了所有必要的属性,但条目没有更新,也没有显示任何错误。该怎么解决呢?

顺便说一下

class Source(db.Model):
  #some string properties

2 个回答

2

与其直接从请求中设置模型的值,不如考虑使用Django表单。Django表单是和App Engine一起提供的,它可以帮助你验证表单数据、将数据存储到数据库中,还能生成表单的HTML代码。关于如何在App Engine的数据库中使用Django表单,有一篇文章可以参考,点击这里

另外,记得基于GET请求进行修改几乎总是个坏主意,这样做可能会导致XSRF漏洞和其他问题哦!

2

你现在绕过了模型的元类(type(type(source)))通常用来正确处理属性设置的功能。你需要把内部循环改成:

for property in self.request.arguments():
  if property != 'id':
    setattr(source, property, self.request.get(property))

这样一来,所有东西应该就能正常工作了(前提是所有属性的类型都能从字符串正确设置,因为你从request.get得到的就是字符串)。

撰写回答