Wallace Figueiredo
Wallace Figueiredo

Reputation: 27

Question about Dynamic Routing with Flask

I'm trying to create a logged area in my Flaks app where each user will have its own routes to access their information.

/user/<userid>/dashboard 
/user/<userid>/profile
/user/<userid>/operations 
/user/<userid>/analytics

What is the best way to handle that? In the example below, I'm passing the userId variable after the login inside the url_for. Once the redirect will come from the html template don't know how to pass the userId to the other routes.

I was reading something about having multiple routes with a single method but couldn't understand if it fits in what I need. Sry for the noob question and thanks in advance.

@app.route('/logon', methods=['POST'])
def logon():
    username = request.form['username']
    passwd = request.form['password']
    user = login_verified(username, passwd)
    session['token'] = user['idToken']
    return redirect(url_for('dashboard', usrId=user['userId']))

@app.route('/user/<usrId>/dashboard', methods=['GET'])
def dashboard(usrId):
    if 'token' in session:
        print('User ID = %s' % usrId)
        return render_template('dashboard.html')
    else:
        return redirect(url_for('login'))

Upvotes: 0

Views: 79

Answers (1)

Wallace Figueiredo
Wallace Figueiredo

Reputation: 27

Guys just found a way to do what I was looking for (don't know if this is the best one but works). Below the solution I found:

@app.route('/logon', methods=['POST'])
def logon():
    username = request.form['username']
    passwd = request.form['password']
    user = login_verified(username, passwd)
    session['token'] = user['idToken']
    return redirect(url_for('dashboard', usrId=user['userId']))


@app.route('/user/<usrId>/dashboard', methods=['GET'])
def dashboard(usrId):
    if 'token' in session:
        print('User ID = %s' % usrId)
        return render_template('dashboard.html', user=usrId)
    else:
        return redirect(url_for('login'))


@app.route('/user/<usrId>/operations', methods=['GET', 'POST'])
def operations(usrId):
    if 'token' in session:
        return render_template('operations.html', user=usrId)
    else:
        return redirect(url_for('login'))

and the template...

<body>
    <h1>Dashboard</h1>
    <div>
      <a href="{{ url_for('operations', usrId=user) }}">Operações</a>
      <a href="">Perfil</a>
    </div>
    <br />
    <input type="button" value="Logout" onclick="location.href='/logout'" />
  </body>

Upvotes: 2

Related Questions