Multiple functions on class-based views flask
<p>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.</p>

<p>A pseudo-code like this:</p>

<pre><code>On POST associate /path to MyControllerClass@doPostMethod
On GET associate /path to MyControllerClass@someGetMethod
On GET associate /path/extra to MyControllerClass@someOtherGetMethod
...
</code></pre>

<p>On Flask I would have them as separated functions. Something like:</p>

<pre><code>def doPostFunction()...
def someGetFunction()...
def someOtherGetFunction()...
</code></pre>

<p>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 <em>dispatch_request</em> class-based view's method.</p>

<pre><code>class DoPostClass(View):
    dispatch_request()
        ...

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

class DoSomeOtherGetClass(View):
    dispatch_request()
        ...
</code></pre>

<p>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.</p>

<p>Thanks in advance.</p>

<p>Based on my laravel/flask project experience, the classy code of controller/view are same. You can try <a href="https://github.com/apiguy/flask-classy" rel="nofollow">flask-classy</a> extension</p>

<p>Below is an example based on <code>flask-classy</code>.</p>

<p><strong>Directory</strong></p>

<pre><code>.
âââ index.py
âââ views
    âââ __init__.py
    âââ myView.py
</code></pre>

<p><strong>myView.py</strong></p>

<pre><code>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)
</code></pre>

<p><strong>index.py</strong></p>

<pre><code>from flask import Flask
from views.myView import myView

app = Flask(__name__)
myView.register(app)
</code></pre>

<p><strong>Run</strong></p>

<pre><code>$ export FLASK_APP=index.py
$ flask run
# Index: http://127.0.0.1:5000/my
# Get: http://127.0.0.1:5000/my/&lt;id&gt;
</code></pre>

python flask