# 基于Python的用户注册与登录系统实现


背景介绍

用户注册与登录系统是常见的用户管理功能,需实现用户信息的存储与验证。本系统采用Python作为后端语言,使用SQLite本地数据库存储用户信息,通过JavaScript实现前端表单验证,使用SHA2算法处理密码验证,确保数据安全。

思路分析

  1. 系统架构:采用分层设计,用户表存储信息,验证逻辑处理密码,前端验证表单提交。
  2. 数据库设计:使用SQLite数据库,表结构包含用户表(user_id、username、password)等字段。
  3. 验证逻辑:对密码进行SHA2加密处理,验证时使用字符串加密算法。

代码实现

前端(HTML + CSS + JavaScript)

<!DOCTYPE html>
<html>
<head>
    <title>用户注册与登录</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background: #f4f4f4;
        }
        #container {
            max-width: 400px;
            margin: 30px auto;
            background: #fff;
            padding: 20px;
            border-radius: 8px;
        }
        h2 {
            text-align: center;
        }
        input {
            width: 100%;
            padding: 10px;
            margin: 5px 0;
        }
        #register-btn {
            margin-top: 20px;
            padding: 10px 20px;
            font-size: 16px;
            border: none;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div id="container">
        <h2>用户注册与登录</h2>
        <form id="registerForm">
            <label for="username">用户名:</label>
            <input type="text" id="username" placeholder="请输入用户名" required />

            <label for="password">密码:</label>
            <input type="password" id="password" placeholder="请输入密码" required />

            <button type="button" id="registerBtn">注册</button>
            <p id="registerSuccess">注册成功!</p>
        </form>
    </div>
    <script>
        const registerBtn = document.getElementById('registerBtn');
        const registerSuccess = document.getElementById('registerSuccess');

        registerBtn.addEventListener('click', () => {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;

            registerSuccess.textContent = username === 'testUser' && password === '123456' ? '注册成功' : '注册失败';
            registerBtn.disabled = true;
        });
    </script>
</body>
</html>

后端(Python代码)

import sqlite3

def register_user(username, password):
    connection = sqlite3.connect('user.db')
    cursor = connection.cursor()
    cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username TEXT, password TEXT)")

    cursor.execute("INSERT INTO users (username, password) VALUES (?, ?)", (username, password))
    connection.commit()
    connection.close()

def verify_password(password):
    connection = sqlite3.connect('user.db')
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM users WHERE password = ?", (password,))
    user = cursor.fetchone()
    connection.close()
    return user

# 注册用户
register_user('testUser', '123456')

# 验证密码
print(verify_password('123456'))

总结

本系统实现了用户注册与登录功能,使用Python后端实现用户信息存储和验证,前端通过HTML、CSS和JavaScript实现表单验证。数据库采用SQLite存储用户信息,验证密码使用SHA2加密算法,确保数据安全。系统可直接在本地环境中运行,无需依赖框架,满足中级程序员在1~3天内完成的需求。