Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask: using app as an attribute and accessing decorators

Tags:

python

flask

using the python flask module, i would like to have the

app = flask.Flask(__name__)

as a attribute of a class:

class Handler(object):
    def __init__(self):
        self.datastores = {}
        self.websocket_queue = gevent.queue.JoinableQueue()
        self.app = flask.Flask(__name__)

the problem is how to access decorators then?

    @self.app.route('/socket.io/<path:remaining>')
    def socketio(self, remaining):

That generates the error NameError: name 'self' is not defined Thanks

like image 345
Mermoz Avatar asked Apr 08 '13 14:04

Mermoz


2 Answers

You could try to use Flask-Classy as it provides an easy way to use classes with Python-Flask.

like image 199
eandersson Avatar answered Oct 21 '22 07:10

eandersson


It depends - if you are adding handlers inside of a method of the Handler class it should work without issue:

def add_routes(self):
    @self.app.route("/some/route")
    def some_route():
        return "At some route"

If you are attempting to add routes outside of Handler you will need to use a reference to your Handler instance:

handler = Handler()

@handler.app.route("/some/route")
def some_route():
    return "At some route"
like image 30
Sean Vieira Avatar answered Oct 21 '22 06:10

Sean Vieira