Search code examples
pythonpython-2.7flaskpython-decoratorsdigest-authentication

Call decorators directly Flask, python


I am trying to create a simple Rest API.

Even if it is simple, I don't want to mix everything in a single file.

Therefore I have defined separate classes

Here is some of my files

app = Flask(__name__)

if __name__ == '__main__':
    api = PostApi(app)
    api.setup()
    api.set_routes()
    app.run(debug=True)

Post API class

class PostApi(object): BASE_API_ROUTE = '/post'

def __init__(self, app):
    super(PostApi, self).__init__()
    self.app = app

def setup(self):
    self.api = Api(self.app)
    self.app.config['SECRET_KEY'] = SECRET['digest_key']

def set_routes(self):
    self.api.add_resource(PostCategories, self.BASE_API_ROUTE + "/categories")
    self.api.add_resource(PostCatalog, self.BASE_API_ROUTE + "/catalog")
    self.api.add_resource(PostTags, self.BASE_API_ROUTE + "/tags")

And for example one of my endpoint classes

class PostTags(Resource):
    def __init__(self):
        super(PostTags, self).__init__()

    def get(self):
        return {'hello': 'world'}

It works, but I need to add authentication for my routes.

As you can see I am not using route decorators like app.route instead I am using the library flask_restful.

I need to protect my routes with the Digest Auth in this case. However, I am not sure how to do this, because I am not using decorators

I am a newbie developer. Could you suggest how to keep my endpoints separated and apply some protection to my routes.


Solution

  • You can use before_request. This will be called before every request on every route.

    something like this:

    @app.before_request
    def before_request():
        //add your logic here
    

    there's also before_first_request.

    visit Flask Documentation for more info.