Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Flask Restful as a Blueprint in Large Application

I am trying to use Flask restful as a Blueprint in a pattern that works for other blueprints. I keep getting the following error message

I get the following error message

AttributeError: 'Blueprint' object has no attribute 'add_resource'

My project setup is as follows:

Folder structure

├── app
│   ├── __init__.py
│   ├── api
│   │   ├── __init__.py
│   │   └── routes.py
│   ├── main
│   │   ├── __init__.py
│   │   ├── forms.py
│   │   └── views.py
│   └── templates
│       ├── base.html
│       └── home.html
├── config.py
├── manage.py
└── requirements.txt

__init__.py

from flask import Flask
from flask_restful import Api
from flask_bootstrap import Bootstrap
from config import config
bootstrap = Bootstrap()
api = Api()

def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    bootstrap.init_app(app)
    api.init_app(app)

    from .main import main as main_blueprint
    from .api import api as api_blueprint
    app.register_blueprint(main_blueprint)
    app.register_blueprint(api_blueprint)
    return app

api/__init__.py

from flask import Blueprint

api = Blueprint('api', __name__)

from . import routes

api/routes.py

from flask_restful import Resource
from . import api

class TodoItem(Resource):
    def get(self, id):
        return {'task': 'Say "Hello, World!"'}

api.add_resource(TodoItem, '/todos/<int:id>')

What am I doing wrong??

like image 699
CraigH Avatar asked Mar 11 '23 16:03

CraigH


1 Answers

If you follow the instructions from https://flask-restful.readthedocs.io/en/0.3.5/intermediate-usage.html

The key points here are to create a Flask Blueprint instance & pass it to a new instance of flask-restfuls's Api class.

Lastly, make sure to register the flask-restful api blueprint within your create_app function: app.register_blueprint(api_bp)

from flask import Flask, Blueprint
from flask_restful import Api
from flask_bootstrap import Bootstrap
from config import config

bootstrap = Bootstrap()
api_bp = Blueprint('api', __name__)
api = Api(api_bp)

def create_app(config_name):
   app = Flask(__name__)
   app.config.from_object(config[config_name])
   config[config_name].init_app(app)

   bootstrap.init_app(app)

   from .users import main as users_blueprint
   from .blogs import main as blogs_blueprint

   # blueprints for blogs & users
   app.register_blueprint(users_blueprint)
   app.register_blueprint(blogs_blueprint)
   app.register_blueprint(api_bp)
   
   return app

Also note, you don't need to register api.init_app(app) anymore.

like image 146
Joe Gasewicz Avatar answered May 08 '23 12:05

Joe Gasewicz