AI生成代码示例

实现一个简单的用户登录系统,该系统包括用户注册、登录和密码加密功能。以下是具体的实现步骤和代码示例。

用户注册功能

用户注册功能需要收集用户的基本信息,如用户名、邮箱和密码,并将这些信息存储到数据库中。密码需要加密存储以提高安全性。

python 复制代码
from flask import Flask, request, jsonify
from werkzeug.security import generate_password_hash

app = Flask(__name__)

@app.route('/register', methods=['POST'])
def register():
    data = request.get_json()
    username = data.get('username')
    email = data.get('email')
    password = data.get('password')

    if not username or not email or not password:
        return jsonify({'message': 'Missing required fields'}), 400

    hashed_password = generate_password_hash(password)
    # 存储用户信息到数据库
    # 示例代码省略数据库操作

    return jsonify({'message': 'User registered successfully'}), 201

用户登录功能

用户登录功能需要验证用户提供的凭证是否匹配数据库中的记录。密码需要解密并进行比对。

python 复制代码
from werkzeug.security import check_password_hash

@app.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    if not username or not password:
        return jsonify({'message': 'Missing required fields'}), 400

    # 从数据库中查询用户信息
    # 示例代码省略数据库查询
    user = {'username': username, 'password': 'hashed_password_from_db'}

    if not user or not check_password_hash(user['password'], password):
        return jsonify({'message': 'Invalid credentials'}), 401

    return jsonify({'message': 'Login successful'}), 200

密码加密与验证

密码加密使用 werkzeug.security 模块提供的 generate_password_hashcheck_password_hash 函数,确保密码存储的安全性。

python 复制代码
from werkzeug.security import generate_password_hash, check_password_hash

# 加密密码
password = 'securepassword123'
hashed_password = generate_password_hash(password)
print(f'Hashed password: {hashed_password}')

# 验证密码
is_valid = check_password_hash(hashed_password, password)
print(f'Password valid: {is_valid}')

数据库集成

为了完整实现用户系统,需要将上述功能与数据库集成。以下是使用 SQLite 数据库的示例代码。

python 复制代码
import sqlite3
from werkzeug.security import generate_password_hash

def init_db():
    conn = sqlite3.connect('users.db')
    cursor = conn.cursor()
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS users (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            username TEXT UNIQUE NOT NULL,
            email TEXT UNIQUE NOT NULL,
            password TEXT NOT NULL
        )
    ''')
    conn.commit()
    conn.close()

def register_user(username, email, password):
    hashed_password = generate_password_hash(password)
    conn = sqlite3.connect('users.db')
    cursor = conn.cursor()
    cursor.execute('INSERT INTO users (username, email, password) VALUES (?, ?, ?)',
                   (username, email, hashed_password))
    conn.commit()
    conn.close()

def verify_user(username, password):
    conn = sqlite3.connect('users.db')
    cursor = conn.cursor()
    cursor.execute('SELECT password FROM users WHERE username = ?', (username,))
    user = cursor.fetchone()
    conn.close()
    if user and check_password_hash(user[0], password):
        return True
    return False

测试用例

为确保功能的正确性,可以编写测试用例进行验证。

python 复制代码
import unittest
from app import app, init_db, register_user, verify_user

class TestUserSystem(unittest.TestCase):
    def setUp(self):
        app.config['TESTING'] = True
        self.client = app.test_client()
        init_db()

    def test_register(self):
        response = self.client.post('/register', json={
            'username': 'testuser',
            'email': 'test@example.com',
            'password': 'testpass'
        })
        self.assertEqual(response.status_code, 201)

    def test_login(self):
        register_user('testuser', 'test@example.com', 'testpass')
        response = self.client.post('/login', json={
            'username': 'testuser',
            'password': 'testpass'
        })
        self.assertEqual(response.status_code, 200)

if __name__ == '__main__':
    unittest.main()

通过以上扩展,文章内容变得更加详细且实用,涵盖了用户登录系统的各个方面,包括注册、登录、密码加密、数据库集成和测试用例。

相关推荐
山间小僧4 小时前
「AI学习笔记」RNN
机器学习·aigc·ai编程
可夫小子6 小时前
放弃 Claude 订阅?我用 8 年前的服务器,强跑 Google 最强开源模型 Gemma 4 真实测评!
ai编程
菜菜艾6 小时前
基于llama.cpp部署私有大模型
linux·运维·服务器·人工智能·ai·云计算·ai编程
Shawn_Shawn7 小时前
openspec使用手册
llm·ai编程·claude
刀法如飞7 小时前
AI Agent实战:我用Gemini批量完成了《道德经》解读
程序员·aigc·ai编程
小虎AI生活7 小时前
7 个理由 +3 步安装:Gemma 4 外贸选型与部署全攻略
ai编程
C澒8 小时前
IntelliPro 企业级产研协作平台:前端智能生产模块设计与落地
前端·ai编程
Cosolar8 小时前
Nanobot 深度解析:超轻量级通用 AI Agent 运行时的架构设计与实战指南
gpt·llm·ai编程
孟健8 小时前
我把Hermes里23个Agent全切到GLM-5.1:执行力比GPT强,但有个硬伤
ai编程
爱吃的小肥羊9 小时前
2026 最新 Codex 如何使用指南:ChatGPT 订阅、CLI 安装、App 登录全流程
aigc·ai编程