The below works in Flask-Classful (it's a maintained fork of the now-abandoned Flask-Classy), but I was wondering if there is a "native" version of the logic I have for the last two routes in Flask-Classful, without mixing Flask routes and Flask-Classful built-in special methods like get()
and post()
?
From the extensive documentation Flask-Classy has at https://pythonhosted.org/Flask-Classy/ I unfortunately couldn't spot an example for the last two routes in the below code, which would be eg. GET /news/123/comments/
and GET /news/123/comments/321
. There were some examples for cases that would be like GET /news/comments/123
, but not for when you have two variables you pick from the route URI (which will be used for DB queries).
from flask_classful import FlaskView, route
class NewsView(FlaskView):
def index(self):
return "This is GET /news\n"
def get(self, news_id):
return "This is GET /news/{}\n".format(news_id)
def post(self):
return "This is POST /news\n"
def put(self, news_id):
return "This is PUT /news/{}\n".format(news_id)
def patch(self, news_id):
return "This is PATCH /news/{}\n".format(news_id)
def delete(self, news_id):
return "This is DELETE /news/{}\n".format(news_id)
@route("/<int:news_id>/comments/<int:comment_id>", methods=["GET"])
def news_comment(self, news_id, comment_id):
return "This is GET /news/{}/comments/{}\n".format(news_id, comment_id)
@route("/<int:news_id>/comments/", methods=["GET"])
def news_comments(self, news_id):
return "This is GET /news/{}/comments/\n".format(news_id)
The routes are registered with:
def register_views(app):
api_path = "/api/1.0"
from apps.news.views import NewsView
NewsView.register(app, route_base="{}/news/".format(api_path))
It seems to work though. Maybe it's just splitting hairs, but I would think something like this would have built-in support in Flask-Classful?
Here's some test requests, where it works:
$ curl -X GET https://localhost:443/api/1.0/news/ --insecure -L
This is GET /news
$ curl -X GET https://localhost:443/api/1.0/news/123 --insecure -L
This is GET /news/123
$ curl -X POST https://localhost:443/api/1.0/news/ --insecure -L
This is POST /news
$ curl -X PUT https://localhost:443/api/1.0/news/123 --insecure -L
This is PUT /news/123
$ curl -X PATCH https://localhost:443/api/1.0/news/123 --insecure -L
This is PATCH /news/123
$ curl -X DELETE https://localhost:443/api/1.0/news/123 --insecure -L
This is DELETE /news/123
$ curl -X GET https://localhost:443/api/1.0/news/1/comments/ --insecure -L
This is GET /news/1/comments/
$ curl -X GET https://localhost:443/api/1.0/news/1/comments/2 --insecure -L
This is GET /news/1/comments/2
news_comment
without having to use a decorator? Is that your question? – Tarun Lalwani Sep 3 '17 at 19:07get()
for multiple subpaths (they all share the/api/1.0/news/
path) in the same view. – Juha Untinen Sep 3 '17 at 21:20