如何在Python中利用HTML表单实现账号密码存入数据库?
用Flask实现表单数据存入数据库的完整步骤
1. 先修正你的HTML表单
原始表单缺少提交方式和目标路由,需要补充method="POST"和提交路径,同时增加前端必填验证,避免空提交:
<form method="POST" action="/submit"> <label for="user-name">Username:</label> <input type="text" name="username" id="user-name" required> <label for="user-pwd">Password:</label> <input type="password" name="user-password" id="user-pwd" required> <input type="submit" value="Submit"> </form>
2. 安装依赖
先安装必要的Python库:
pip install flask flask-sqlalchemy flask-bcrypt
flask:核心Web框架flask-sqlalchemy:简化数据库操作的ORM工具flask-bcrypt:安全加密密码(绝对禁止明文存储密码)
3. 编写Flask后端代码
创建app.py文件,代码如下:
from flask import Flask, render_template, request, redirect, url_for from flask_sqlalchemy import SQLAlchemy from flask_bcrypt import Bcrypt # 初始化Flask应用 app = Flask(__name__) # 配置SQLite数据库(开发测试用,生产可换MySQL/PostgreSQL) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.secret_key = 'your-random-secret-key' # 自定义任意字符串,保障会话安全 # 初始化数据库和密码加密工具 db = SQLAlchemy(app) bcrypt = Bcrypt(app) # 定义用户数据表模型 class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) password_hash = db.Column(db.String(120), nullable=False) # 首次运行时创建数据库表 with app.app_context(): db.create_all() # 路由:显示表单页面 @app.route('/') def index(): return render_template('index.html') # 表单文件需放在templates文件夹下 # 路由:处理表单提交 @app.route('/submit', methods=['POST']) def submit(): # 获取表单提交的字段值 username = request.form.get('username') password = request.form.get('user-password') # 检查用户名是否已存在 existing_user = User.query.filter_by(username=username).first() if existing_user: # 实际项目可添加提示信息,这里先重定向回表单页 return redirect(url_for('index')) # 加密密码 hashed_password = bcrypt.generate_password_hash(password).decode('utf-8') # 创建新用户对象并写入数据库 new_user = User(username=username, password_hash=hashed_password) db.session.add(new_user) db.session.commit() # 提交成功后的反馈,可替换为跳转页面 return "用户注册成功!" if __name__ == '__main__': app.run(debug=True)
4. 项目结构
按如下结构组织文件:
your-project/ ├── app.py ├── templates/ │ └── index.html # 存放修改后的HTML表单 └── users.db # 运行后自动生成的SQLite数据库文件
5. 运行测试
- 在项目目录下执行
python app.py - 打开浏览器访问
http://localhost:5000 - 输入用户名和密码提交,数据会加密后存入数据库
关键注意事项
- 密码必须加密存储,
flask-bcrypt是最基础的安全要求 - 生产环境建议替换SQLite为MySQL或PostgreSQL,只需修改
SQLALCHEMY_DATABASE_URI配置(例如mysql+pymysql://user:pass@localhost/db_name) - 后端需补充更多验证逻辑,比如用户名长度、密码强度校验,避免非法数据入库
- 可添加Flask的
flash功能实现用户友好的错误提示
内容的提问来源于stack exchange,提问作者Shivam rola
相关产品推荐
相关产品推荐

