July 2019
Beginner to intermediate
302 pages
9h 38m
English
We simply have to modify our views for product handling to extend the MethodView class in views.py:
import jsonfrom flask.views import MethodView, abort
class ProductView(MethodView):
def get(self, id=None, page=1):
if not id:
products = Product.query.paginate(page, 10).items
res = {}
for product in products:
res[product.id] = {
'name': product.name,
'price': product.price,
'category': product.category.name
}
else:
product = Product.query.filter_by(id=id).first()
if not product:
abort(404)
res = json.dumps({
'name': product.name,
'price': product.price,
'category': product.category.name
})
return res
The preceding get() method searches for the product and sends back a JSON result.
Similarly, we can write the post(), put() ...