3

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.

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Amazing!, exactly what I wanted. Thank you very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.