Search code examples
pythonflask-restfulflask-httpauth

Flask-restful app fails when authentication is enabled


I'm getting this error whenever I try and enable authentication using flask_httpauth for my flask_restful project:

AttributeError: 'function' object has no attribute 'as_view'

Here's a very basic example: apicontroller.py:

from flask_restful import Resource, Api
from flasktest import api, app
from flask_httpauth import HTTPTokenAuth

auth = HTTPTokenAuth()

@auth.login_required
class ApiController(Resource):
    def get(self):
        return True

api.add_resource(ApiController, '/api/apicontroller')

init.py:

from flask import render_template
from flask import Flask, request, render_template, session, flash, redirect, url_for, jsonify
from flask_restful import Resource, Api, reqparse, fields
from flask_httpauth import HTTPTokenAuth


app = Flask(__name__)

api = Api(app)

import flasktest.apicontroller

Whenever I decorate the controller class with @auth.login_required, it fails with the mentioned error. How can I fix this?


Solution

  • I believe that you cannot not apply decorators to class.

    To solve that:

    from flask_restful import Resource, Api
    from flasktest import api, app
    
    from flask_httpauth import HTTPTokenAuth
    
    auth = HTTPTokenAuth()
    
    class ApiController(Resource):
        decorators = [auth.login_required]
    
        def get(self):
            return True
    
    api.add_resource(ApiController, '/api/apicontroller')