Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

same url_prefix for two flask blueprints

I want to implement simple site layout:

/ must render home.html

/one, /two, /three must render one.html, two.html, three.html correspondingly

So far I came up with following code:

main_page = Blueprint('main', __name__)
category_page = Blueprint('category', __name__)


@main_page.route("/")
def home():
    return render_template('home.html')


@category_page.route('/<category>')
def show(category):
    return render_template('{}.html'.format(category))

app = Flask(__name__)
app.register_blueprint(main_page, url_prefix='/')
app.register_blueprint(category_page, url_prefix='/categories')

This way I am able to route categories to /categories/<category>. How can I route them to just /<category> instead, while keeping home.html linked to /? Appreciate your help

I tried two approaches:

  1. Setting url_prefix='/' for both blueprints => second one does not work.

  2. Instead of main_page blueprint use just app.route('/') to render home.html. This one also does not work when mixing with category_page blueprint

like image 867
MaxPY Avatar asked Oct 22 '17 05:10

MaxPY


Video Answer


1 Answers

You can move the variable to the url_prefix parameter inside the registering statement :

@main_page.route("/")
def home():
    return render_template('home.html')
app.register_blueprint(main_page, url_prefix='/')

@category_page.route('/')
def show(category):
    return render_template('{}.html'.format(category))        
app.register_blueprint(category_page, url_prefix='/<category>')

(it depends on the complexity of the whole pattern, but it may be better to keep the registering statements with the variables close to each function to handle many views.)

like image 128
PRMoureu Avatar answered Sep 28 '22 10:09

PRMoureu