用Python写一个登录页面
时间: 2024-03-06 20:22:26 浏览: 20
好的,这是一个简单的登录页面代码供你参考:
```python
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
@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 username or password. Please try again.'
else:
return redirect(url_for('home'))
return render_template('login.html', error=error)
@app.route('/home')
def home():
return 'Welcome to the home page!'
if __name__ == '__main__':
app.run()
```
这个程序使用 Flask 框架和 Jinja2 模板引擎构建了一个简单的登录页面。它使用两个路由:一个是登录页面,一个是首页。当用户提交登录表单时,程序会检查用户名和密码是否为“admin”,如果是,则重定向到首页,否则显示一条错误信息。
登录页面的 HTML 代码如下:
```html
<!doctype html>
<html>
<head>
<title>Login</title>
</head>
<body>
{% if error %}
<p style="color:red">{{ error }}</p>
{% endif %}
<form method="post">
<label for="username">Username:</label>
<input type="text" name="username" id="username"><br>
<label for="password">Password:</label>
<input type="password" name="password" id="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>
```
希望这对你有帮助!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)