我正在使用 jQuery 的 AJAX 函数,如下所示:
$.ajax ({ "url" : "/note",
"async" : true,
"type" : "POST",
"data" : {"id" : id, "content" : el.value}
});
在后端(Python Google App Engine,目前使用 webapp.RequestHandler),PUT 请求由处理 POST 请求的同一函数处理,如下所示:
class uNote(webapp.RequestHandler):
def post(self):
user = users.get_current_user()
if user:
logging.critical("ID: " + self.request.get('id'))
note = stickynote.db.get( self.request.get('id') )
if note:
content = self.request.get( 'content' )
if content:
note.content = content
else:
note.x = int(self.request.get('x'))
note.y = int(self.request.get('y'))
note.z = int(self.request.get('z'))
note.put()
self.response.out.write ( "true" );
else:
self.response.out.write ("no id found")
def put(self):
user = users.get_current_user()
if user:
logging.critical("ID: " + self.request.get('id'))
note = stickynote.db.get( self.request.get('id') )
if note:
content = self.request.get( 'content' )
if content:
note.content = content
else:
note.x = int(self.request.get('x'))
note.y = int(self.request.get('y'))
note.z = int(self.request.get('z'))
note.put()
self.response.out.write ( "true" );
else:
self.response.out.write ("no id found")
如果我发出 POST 请求,一切正常。如果我将其更改为 PUT 请求(通过更改 AJAX 调用的类型),则没有任何效果。如果我检查 GAE 的日志,我会看到:
BadKeyError: Invalid string key .
这是我记录每次通话 ID 的结果:
ID: ahFkZXZ-YXp2ZC13ZWJub3Rlc3ItCxIKU3RpY2t5Tm90ZSIQdGVzdEBleGFtcGxlLmNvbQwLEgdzbk1vZGVsGAIM (from the POST call)
ID: (from the PUT call)
很明显,它没有为 PUT 调用正确传递 ID,这就是数据存储区给我一个 BadKeyError 的原因。我不确定这是 jQuery 方面的问题,还是来自 GAE 方面的问题,而且我不知道发生了什么。任何帮助将不胜感激。
最佳答案
self.request.POST
,因此 self.request.get()
don't return form data for PUT requests (或任何非 POST 请求)。虽然使用 PUT 请求提交表单数据并不常见(更常见的是,您提交的内容作为请求的主体),但他们故意在此处禁用它确实有点奇怪。
如果你想访问数据,你需要自己从正文中解码它,或者使用 urlparse.parse_qs(self.request.body)
,或者 like this .
另一种选择是修改您的 API,这样您就不会使用表单数据 - 例如,通过将 ID 作为 URL 的一部分,并将内容作为 PUT 请求的原始主体发送。
关于jquery - 使用 jquery/python GAE 破坏 PUT 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7020562/