Flask - Routes dynamic component
1. Route: Set url as 'user/<username>'
- When a route has a dynamic component, Flask will accept any text in that portion of the URL, and will invoke the view function with the actual text as an argument.
2. Function: Use first_or_404
filter_by(username=username)
this user name is given by URL ! (wow)- if user is not founded, raise 404 error
@app.route('/user/<username>') # dynamic component
@login_required
def user(username):
user = User.query.filter_by(username=username).first_or_404() # if user is not founded, raise 404 error page
# the username receive from routes
posts = [
{'author': user, 'body': 'Test post #1'},
{'author': user, 'body': 'Test post #2'}
]
return render_template('user.html', user=user, posts=posts)
####3. View - To access the profile page
- To access the
user/<username>
, when seturl_for
, need to give username argument. - so, get current_user’s username, and passing the value as an argument.
<div> Microblog:
<a href="">Home</a>
<a href="">Profile</a>
<a href="">Log Out</a>
</div>