Search code examples
pythonflask-restful

AttributeError: class Home has no attribute 'as_view'


I'm using Flask Restful and I want to render an HTML file on the root endpoint:

from flask_restful import Resource, Api
app = Flask( __name__, static_url_path = '', static_folder = "docs" )
api = Api(app, catch_all_404s=True)
class Home():
    def get(self):
        return app.send_static_file( 'index.html' )
api.add_resource(Home, '/')

When I run this code, I get this error:

    api.add_resource(Home, '/')
  File "/home/vagrant/.local/lib/python2.7/site-packages/flask_restful/__init__.py", line 404, in add_resource
    self._register_view(self.app, resource, *urls, **kwargs)
  File "/home/vagrant/.local/lib/python2.7/site-packages/flask_restful/__init__.py", line 444, in _register_view
    resource_func = self.output(resource.as_view(endpoint, *resource_class_args,
AttributeError: class Home has no attribute 'as_view'

How to render a static file in Flask Restful ?


Solution

  • Have a look at Flask Restful Documentation; as an example you can find the following in the documentation:

    from flask import Flask, request
    from flask_restful import Resource, Api
    
    app = Flask(__name__)
    api = Api(app)
    
    todos = {}
    
    class TodoSimple(Resource):
        def get(self, todo_id):
            return {todo_id: todos[todo_id]}
    
        def put(self, todo_id):
            todos[todo_id] = request.form['data']
            return {todo_id: todos[todo_id]}
    
    api.add_resource(TodoSimple, '/<string:todo_id>')
    
    if __name__ == '__main__':
        app.run(debug=True)
    

    As you can see above, one thing you're missing surely is the inheritance from Resource.