I'm using Flask on Python and I'm displaying the username at the top of the site (and it's working) as follows:
@app.route("/")
@login_required
def index():
"""Queries the user's First Name to display in the title"""
names = db.execute("""
SELECT first_name
FROM users
WHERE id=:user_id
""",
user_id = session["user_id"]
)
return render_template("index.html", names = names)
<header class="mainHeader">
{% for name in names %}
<h1>{{ name["first_name"] }}' Bookshelf</h1>
{% else %}
<h1>Your Bookshelf</h1>
{% endfor %}
</header>
I don't know if it is necessary, but here is my database configuration:
Although it is working, I believe that it is not ideal to use for loop to display just one name. Does anyone have any suggestions?
Editing to include login routine:
@app.route("/login", methods=["GET", "POST"])
def login():
"""Log user in"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# Ensure email and password was submitted
result_checks = is_provided("email") or is_provided("password")
if result_checks is not None:
return result_checks
# Query database for email
rows = db.execute("SELECT * FROM users WHERE email = ?", request.form.get("email"))
# Ensure email exists and password is correct
if len(rows) != 1 or not check_password_hash(rows[0]["hash"], request.form.get("password")):
return "E-mail ou Senha inválidos"
# Remember which user has logged in
session["user_id"] = rows[0]["id"]
session["email"] = request.form.get("email")
# Redirect user to home page
return redirect("/")
# User reached route via GET (as by clicking a link or via redirect)
else:
return render_template("login.html")
