使用基于 aiohttp class 的视图而不创建冗余端点
Using aiohttp class based views without creating redundant endpoints
我目前正在使用 aiohttp
实现 API。我正在使用基于 class 的视图,并且我有几个端点有和没有可变路径。当我尝试将可变路径与基于 class 的视图组合时,我最终创建了冗余端点。下面是一些描述我的问题的示例代码。
假设我想要以下端点和方法:
GET api/users
DELETE api/users/{id}
我用下面的代码做他:
from aiohttp import web
class UserView(web.View):
async def get(self):
return web.json_response({"result": []})
async def delete(self):
user_id = self.request.match_info.get("id", None)
return web.json_response({"result": f"User {user_id} was deleted"})
if __name__ == "__main__":
app = web.Application()
app.router.add_view("/users", UserView)
app.router.add_view("/users/{id}", UserView)
web.run_app(app)
我的代码创建了以下端点和方法组合。
GET api/users
GET api/users{id}
DELETE api/users
DELETE api/users/{id}
如您所见,我不需要全部。我有什么办法我仍然可以使用基于 class 的视图和可变路径而不会以冗余的 endpoint/method 组合结束?
显然,您可以通过将视图传递给路由器的 get
、post
... 方法来做到这一点!
from aiohttp import web
class UserView(web.View):
async def get(self):
return web.json_response({"result": []})
async def delete(self):
user_id = self.request.match_info.get("id", None)
return web.json_response({"result": f"User {user_id} was deleted"})
if __name__ == "__main__":
app = web.Application()
app.router.get("/users", UserView)
app.router.delete("/users/{id}", UserView)
web.run_app(app)
我目前正在使用 aiohttp
实现 API。我正在使用基于 class 的视图,并且我有几个端点有和没有可变路径。当我尝试将可变路径与基于 class 的视图组合时,我最终创建了冗余端点。下面是一些描述我的问题的示例代码。
假设我想要以下端点和方法:
GET api/users
DELETE api/users/{id}
我用下面的代码做他:
from aiohttp import web
class UserView(web.View):
async def get(self):
return web.json_response({"result": []})
async def delete(self):
user_id = self.request.match_info.get("id", None)
return web.json_response({"result": f"User {user_id} was deleted"})
if __name__ == "__main__":
app = web.Application()
app.router.add_view("/users", UserView)
app.router.add_view("/users/{id}", UserView)
web.run_app(app)
我的代码创建了以下端点和方法组合。
GET api/users
GET api/users{id}
DELETE api/users
DELETE api/users/{id}
如您所见,我不需要全部。我有什么办法我仍然可以使用基于 class 的视图和可变路径而不会以冗余的 endpoint/method 组合结束?
显然,您可以通过将视图传递给路由器的 get
、post
... 方法来做到这一点!
from aiohttp import web
class UserView(web.View):
async def get(self):
return web.json_response({"result": []})
async def delete(self):
user_id = self.request.match_info.get("id", None)
return web.json_response({"result": f"User {user_id} was deleted"})
if __name__ == "__main__":
app = web.Application()
app.router.get("/users", UserView)
app.router.delete("/users/{id}", UserView)
web.run_app(app)