I'm not sure if Flask implements all of the routing stuff that Werkzeug does (Flask is based on Werkzeug), but in werkzeug you can use an any route, like so:

gallery = Blueprint(__name__, __name__, url_prefix='/<any("photos,paintings"):source>')

If you use @gallery.route on your views, you'll get an argument source, which you can use to determine your source directory.

@gallery.route('/show')
def show(source):
    # Show stuff based on source being "photos" or "paintings"

Not sure if that works in Flask, but worth a shot...

Answer from Menno on Stack Overflow
🌐
Flask
flask.palletsprojects.com › en › stable › blueprints
Modular Applications with Blueprints — Flask Documentation (3.1.x)
Additionally it will prefix the endpoint of the function with the name of the blueprint which was given to the Blueprint constructor (in this case also simple_page). The blueprint’s name does not modify the URL, only the endpoint. ... from flask import Flask from yourapplication.simple_page import simple_page app = Flask(__name__) app.register_blueprint(simple_page)
Discussions

python - Flask Blueprint Initialization - Initializing some global variables - Stack Overflow
From the flask main application object, in this case app, you can access the list of blueprints registered; app.blueprints, which is a python dictionary with the name of the blueprint that you passed in the constructor. More on stackoverflow.com
🌐 stackoverflow.com
Flask Blueprint issue : Forums : PythonAnywhere
Fixed it, not sure how but here's what I did: 1. Before I was specifying the url_prefix in Blueprint constructor, moved it to Blueprint registration, removed the name arg there as well. 2. Moved the app_views import line and blueprint registration above some other imports related to flask shell. More on pythonanywhere.com
🌐 pythonanywhere.com
python - How to pass arbitrary arguments to a flask blueprint? - Stack Overflow
What is stopping you from putting ... module.construct_blueprint(database)? 2015-02-21T01:52:53.263Z+00:00 ... Only my end-of-the-day tiredness. Thank you sir. 2015-02-21T01:56:48.08Z+00:00 ... Very elegant solution. Especially when using the integration of SQLAlchemy, BCrypt etc., this offers a very easy way to pass existing components down the chain. In addition one might basically also build a route-factory if such a need arises. In case people need to use the Flask app in this constructor function, ... More on stackoverflow.com
🌐 stackoverflow.com
Structuring a small Flask app -- wondering if Blueprints is the right approach, or overkill
There is nothing "overkill" about the blueprints. The computer does not care how you organise your code, we break the app into the smaller chunks for the convenience of developers and maintainers. Having a blueprint in your project does not necessarily mean that it should be a reusable component. Yes, you can have multiple route files without blueprints, but each route file would probably have its own templates, forms, maybe models, helpers etc. - and if you consider grouping these things into separate directories, this is basically the same thing as blueprints. More on reddit.com
🌐 r/flask
15
11
October 9, 2023
🌐
Exploreflask
exploreflask.com › en › latest › blueprints.html
Blueprints — Explore Flask 1.0 documentation
To create a blueprint object, we import the Blueprint() class and initialize it with the arguments name and import_name. Usually import_name will just be __name__, which is a special Python variable containing the name of the current module. We’re using a functional structure for this Facebook ...
🌐
Real Python
realpython.com › flask-blueprint
Use a Flask Blueprint to Architect Your Applications – Real Python
February 6, 2021 - In this tutorial, you'll learn how to use a Flask Blueprint to help you structure your application by grouping its functionality into reusable components. You'll learn what Blueprints are, how they work, and how you can use them to organize your code.
🌐
OverIQ
overiq.com › flask-101 › application-structure-and-blueprint-in-flask
Application Structure and Blueprint in Flask - Flask tutorial - OverIQ.com
Inside the main directory create __init__.py file with the following code: ... We are creating blueprint object using the Blueprint class. The Blueprint() constructor takes two arguments, the blueprint name and the name of the package where blueprint is located; for most applications passing ...
🌐
Miguel Grinberg
blog.miguelgrinberg.com › post › the-flask-mega-tutorial-part-xv-a-better-application-structure
The Flask Mega-Tutorial, Part XV: A Better Application Structure - miguelgrinberg.com
I should note that Flask blueprints can be configured to have a separate directory for templates or static files. I have decided to move the templates into a subdirectory of the application's template directory so that all templates are in a single hierarchy, but if you prefer to have the templates that belong to a blueprint inside the blueprint package, that is supported. For example, if you add a template_folder='templates' argument to the Blueprint() constructor, you can then store the blueprint's templates in app/errors/templates.
Top answer
1 of 2
3

so each blueprint needs to tell my base application how it want's to be named and what it's default route is.

When you create a blueprint you already pass its name in the first parameter:

simple_page = Blueprint('simple_page')

You can pass to the constructor the url_prefix value too

simple_page = Blueprint('simple_page', url_prefix='/pages')

I have a main application containing some sub applications implemented as blueprints. The main application should hold a navigation bar referencing to all sub applications (blueprints)

This is an example in one python module, you should split each blueprint in its own module.

from flask import Flask, Blueprint, render_template

# ADMIN
admin = Blueprint('admin', __name__, url_prefix='/admin')

@admin.route('/')
def admin_index():
    return 'Admin module'

@admin.route('/settings')
def settings():
    return 'Admin Settings'


# USER
user = Blueprint('user', __name__, url_prefix='/user')

@user.route('/')
def user_index():
    return 'User module'

@user.route('/profile')
def profile():
    return 'User Profile'


app = Flask(__name__)
app.register_blueprint(admin)
app.register_blueprint(user)

@app.route('/')
def index():
    return render_template('index.html', blueprints=app.blueprints)

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True, port=7000)

The Jinja2 template. Remember to place this file in the templates folder in you root project, which is where flask search the templates by default.

<ul>
  {% for bp_name, bp in blueprints.iteritems() %}
    <li><a href="{{ bp.url_prefix }}">{{ bp.name }}</a></li>
  {% endfor %}
</ul>

From the flask main application object, in this case app, you can access the list of blueprints registered; app.blueprints, which is a python dictionary with the name of the blueprint that you passed in the constructor. So you pass this object to you template and loops on it to render the name and URL in the menu.

Furthermore, what if I want to enable blueprint authors to pass more data in a standardized way (e.g. in which color to display the link to his piece, or whatever...)

As this is a blueprint specific data, I think a good solution is to extend the Blueprint class and implement a custom method to save extra data in a standardized way and then access then from the main application object.

custom.py

from flask import Blueprint

class MyBlueprint(Blueprint):

    bp_data = {}

    def set_data(data):
        # here you can make extra task like ensuring if 
        # a minum group of value were provided for instance
        bp_data = data

admin.py

from .custom import MyBlueprint

admin = MyBlueprint('admin', __name__, url_prefix='/admin')
admin.set_data({'color': '#a569bd', 'enabled': true})

# all the blueprint's routes
...

app.py

from admin import admin

app = Flask(__name__)
app.register_blueprint(admin)

@app.route('/')
def index():
    for a, b in app.blueprints:
        print b.bp_data['color']
        print b.bp_data['enabled']
    ...

Of course, my custom Blueprint class needs more work on it, like validating what type of data its being passed or throwing an error if there isn't a required value, like; title, require_auth, etc. From this point, it's you who must define what is the minimum required data that a blueprint must provide to your main application to work properly.

2 of 2
1

Here I present you a extensible app pattern that I usually use. It is proved that work fine.

Directory structure:

YourApp
|- plugins (will contain all the user's plugins)
     |- __init__.py (empty)
     |-plugin1
          |- __init__.py (empty)
          |- loader.py
|- app.py

app.py

from flask import Flask
import os

def plugin_loader(app):
  """ Function for discover new potencial plugins.
  After checking the validity (it means, check if it implements
  'register_as_plugin', load the user defined blueprint"""

  plugins = [x for x in os.listdir('./plugins')
             if os.path.isdir('./plugins/' + x)]
  for plugin in plugins:
    # TODO: Add checking for validation
    module = __import__('plugins.' + str(plugin) + '.loader', fromlist=['register_as_plugin'])

    app = module.register_as_plugin(app)

  return app

# Creates the flask app
app = Flask(__name__)
# Load the plugins as blueprints
app = plugin_loader(app)

print(app.url_map)


@app.route('/')
def root():
  return "Web root!"

app.run()

plugins/plugin1/loader.py

from flask import Blueprint


plugin1 = Blueprint('plugin1', __name__)

@plugin1.route('/version')
def version():
  return "Plugin 1"

def register_as_plugin(app):
  app.register_blueprint(plugin1, url_prefix='/plugin1')

  return app

So futures plugins should implement the register_as_plugin function, inside the loader.py file, inside their directory in plugins/.

For more information about directories discovery you can read https://docs.python.org/2/library/os.path.html. For more information about the dynamic import of modules you can read https://docs.python.org/2/library/functions.html#import.

Proved with Python 2.7.6, Flask 0.10.1 and Unix platform.

Find elsewhere
🌐
PythonAnywhere
pythonanywhere.com › forums › topic › 27979
Flask Blueprint issue : Forums : PythonAnywhere
from flask import Flask def create_app(): app = Flask(__name__) from .main import main as main_bp app.register_blueprint(main_bp) return app if __name__ == "__main__": create_app()
🌐
Beautiful Soup
tedboy.github.io › flask › generated › generated › flask.Blueprint.html
flask.Blueprint — Flask API
flask.Blueprint · View page source ... root_path=None)[source]¶ · Represents a blueprint. A blueprint is an object that records functions that will be called with the BlueprintSetupState later to register functions or other things on the main application....
🌐
Readthedocs
flask-cn.readthedocs.io › en › latest › blueprints
Modular Applications with Blueprints — Flask 0.7 documentation
Additionally it will prefix the endpoint of the function with the name of the blueprint which was given to the Blueprint constructor (in this case also simple_page). ... from flask import Flask from yourapplication.simple_page import simple_page app = Flask(__name__) app.register_blueprint(simple_page)
🌐
Readthedocs
test-flask.readthedocs.io › en › latest › blueprints.html
Modular Applications with Blueprints — Flask 0.11-dev documentation
Additionally it will prefix the endpoint of the function with the name of the blueprint which was given to the Blueprint constructor (in this case also simple_page). ... from flask import Flask from yourapplication.simple_page import simple_page app = Flask(__name__) app.register_blueprint(simple_page)
🌐
Hackers and Slackers
hackersandslackers.com › flask-blueprints
Organize Flask Apps with Blueprints
August 20, 2024 - We can organize our Flask apps via a built-in concept called Blueprints, which are essentially the Flask equivalent of Python modules. Blueprints are intended to encapsulate feature-sized sections of our application, such as checkout flows, ...
🌐
Flask
flask.palletsprojects.com › en › latest › blueprints
Modular Applications with Blueprints — Flask Documentation (3.2.x)
Additionally it will prefix the endpoint of the function with the name of the blueprint which was given to the Blueprint constructor (in this case also simple_page). The blueprint’s name does not modify the URL, only the endpoint. ... from flask import Flask from yourapplication.simple_page import simple_page app = Flask(__name__) app.register_blueprint(simple_page)
🌐
Runebook
runebook.dev › english › articles › flask
Understanding Blueprint.register(): Integrating Blueprints in Flask
Modularization Blueprints promote code organization and reusability by allowing you to structure your Flask application into smaller, more manageable units. Templates and Static Files You can configure Blueprints to have their own template and static file directories. Error Handling Blueprints can also have their own error handlers that are specific to the Blueprint's routes. URL Prefixes The url_prefix in the Blueprint constructor and the route() decorator work together to construct the final URLs.
🌐
Plain English
python.plainenglish.io › how-to-use-blueprints-in-flask-3d29b5858ec1
How to Use Blueprints in Flask - Ashutosh Krishna - Medium
September 5, 2022 - Now that you have created a blueprint for the admin-related functionality, you can use it while creating routes for the admins. from flask import Blueprint# Defining a blueprint admin_bp = Blueprint( 'admin_bp', __name__, template_folder='templates', static_folder='static' )@admin_bp.route('/admin') # Focus here def admin_home(): return "Hello Admin!"
🌐
Reddit
reddit.com › r/flask › structuring a small flask app -- wondering if blueprints is the right approach, or overkill
r/flask on Reddit: Structuring a small Flask app -- wondering if Blueprints is the right approach, or overkill
October 9, 2023 -

Hello all,

I'm new to Flask. I'm porting an app from PHP (Symfony) to python/flask, and wonder how to organize it.

The app has about 90 endpoints - some JSON/API, some user UI -- in various categories, such as "book" (add/edit/etc), "term" (ditto), "read" (various methods). In Symfony, each of these categories are handled by a separate controller, e.g. BookController.php.

With Flask, I understand I can create blueprints, but none of these are "subsystems", they're all related to the central idea of the app, and I'm not going to need them to be modular pick-up-and-drop-in pieces.

I'm inclined to make them all blueprints anyway, just because that seems to be easy to grok for any newcomers to the project, if people want to work on it. I'd be interested to know if there were any other good alternatives, such as simple python files (e.g. "routes/book_routes.py").

Thank you very much!

🌐
Readthedocs
flask-restful.readthedocs.io › en › latest › intermediate-usage.html
Intermediate Usage — Flask-RESTful 0.3.10 documentation
Here’s an example of how to link an Api up to a Blueprint. from flask import Flask, Blueprint from flask_restful import Api, Resource, url_for app = Flask(__name__) api_bp = Blueprint('api', __name__) api = Api(api_bp) class TodoItem(Resource): def get(self, id): return {'task': 'Say "Hello, World!"'} api.add_resource(TodoItem, '/todos/<int:id>') app.register_blueprint(api_bp)
🌐
Runebook
runebook.dev › english › articles › flask
Flask Blueprint Registration: Common Errors and Troubleshooting
The __name__ argument in the Blueprint constructor might be incorrect, leading to issues with the module where the Blueprint is defined.
🌐
DevDreamz
devdreamz.com › question › 438498-how-do-i-pass-constructor-arguments-to-a-flask-blueprint
How do I pass constructor arguments to a Flask Blueprint? - DevDreamz
I'm not sure if Flask implements all of the routing stuff that Werkzeug does (Flask is based on Werkzeug), but in werkzeug you can use an any route, like so: gallery = Blueprint(__name__, __name__, url_prefix='/<any("photos,paintings"):source>')