Search code examples
pythonflaskblueprint

How to add views to a blueprint in separate files


I have a huge application that was getting hard to update its views. To 'fix' this, I had separate the views into a few files, using blueprints. The problem is that the blueprints are also getting very big, because the long documentation that each view has and the different verifications that each view requires.

I had tried to do an import like this:

Import

Where I have a main file that contains the Flask application (which imports the blueprint), a file that contains the blueprint and a file the imports the blueprint and configure the views in it. The problem is that with this approach the views are not rendered, because flow reasons.

The main file, in the root of a folder:

from flask import Flask

from source import test

application = Flask(__name__)

application.register_blueprint(test)

application.run()

The blueprint file, inside a subfolder in the root folder:

from flask import Blueprint

test = Blueprint('test', __name__)

The view file, inside the same subfolder as the blueprint file:

from .test import test

@test.route('/home', methods=['GET', 'POST'])
def home():
    return 'home'

I had also tried to add the blueprint decorator to a declared function, this way the views are add to the blueprint in the blueprint file, but I don't think this is a good approach or a scalable approach - and it didn't work ^ - ^.

I expect to create a blueprint in a file, import the blueprint in other files and add views to the blueprint and then import the blueprint and add it to the Flask application.


Solution

  • In root folder change main file:

    from flask import Flask
    
    from source.listener import test
    
    application = Flask(__name__)
    
    application.register_blueprint(test)
    
    application.run()
    

    The blueprint file, inside a subfolder in the root folder:

    listener.py

    from flask import Blueprint
    
    from source.view import home
    
    
    test = Blueprint('test', __name__)
    
    test.add_url_rule('/home', view_func=home,methods=['GET', 'POST'])
    

    The view file, inside the same subfolder as the blueprint file:

    from flask import request
    
    def home():
        if request.method == 'POST':
            user = request.form['name']
            return "Welcome "+user
        else:
            return 'home'
    

    Get Request O/P:

     Home
    

    Post Request O/P:

    Welcome username