python写一个web登录页面
时间: 2023-10-16 08:06:32 浏览: 35
好的,下面是一个简单的 Python Web 登录页面的示例,使用 Flask 框架实现。前提是你已经安装了 Flask 和相关依赖。
```python
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
# 简单的用户列表,用于演示登录功能
users = [
{"username": "admin", "password": "admin"},
{"username": "guest", "password": "guest"},
]
# 首页
@app.route('/')
def index():
return render_template('index.html')
# 登录页面
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
for user in users:
if user['username'] == username and user['password'] == password:
# 登录成功,跳转到欢迎页面
return redirect(url_for('welcome', username=username))
# 登录失败,重新显示登录页面
return render_template('login.html', error=True)
else:
return render_template('login.html')
# 欢迎页面
@app.route('/welcome/<username>')
def welcome(username):
return render_template('welcome.html', username=username)
if __name__ == '__main__':
app.run(debug=True)
```
上面的代码中,`index()` 函数渲染了一个简单的首页模板(`index.html`),包含一个链接到登录页面的按钮。`login()` 函数处理登录请求,如果用户名和密码匹配成功,则使用 Flask 的 `redirect()` 函数跳转到欢迎页面(`welcome()` 函数),否则重新渲染登录页面模板并显示一个错误消息。`welcome()` 函数渲染一个欢迎页面模板(`welcome.html`),显示登录成功的消息和用户名。
这是一个简单的示例,你可以根据自己的需求进行修改和扩展。同时,为了保证安全性,建议在实际生产环境中使用更加完善的用户认证方案。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)