How to use delete() method in Google App Engine Python's request handler
In GAE Python, I could use
class MyRequestHandler(webapp.RequestHandler):
def get(self):
pass #Do Something...
def post(self):
pass #Do Something...
To handle GET and POST request. But how can I handle DELETE and PUT? I see delete() and put() in API documentation, but I don't know how to 开发者_JAVA百科write a form to simulate DELETE and PUT.
I know in Rails, I can use post method with a hidden field in form to simulate the requests like this:
<input type="hidden" name="_method" value="delete" />
and Rails handles the dirty works automatically.
Is there any similar way to do it in GAE python?
I searched this in Google, but no luck.
Thanks.
You can use the request method which accepts all the methods like get,post,delete and put. Then you can check it for the request type accordingly.
Check this:
http://gdata-python-client.googlecode.com/svn/trunk/pydocs/gdata.urlfetch.html
<form method="post" action="">
<input type="hidden" name="_method" value="put" />
<input type="text" name="name" value="" />
<input type="submit" value="Save" />
</form>
def post(self):
method= self.request.get("_method")
if method == 'put':
#call put() function as required
you can go through this as well for the put specification.
http://code.google.com/appengine/docs/python/tools/webapp/requesthandlerclass.html#RequestHandler_put
The HTML specification doesn't allow a form to use the DELETE method, and you probably can't get a browser to send an HTTP DELETE request with a form. The delete() method of a RequestHandler subclass would generally be used for a RESTful web application with a client that knows how to send DELETE requests, rather than using ordinary HTML forms. (For a browser-based client, you can send DELETE requests in javascript using XMLHttpRequest.)
You can implement this simulation yourself of course, In pseudo code (I'm not familiar with GAE specifics):
def post(self):
if request.get('_method', '') == 'delete':
return self.post()
If you want to truely test PUT and DELETE you will have to find a way to actually use these methods in stead of simulating them. You can use curl for this, for example, i.e.
$ curl -X DELETE url
$ curl -T file url # for PUT
See the curl documentation / manpage for more information.
First, you need to create a new RequestHandler subclass :
from google.appengine.ext import webapp
class RESTfulHandler(webapp.RequestHandler):
def post(self, *args):
method = self.request.get('_method')
if method == "put":
self.put(*args)
elif method == "delete":
self.delete(*args)
else:
self.error(405) # Method not allowed
Then your handler will inherit from it :
class MyHandler(RESTfulHandler):
def get(self):
...
def delete(self):
...
def put(self):
...
def post(self):
...
Here is another example using the X-HTTP-Method-Override header used by most JavaScript libraries : http://github.com/sork/webapp-handlers/blob/master/restful.py
精彩评论