0

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?

Trondh
  • 3,221
  • 1
  • 25
  • 34

1 Answers1

6

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')
vishes_shell
  • 22,409
  • 6
  • 71
  • 81