使用 Flask 实现简单的登录注册功能

目录

[1. 引言](#1. 引言)

[2. 环境准备](#2. 环境准备)

[3. 数据库设置](#3. 数据库设置)

[4. Flask 应用基本配置](#4. Flask 应用基本配置)

[5. 实现用户注册](#5. 实现用户注册)

[6. 实现用户登录](#6. 实现用户登录)

[7. 路由配置](#7. 路由配置)

[8. 创建前端页面](#8. 创建前端页面)

[9. 结论](#9. 结论)


1. 引言

在这篇文章中,我们将使用 Flask 框架创建一个简单的登录和注册系统。Flask 是一个轻量级的 Python Web 框架,适合快速开发 Web 应用。

2. 环境准备

  • 安装 Flask:可以通过 pip 安装 Flask 和相关依赖:

    复制代码
    pip install Flask 

    以下是具体配置

python 复制代码
from flask import Flask, render_template, request, render_template_string, redirect, url_for
from flask_mysqldb import MySQL
from werkzeug.security import generate_password_hash, check_password_hash
from config import Config  # 导入配置文件
  • 创建项目结构:

    python 复制代码
    flask_demologin/
    ├── app.py
    ├── config.py
    ├── templates/
    │   ├── login.html
    │   ├── res.html
    │   └── index.html
    └── static/
        └── css/
        └── img/

3. 数据库设置

  • 使用 MySQL :
    • 创建数据库及用户表。

      CREATE DATABASE demologin;
      USE demologin;

      CREATE TABLE users (
      id INT AUTO_INCREMENT PRIMARY KEY,
      username VARCHAR(100) NOT NULL UNIQUE,
      password VARCHAR(255) NOT NULL
      );

4. Flask 应用基本配置

  • config.py 文件配置数据库连接:

    复制代码
    class Config:
    MYSQL_HOST = 'localhost'
    MYSQL_USER = 'root'  # 替换为你的 MySQL 用户名
    MYSQL_PASSWORD = 'root'  # 替换为你的 MySQL 密码
    MYSQL_DB = 'demologin' # 替换为你的 数据库名称

5. 实现用户注册

  • 在 app.py 中创建注册路由 :

    python 复制代码
    @app.route('/register', methods=['POST'])
    def register():
        name = request.form.get('username')
        pwd = request.form.get('password')
    
        if not name or not pwd:
            return render_template_string("用户名和密码不能为空,<a href='/'>返回登录</a>"), 400
    
        cur = mysql.connection.cursor()
        cur.execute("SELECT * FROM users WHERE username = %s", (name,))
        user = cur.fetchone()
    
        if user:
            return render_template_string("用户名已存在,<a href='/'>返回登录</a>"), 400
    
        hashed_pwd = generate_password_hash(pwd)
        cur.execute("INSERT INTO users (username, password) VALUES (%s, %s)", (name, hashed_pwd))
        mysql.connection.commit()
        cur.close()
    
        return render_template_string("注册成功,<a href='/'>返回登录</a>"), 201

6. 实现用户登录

  • 在 app.py 中创建登录路由 :

    复制代码
    @app.route('/login', methods=['POST'])
    def login():
        name = request.form.get('username')
        pwd = request.form.get('password')
    
        if not name or not pwd:
            return render_template_string("用户名和密码不能为空,<a href='/'>返回注册</a>"), 400
    
        cur = mysql.connection.cursor()
        cur.execute("SELECT * FROM users WHERE username = %s", (name,))
        user = cur.fetchone()
    
        if user and check_password_hash(user[2], pwd):  # user[2] 是密码字段
            return redirect(url_for('home'))  # 登录成功,重定向到主页
        else:
            return "用户名或密码错误", 401

7. 路由配置

  • 设置首页和重定向 :

    复制代码
    @app.route('/')
    def home():
        return render_template('index.html')  # 渲染主页模板
    • 设置登录页面和注册页面和重定向:

      @app.route('/')
      def Index_login(): # put application's code here
      return render_template('login.html')

      @app.route('/res')
      def Index_res(): # put application's code here
      return render_template('res.html')

8. 创建前端页面

  • login.html 和 res.html 的简单示例:

    python 复制代码
    <!-- login.html -->
    <div class="cont-parent"> 
            <div class="cont">
                <div class="form sign-in">
                    <h2>Welcome back, Doctor</h2>
                    <form action="/login" method="post">
                        <label>
                            <span>用户名</span>
                            <input type="text" name="username" placeholder="Username" required/>
                        </label>
                        <label>
                            <span>密码</span>
                            <input type="password" name="password" placeholder="Password" required/>
                        </label>
                        <button type="submit" class="submit">登录</button>
                    </form>
                    <p class="forgot-pass">忘记密码?</p>
                    <button type="button" class="fb-btn">链接 <span>facebook</span></button>
                </div>
                <div class="sub-cont">
                    <div class="img">
                        <div class="img__text m--up">
                            <h2>刚来?</h2>
                            <p>那就<a href="/res">注册</a>一个吧!</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    
    <!-- res.html -->
    <div class="cont-parent"> 
        <div class="cont">
            <div class="form sign-in">
                <h2>Time to feel like home,</h2>
                <form action="/register" method="post">
                        <label>
                            <span>用户名</span>
                            <input type="text" name="username" placeholder="Username" required/>
                        </label>
                        <label>
                            <span>密码</span>
                            <input type="password" name="password" placeholder="Password" required/>
                        </label>
                        <button type="submit" class="submit">注册</button>
                </form>
                    <button type="button" class="fb-btn">Join with <span>facebook</span></button>
            </div>
            <div class="sub-cont">
                <div class="img">
                    <div class="img__text m--up">
                        <h2>已经有账号了?</h2>
                        <p>那就去<a href="/">登录</a>吧!</p>
                    </div>
    
                </div>
                
        </div>
        </div>
        </div>

9. 结论

通过本文,我们实现了一个基本的登录和注册功能。

以下是实现的效果图(前端靠大家自由发挥,提供的html代码进作为参考)

相关推荐
前端精髓35 分钟前
结构化输出with_structured_output(抽卡)
python·langchain
尹人入圣1 小时前
目前热门的IP驱动产业新场景新工具
网络·python·网络协议·tcp/ip
Nuanyt2 小时前
Agent 学习笔记(下篇三):上线工程、进阶选择与操作界面(Stage 7 / 7.5 / 8 + 延伸路线)
笔记·python·学习·memory·aiagent·harness
吴卫斌2 小时前
定投ETF实战指南(四):行业/主题ETF——定投的“进攻端“
开发语言·python·股票·量化
2601_967987373 小时前
Python——入门级(定义功能def函数)
python·函数·可变参数·默认参数·关键字参数
Decay__4 小时前
09_MySQL 闪回与时间点恢复 —— binlog 回放、mysqlbinlog、PITR 与误删恢复
运维·数据库·sql·mysql·架构
专注仿真5 小时前
梯度提升类(XFBoost)算法详解与代码实例
开发语言·人工智能·python·算法·大模型训练·控制算法
外收内放5 小时前
Python基础语法练习题(75)
开发语言·python·学习
梦影_6 小时前
MySQL进阶教程(五)—— SQL调优(下)
android·大数据·数据库·后端·sql·mysql·database
黑十6 小时前
PyTorch 报 “no CUDA GPUs are available“ 怎么办?3 步排查
服务器·网络·人工智能·pytorch·python