Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save avanish/b498ac10b151fa1645ff8325898dcdf2 to your computer and use it in GitHub Desktop.
Save avanish/b498ac10b151fa1645ff8325898dcdf2 to your computer and use it in GitHub Desktop.
Example of how to split a Flask blueprint into multiple files, with routes in each file, and of how to register all those routes.
"""
Note: can't put in a subdirectory for this example (GitHub Gists
doesn't allow subdirectories). Recommended to move this file to
foo/bar.py.
"""
routes = []
def ping_bar():
return 'Ping bar'
routes.append(dict(
rule='/ping-bar/',
view_func=ping_bar))
def save_bar():
return 'Save bar'
routes.append(dict(
rule='/save-bar/',
view_func=save_bar,
options=dict(methods=['POST',])))
"""
Note: can't put in a subdirectory for this example (GitHub Gists
doesn't allow subdirectories). Recommended to move this file to
foo/baz.py.
"""
routes = []
def call_baz():
return 'Call baz'
routes.append(dict(
rule='/call-baz/',
view_func=call_baz))
def delete_baz():
return 'Delete baz'
routes.append(dict(
rule='/delete-baz/',
view_func=delete_baz,
options=dict(methods=['GET', 'POST'])))
from flask import Flask
app = Flask(__name__)
app.debug = True
@app.route('/')
def home():
return 'App home'
from foo import mod
app.register_blueprint(mod, url_prefix='/foo')
if __name__ == '__main__':
app.run()
"""
Note: can't put in a subdirectory for this example (GitHub Gists
doesn't allow subdirectories). Recommended to move this file to
foo/__init__.py, and to change the imports to
'from .bar' and 'from .baz'.
"""
from flask import Blueprint
mod = Blueprint('foo', __name__)
@mod.route('/')
def home():
return 'Foo home'
from bar import routes as bar_routes
from baz import routes as baz_routes
routes = (
bar_routes +
baz_routes)
for r in routes:
mod.add_url_rule(
r['rule'],
endpoint=r.get('endpoint', None),
view_func=r['view_func'],
**r.get('options', {}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment