You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I've tested the example of the Todo API that you provided. It's structured using classes to define the API resources. However, I'm wondering if it's possible to write the code in a different way by grouping all CRUD operations into a single controller class called TodoController.
Here's the initial example I retrieved from Flask-RESTx documentation:
fromflaskimportFlaskfromflask_restximportApi, Resource, fieldsfromwerkzeug.middleware.proxy_fiximportProxyFixapp=Flask(__name__)
app.wsgi_app=ProxyFix(app.wsgi_app)
api=Api(
app,
version="1.0",
title="TodoMVC API",
description="A simple TodoMVC API",
)
ns=api.namespace("todos", description="TODO operations")
todo=api.model(
"Todo",
{
"id": fields.Integer(readonly=True, description="The task unique identifier"),
"task": fields.String(required=True, description="The task details"),
},
)
classTodoDAO:
def__init__(self):
self.counter=0self.todos= []
defget(self, id):
fortodoinself.todos:
iftodo["id"] ==id:
returntodoapi.abort(404, f"Todo {id} doesn't exist")
defcreate(self, data):
todo=datatodo["id"] =self.counter=self.counter+1self.todos.append(todo)
returntododefupdate(self, id, data):
todo=self.get(id)
todo.update(data)
returntododefdelete(self, id):
todo=self.get(id)
self.todos.remove(todo)
DAO=TodoDAO()
DAO.create({"task": "Build an API"})
DAO.create({"task": "?????"})
DAO.create({"task": "profit!"})
@ns.route("/")classTodoList(Resource):
"""Shows a list of all todos, and lets you POST to add new tasks"""@ns.doc("list_todos")@ns.marshal_list_with(todo)defget(self):
"""List all tasks"""returnDAO.todos@ns.doc("create_todo")@ns.expect(todo)@ns.marshal_with(todo, code=201)defpost(self):
"""Create a new task"""returnDAO.create(api.payload), 201@ns.route("/<int:id>")@ns.response(404, "Todo not found")@ns.param("id", "The task identifier")classTodo(Resource):
"""Show a single todo item and lets you delete them"""@ns.doc("get_todo")@ns.marshal_with(todo)defget(self, id):
"""Fetch a given resource"""returnDAO.get(id)
@ns.doc("delete_todo")@ns.response(204, "Todo deleted")defdelete(self, id):
"""Delete a task given its identifier"""DAO.delete(id)
return"", 204@ns.expect(todo)@ns.marshal_with(todo)defput(self, id):
"""Update a task given its identifier"""returnDAO.update(id, api.payload)
if__name__=="__main__":
app.run(debug=True)
And here's the reorganized version with the TodoController class:
fromflaskimportFlaskfromflask_restximportApi, Resource, fieldsfromwerkzeug.middleware.proxy_fiximportProxyFixapp=Flask(__name__)
app.wsgi_app=ProxyFix(app.wsgi_app)
api=Api(
app,
version="1.0",
title="TodoMVC API",
description="A simple TodoMVC API",
)
ns=api.namespace("todos", description="TODO operations")
todo=api.model(
"Todo",
{
"id": fields.Integer(readonly=True, description="The task unique identifier"),
"task": fields.String(required=True, description="The task details"),
},
)
classTodoDAO:
def__init__(self):
self.counter=0self.todos= []
defget(self, id):
fortodoinself.todos:
iftodo["id"] ==id:
returntodoapi.abort(404, f"Todo {id} doesn't exist")
defcreate(self, data):
todo=datatodo["id"] =self.counter=self.counter+1self.todos.append(todo)
returntododefupdate(self, id, data):
todo=self.get(id)
todo.update(data)
returntododefdelete(self, id):
todo=self.get(id)
self.todos.remove(todo)
DAO=TodoDAO()
DAO.create({"task": "Build an API"})
DAO.create({"task": "?????"})
DAO.create({"task": "profit!"})
@ns.route("/")classTodoController(Resource):
@ns.doc("list_todos")@ns.marshal_list_with(todo)@ns.get('')defgetTodos(self):
"""List all tasks"""returnDAO.todos@ns.doc("create_todo")@ns.expect(todo)@ns.marshal_with(todo, code=201)@ns.post('')defcreateTodo(self):
"""Create a new task"""returnDAO.create(api.payload), 201@ns.doc("get_todo")@ns.marshal_with(todo)@ns.get('/<int:id>')defgetTodo(self, id):
"""Fetch a given resource"""returnDAO.get(id)
@ns.doc("delete_todo")@ns.response(204, "Todo deleted")@ns.delete('/<int:id>')defdeleteTodo(self, id):
"""Delete a task given its identifier"""DAO.delete(id)
return"", 204@ns.doc("update_todo")@ns.expect(todo)@ns.marshal_with(todo)@ns.put('/<int:id>')defupdateTodo(self, id):
"""Update a task given its identifier"""returnDAO.update(id, api.payload)
if__name__=="__main__":
app.run(debug=True)
Is it possible to adopt this structure to manage CRUD operations in a more concise and organized manner? Additionally, will Flask-RESTx support this type of structure in the future?
Thank you.
The text was updated successfully, but these errors were encountered:
I don't think this is currently possible. If you have a look at the code for the flask-restx resource class, it matches method names against the incoming HTTP request.method.
You could probably write your own custom Resource to structure the code in this way, but it's unlikely flask-restx will make this possible going forwards.
Ask a question
Hello,
I've tested the example of the Todo API that you provided. It's structured using classes to define the API resources. However, I'm wondering if it's possible to write the code in a different way by grouping all CRUD operations into a single controller class called TodoController.
Here's the initial example I retrieved from Flask-RESTx documentation:
And here's the reorganized version with the TodoController class:
Is it possible to adopt this structure to manage CRUD operations in a more concise and organized manner? Additionally, will Flask-RESTx support this type of structure in the future?
Thank you.
The text was updated successfully, but these errors were encountered: