上一节 ,讲述了最基本的 Flask 结构,以及路由、静态页面和 Bootstrap。
这一节,我们添加用户登录界面。
Add a route to handle requests to the login URL
app.py
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != 'admin'\
or request.form['password'] != 'admin':
error = 'Invalid Credentials. Please try again.'
else:
return redirect(url_for('home'))
return render_template('login.html', error=error)
同时,确保添加 import
from flask import Flask, render_template, request, url_for, redirect
Add a template for the login page
templates/login.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin="anonymous">
<title>Flask Intro - login page</title>
</head>
<body>
<div class="container">
<h1>Please login</h1>
<br>
<form class="" method="post">
<input type="text" placeholder="Username" name="username" value="{{ request.form.username }}">
<input type="password" placeholder="Password" name="password" value="{{ request.form.password }}">
<input type="submit" value="login" class="btn btn-default">
</form>
<br>
{% if error %}
<p class="error"><strong>Error:</strong> {{ error }}</p>
{% endif %}
</div>
</body>
</html>
网友评论