-1

Is there a prefered way of setting up Flask so that it routes by username (mysite.com/<username>) at the top level but still works well (and fast) for all other routes and static files?

The way I imagine it now is something like:

@app.route('/<username>', methods=['GET'])
def username_route(username):

    if username_is_valid(username):  # DB checks, not too fast
        display_user_page(username)
    
    render_template('user_not_found.html')

But would that have any unwanted effects on other routes or static assets, favicons, or something that I'm forgetting?

fersarr
  • 3,399
  • 3
  • 28
  • 35

2 Answers2

0

Put your username_route at the end. Flask checks for each route from top to bottom. So, when you put faqs_route at the top which points to mysite.com/faqs, flask will consider that first.

Now, if you want to go to mysite.com/<username>, it will check all the top functions and since it can't find the corresponding route, it will go to the username_route at the end which will be the right route for mysite.com/<username>

Muhammed Jaseem
  • 782
  • 6
  • 18
0

You can send data with post request on frontend for clicking profile cases.

<button onclick="urlfor('username', {'user_id': id})"/>

Top level solution is possible with app.config.

app.config['RESERVED_ROUTES'] = [
    "faqs",
    "settings",
    "login",
    ...
]

Now we decide on request are user or reserved route. Because when we want to use blueprint in Flask it copy the config and give them an instance. So it is reachable for every request even you want to scale your app with blueprints.

@app.before_request
def decide_user_or_not():
    if request.path in app.config['RESERVED_ROUTES']:
        register_blueprint(route_blueprint)
    else:
        register_blueprint(user_blueprint)
Baris Senyerli
  • 642
  • 7
  • 13
  • Didnt know about blueprints! nice. I guess you could automatically get all the routes via https://stackoverflow.com/questions/13317536/get-list-of-all-routes-defined-in-the-flask-app and add favicon.png as well since some browsers seem to request it – fersarr Sep 02 '21 at 21:45
  • 1
    also, browsers ask for /favicon.ico, so it's useful to add it to an exceptions list – fersarr Sep 08 '21 at 20:22