python flask实现web 实现用户登录注册界面,并实现数据在数据库传入传出
时间: 2024-03-05 11:51:35 浏览: 150
下面是一个使用 Flask 实现用户登录注册界面,并将用户数据存储在 SQLite 数据库中的示例代码:
1. 安装需要的依赖
```
pip install Flask
pip install Flask-WTF
pip install Flask_SQLAlchemy
pip install Werkzeug
```
2. 创建 Flask 应用并配置
```python
from flask import Flask, render_template, redirect, url_for, flash
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import InputRequired, Length, EqualTo
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret_key'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
db = SQLAlchemy(app)
```
3. 创建用户模型
```python
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), unique=True)
password = db.Column(db.String(100))
def __repr__(self):
return f'<User {self.username}>'
```
4. 创建表单类
```python
class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[InputRequired(), Length(min=4, max=50)])
password = PasswordField('Password', validators=[InputRequired(), Length(min=6, max=100)])
confirm_password = PasswordField('Confirm Password', validators=[InputRequired(), EqualTo('password')])
submit = SubmitField('Register')
class LoginForm(FlaskForm):
username = StringField('Username', validators=[InputRequired(), Length(min=4, max=50)])
password = PasswordField('Password', validators=[InputRequired(), Length(min=6, max=100)])
submit = SubmitField('Login')
```
5. 创建路由和视图函数
```python
@app.route('/')
def index():
return render_template('index.html')
@app.route('/register', methods=['GET', 'POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
user = User(username=form.username.data, password=form.password.data)
db.session.add(user)
db.session.commit()
flash('Registration successful', 'success')
return redirect(url_for('login'))
return render_template('register.html', form=form)
@app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user and user.password == form.password.data:
flash('Login successful', 'success')
return redirect(url_for('index'))
else:
flash('Invalid username or password', 'error')
return render_template('login.html', form=form)
```
6. 创建模板文件
index.html:
```html
<!DOCTYPE html>
<html>
<head>
<title>Home - Flask App</title>
</head>
<body>
<h1>Welcome to Flask App</h1>
<p><a href="{{ url_for('login') }}">Login</a> or <a href="{{ url_for('register') }}">Register</a></p>
</body>
</html>
```
register.html:
```html
<!DOCTYPE html>
<html>
<head>
<title>Register - Flask App</title>
</head>
<body>
<h1>Register</h1>
<form method="POST" action="{{ url_for('register') }}">
{{ form.csrf_token }}
{{ form.username.label }} {{ form.username }}
{% for error in form.username.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
<br><br>
{{ form.password.label }} {{ form.password }}
{% for error in form.password.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
<br><br>
{{ form.confirm_password.label }} {{ form.confirm_password }}
{% for error in form.confirm_password.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
<br><br>
{{ form.submit }}
</form>
</body>
</html>
```
login.html:
```html
<!DOCTYPE html>
<html>
<head>
<title>Login - Flask App</title>
</head>
<body>
<h1>Login</h1>
<form method="POST" action="{{ url_for('login') }}">
{{ form.csrf_token }}
{{ form.username.label }} {{ form.username }}
{% for error in form.username.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
<br><br>
{{ form.password.label }} {{ form.password }}
{% for error in form.password.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
<br><br>
{{ form.submit }}
</form>
</body>
</html>
```
7. 运行 Flask 应用
```python
if __name__ == '__main__':
app.run(debug=True)
```
以上代码实现了一个简单的 Flask 应用,包括注册、登录等功能,并将用户数据存储在 SQLite 数据库中。
阅读全文