Registering paths via Blueprint

Blueprint – makes it easy to organize paths in Flask.

This material is from a series of articles on website development in python: from local development to deployment on a remote server.

A simplified view of the code for running a Flask site:

Standard Flask

from flask import Flask
app = Flask(__name__)
app.configfrom_object(‘config.DevConfig’)

# Website routes
@app.route(‘/’)
def home():
return “Home”

# Admin pages
@app.route(‘/ portfolio’)
def portfolio_home():
return “portfolio Home”

if __name__ == “__main__”:
app.run()

Hence, we are only interested in routes… We can move these routes into a separate file. This is a normal practice even for a small project. However, what if there are too many routes?

For these purposes, distribution of routes through Blueprint

Routes via Blueprint

In file app / __ init__.py include several files routes.py:

# Registering Blueprint Paths
from app.routes import main_bp
app.register_blueprint(main_bp, url_prefix=“/”)

from app.adminroutes import admin_bp
app.register_blueprint(admin_bp, url_prefix=“/ admin”)

As you can see above, we have two files routes.py in two directories. For the main page, this is the file app / routes.py… For the admin page, this is the file app / admin / routes.py

app / routes.py

File contents:

main_bp = Blueprint(‘main_blueprint’, __name__)

# Include main page
# Connecting the main page
@main_bp.route(‘/’)
def portfolio_home_route():
return ‘The site is working.’
# return flask.redirect (“/ admin /”)
# return render_template (‘/ admin / index.html’)

app / portfolio / routes.py

File contents:

portfolio_bp = Blueprint(‘portfolio’, __name__)

# Get a list of all names of ever bought shares
@portfolio_bp.route(‘/ get-user /’, methods=[‘GET’])
@login_required
def get_all_user_shares_route():
query = db.sessionquery(Portfolio.name)filter_by(user_id=flask_login.current_userid)
shares = [x.name for x in query.all()]
return json.dumps(shares)

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *