我在谷歌应用程序引擎+ Python + webapp2上构建。构建现代web应用程序的一部分需要restful API。我知道我可以用Flask做到这一点,但是我想探索在webapp2上构建REST API的可能性。
在webapp2上,请求的处理方式如下:
app = webapp2.WSGIApplication([
('/post/new', CreatePost),
('/post/([a-z0-9]+)', ViewPost),
('/post/([a-z0-9]+)/edit', EditPost),
('/post/([a-z0-9]+)/delete', DeletePost)
])注意:([a-z0-9]+)是一个表示post_id的正则表达式
上面的请求处理程序不遵循RESTful模式,因为请求methods是在路径(/delete、/edit、/new)中指定的,而不是在请求头部中指定的。
解决方案是创建一个接收所有请求类型的处理程序类吗?例如:
class PostHandler(webapp2.RequestHandler):
def get(self):
# handle GET requests
def post(self):
# handle POST requests
def put(self):
# handle PUT requests
def delete(self):
# handle DELETE requests
app = webapp2.WSGIApplication([
('/post/?', PostHandler)
])在这种情况下,所有/post路径都由PostHandler处理。在此模式中不再使用post_id,因为它将在请求正文中提交。
这是用webapp2构建REST API的正确方法吗?
发布于 2019-09-25 01:56:45
你走在正确的道路上,但你应该继续处理url中的post_id,并像这样做:
class PostHandler(webapp2.RequestHandler):
def get(self, post_id=None):
if post_id:
# handle Fetching a single post object
else:
# handle Queries
def post(self, post_id=None):
if post_id:
self.abort(405)
# handle creating a single post object
def put(self, post_id=None):
if post_id:
# handle updating a single post object
else:
self.abort(405)
def delete(self, post_id=None):
if post_id:
# handle deleting a single post object
else:
self.abort(405)
app = webapp2.WSGIApplication([
('/post/<post_id>/', PostHandler),
('/post/', PostHandler),
])此外,像voscausa建议的那样将HTTP动词放在请求有效负载中并不符合RESTful应用编程接口设计。
发布于 2019-09-26 12:43:05
应该扩展webapp2.RequestHandler并将其用作RESTfulHandler的新基类,然后根据您的特定用途将RESTfulHandler扩展为RESTfulPostHandler。这样,我们还可以处理新的方式或工作,例如头部中的jwt (JSON web token)、授权和您希望在头部中处理的其他属性。
顺便说一句,"post“可能不是你的项目/对象的最佳名称,因为它很容易与http动词"post”混淆。如果我是您,我会将其重命名为"item“或类似名称,并使用扩展webapp2请求处理程序的RESTfulItemHandler。您希望在处理程序之间共享许多东西,这样在基类中共享功能就很方便了。
https://stackoverflow.com/questions/58068747
复制相似问题