Sergio Guillen Mantilla Sergio Guillen Mantilla - 23 days ago 10
Python Question

Multiple functions on class-based views flask

maybe I'm misunderstanding class-based views on Flask. I come from a PHP/Laravel background. On Laravel I can define a controller class where I can response different json data, views (templates on Flask), etc. So the only thing I do is define a route and associate that route to a specific method on a controller class.

A pseudo-code like this:

On POST associate /path to MyControllerClass@doPostMethod
On GET associate /path to MyControllerClass@someGetMethod
On GET associate /path/extra to MyControllerClass@someOtherGetMethod

On Flask I would have them as separated functions. Something like:

def doPostFunction()...
def someGetFunction()...
def someOtherGetFunction()...

So googling a bit, there are class-based views but as I saw it, insted of defining a function I define a class and put the content of the old view function inside dispatch_request class-based view's method.

class DoPostClass(View):

class DoGetClass(View):

class DoSomeOtherGetClass(View):

Is there a way to have these functions inside a single class? am I misunderstading Flask's class-based views? I know there's a MethodView class that has get, post, put, delete methods but as I'm not createing a RESTful API neither I use nice-RESTful urls, MethodView class seems not to be useful for my case.

Thanks in advance.


Based on my laravel/flask project experience, the classy code of controller/view are same. You can try flask-classy extension

Below is an example based on flask-classy.


└── views

from flask_classy import FlaskView

class myView(FlaskView):
    def index(self):
        return "this is index"

    def get(self, id):
        return "this is page " + str(id)

from flask import Flask
from views.myView import myView

app = Flask(__name__)


$ export
$ flask run
# Index:
# Get:<id>