Sergio Guillen Mantilla Sergio Guillen Mantilla - 1 month ago 17
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):
dispatch_request()
...

class DoGetClass(View):
dispatch_request()
...

class DoSomeOtherGetClass(View):
dispatch_request()
...


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.

Answer

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.

Directory

.
├── index.py
└── views
    ├── __init__.py
    └── myView.py

myView.py

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)

index.py

from flask import Flask
from views.myView import myView

app = Flask(__name__)
myView.register(app)

Run

$ export FLASK_APP=index.py
$ flask run
# Index: http://127.0.0.1:5000/my
# Get: http://127.0.0.1:5000/my/<id>
Comments