anvd
anvd

Reputation: 4047

Multiple subdomains allowed in the same blueprint

I need to have two sub domains allowed in this blueprint. In this case, pt and br. How can i do that? As far as i know, i can only have a sub-domain parameter. I want to use this function for both languages [pt and br].

mod = Blueprint('landing', __name__, url_prefix='/', subdomain='pt')

@mod.route('/', methods=['GET'])
def index():
    pass

I want to avoid dynamic sub-domains because I don't want to change all my url_for().

Upvotes: 3

Views: 1155

Answers (1)

AArias
AArias

Reputation: 2578

Don't define the blueprint's prefix and subdomain where you are doing it currently, define it like so:

mod = Blueprint('landing', __name__)

Then, simply register the blueprint two times, one for each subdomain:

app.register_blueprint(mod, subdomain='pt', url_prefix='/')
app.register_blueprint(mod, subdomain='br', url_prefix='/')

EDIT:

The problem with the given solution, as stated by OP, is that the first registered blueprint will take priority when using url_for in templates.

A quick workaround could be doing something like this when registering:

app.register_blueprint(mod, subdomain='br')
mod.name = 'landing_pt'    
app.register_blueprint(mod, subdomain='pt')

Note that the order this is done with is important (first register one, then change the name, then register the other one).

Then, for url_for to work as expected with both subdomains, it is important to use relative redirects like url_for('.index') instead of url_for('landing.index').

By changing the name of the blueprint for the second registration we trick Flask into thinking this is a different blueprint.

Suggestions welcome to better this kind of dirty workaround.

Upvotes: 6

Related Questions