首页 > 数据库 >flask,mysql实现用户登录注册注销改密

flask,mysql实现用户登录注册注销改密

时间:2023-04-04 12:57:05浏览次数:36  
标签:session flask app request 改密 html mysql password email

flask.py文件

from flask import Flask, render_template, request, redirect, url_for, flash, session

from flask_mysqldb import MySQL

import bcrypt

app = Flask(__name__)

app.secret_key = "secret"

# MySQL configurations

app.config['MYSQL_HOST'] = 'localhost'

app.config['MYSQL_USER'] = 'root'

app.config['MYSQL_PASSWORD'] = 'password'

app.config['MYSQL_DB'] = 'users'

 

mysql = MySQL(app)

 

 

@app.route('/')

def home():

    return render_template('home.html')

@app.route('/login', methods=['GET', 'POST'])

def login():

    if request.method == 'POST' and 'email' in request.form and 'password' in request.form:

        email = request.form['email']

        password = request.form['password'].encode('utf-8')

        cur = mysql.connection.cursor()

        cur.execute('SELECT * FROM accounts WHERE email = %s', (email,))

        account = cur.fetchone()

        cur.close()

        if account:

            if bcrypt.hashpw(password, account[2].encode('utf-8')) == account[2].encode('utf-8'):

                session['loggedin'] = True

                session['id'] = account[0]

                session['email'] = account[1]

                flash('You have been logged in!', 'success')

                return redirect(url_for('dashboard'))

            else:

                flash('Incorrect password!', 'danger')

        else:

            flash('Email not found!', 'danger')

    return render_template('login.html')

@app.route('/register', methods=['GET', 'POST'])

def register():

    if request.method == 'POST' and 'email' in request.form and 'password' in request.form:

        email = request.form['email']

        password = request.form['password'].encode('utf-8')

        hashed_password = bcrypt.hashpw(password, bcrypt.gensalt())

        cur = mysql.connection.cursor()

        cur.execute('SELECT * FROM accounts WHERE email = %s', (email,))

        account = cur.fetchone()

        if account:

            flash('Email already exists!', 'danger')

        else:

            cur.execute('INSERT INTO accounts VALUES (NULL, %s, %s)', (email, hashed_password,))

            mysql.connection.commit()

            flash('You have successfully registered!', 'success')

            return redirect(url_for('login'))

        cur.close()

    return render_template('register.html')

 

 

@app.route('/dashboard')

def dashboard():

    if 'loggedin' in session:

        return render_template('dashboard.html', email=session['email'])

    return redirect(url_for('login'))

 

 

@app.route('/logout')

def logout():

    session.pop('loggedin', None)

    session.pop('id', None)

    session.pop('email', None)

    flash('You have been logged out!', 'success')

    return redirect(url_for('login'))

 

 

@app.route('/change-password', methods=['GET', 'POST'])

def change_password():

    if 'loggedin' in session:

        if request.method == 'POST' and 'current_password' in request.form and 'new_password' in request.form:

            current_password = request.form['current_password'].encode('utf-8')

            new_password = request.form['new_password'].encode('utf-8')

            cur = mysql.connection.cursor()

            cur.execute('SELECT * FROM accounts WHERE id = %s', (session['id'],))

            account = cur.fetchone()

            if bcrypt.hashpw(current_password, account[2].encode('utf-8')) == account[2].encode('utf-8'):

                hashed_new_password = bcrypt.hashpw(new_password, bcrypt.gensalt())

                cur.execute('UPDATE accounts SET password = %s WHERE id = %s', (hashed_new_password, session['id'],))

                mysql.connection.commit()

                flash('Password changed successfully!', 'success')

            else:

                flash('Incorrect password!', 'danger')

        return render_template('change_password.html')

    return redirect(url_for('login'))

 

 

if __name__ == '__main__':

    app.run(debug=True)

HTML文件:

home.html:

复制{% extends 'base.html' %}

{% block content %}

<h1>Welcome to my Flask App!</h1>

{% endblock %}

base.html:

复制<!doctype html>

<html>

<head>

    <title>Flask App</title>

    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">

</head>

<body>

    <div class="container">

        <header>

            <nav>

                <ul>

                    <li><a href="{{ url_for('home') }}">Home</a></li>

                    {% if session.loggedin %}

                    <li><a href="{{ url_for('dashboard') }}">Dashboard</a></li>

                    <li><a href="{{ url_for('logout') }}">Logout</a></li>

                    {% else %}

                    <li><a href="{{ url_for('login') }}">Login</a></li>

                    <li><a href="{{ url_for('register') }}">Register</a></li>

                    {% endif %}

                </ul>

            </nav>

        </header>

        {% with messages = get_flashed_messages() %}

        {% if messages %}

        <ul class="flashes">

            {% for message in messages %}

            <li>{{ message }}</li>

            {% endfor %}

        </ul>

        {% endif %}

        {% endwith %}

        {% block content %}{% endblock %}

    </div>

    <script src="{{ url_for('static', filename='js/script.js') }}"></script>

</body>

</html>

login.html:

复制{% extends 'base.html' %}

{% block content %}

<h1>Login</h1>

<form method="POST">

    <div>

        <label for="email">Email</label>

        <input type="email" name="email" id="email" required>

    </div>

    <div>

        <label for="password">Password</label>

        <input type="password" name="password" id="password" required>

    </div>

    <button type="submit">Login</button>

</form>

{% endblock %}

register.html:

复制{% extends 'base.html' %}

{% block content %}

<h1>Register</h1>

<form method="POST">

    <div>

        <label for="email">Email</label>

        <input type="email" name="email" id="email" required>

    </div>

    <div>

        <label for="password">Password</label>

        <input type="password" name="password" id="password" required>

    </div>

    <button type="submit">Register</button>

</form>

{% endblock %}

dashboard.html:

复制{% extends 'base.html' %}

{% block content %}

<h1>Welcome, {{ email }}!</h1>

{% endblock %}

change_password.html:

复制{% extends 'base.html' %}

{% block content %}

<h1>Change Password</h1>

<form method="POST">

    <div>

        <label for="current_password">Current Password</label>

        <input type="password" name="current_password" id="current_password" required>

    </div>

    <div>

        <label for="new_password">New Password</label>

        <input type="password" name="new_password" id="new_password" required>

    </div>

    <button type="submit">Change Password</button>

</form>

{% endblock %}

CSS文件:

复制.container {

    max-width: 800px;

    margin: 0 auto;

    padding: 0 20px;

}

header {

    display: flex;

    justify-content: space-between;

    align-items: center;

    margin-bottom: 20px;

}

nav ul {

    display: flex;

    list-style: none;

    margin: 0;

    padding: 0;

}

nav ul li {

    margin: 0 10px;

}

nav ul li a {

    color: #333;

    text-decoration: none;

}

nav ul li a:hover {

    text-decoration: underline;

}

.flashes {

    list-style: none;

    margin: 0;

    padding: 0;

}

.flashes li {

    margin-bottom: 10px;

    padding: 10px;

    border-radius: 5px;

}

.success {

    background-color: #d4edda;

    color: #155724;

    border: 1px solid #c3e6cb;

}

.danger {

    background-color: #f8d7da;

    color: #721c24;

    border: 1px solid #f5c6cb;

}

JavaScript文件:

复制// nothing here for now

 

 

标签:session,flask,app,request,改密,html,mysql,password,email
From: https://www.cnblogs.com/1h1y/p/17286021.html

相关文章

  • mysql 时间转换成日期
    很多时候都存了当前时间,没有单独存日期这个函数。查询按天查询的时候,需要转换成日期。selectDATE_FORMAT(create_time,"%Y-%m-%d")asday,count(DISTINCT(product_user_id))asuv,count(product_user_id)aspvfromdts_pay_orderwhereclient_id=32andcreate_ti......
  • ERROR: Could not find a version that satisfies the requirement pymysql (from ver
    踩过的坑不管是idea中直接引入还是 pip3installpymysql都会报错:ERROR:Couldnotfindaversionthatsatisfiestherequirementpymysql(fromversions:none)  原因是网络问题,需要需要使用国内镜像源来加速,比如豆瓣源pipinstallpymysql-ihttp://pypi.douba......
  • MySQL8的root帐号授权
    执行下面的命令MySQL8会报错:grantallprivilegesondb_name.*to'root'@'%'###Cause:java.sql.SQLSyntaxErrorException:Accessdeniedforuser'root'@'%'todatabase'db_name'解决办法:SELECT`User`,`Grant_priv......
  • 安装MYSQL_5.0/8.0教程(附数据库和客户端工具下载链接)
    1.Mysql5.7下载网盘下载(推荐):链接:https://pan.quark.cn/s/d98d2536f847提取码:kbyN 官网下载:mysql下载地址:https://dev.mysql.com/downloads/windows/installer/8.0.html跳转到上述页面,选择Archives(历史存档)选择版本-下载2.Mysql安装双击打开下载好的文件。以前安......
  • CentOS7 卸载mysql(YUM源方式)
     防止重装yum方式查看yum是否安装过mysqlyumlistinstalledmysql*如或显示了列表,说明系统中有MySQLyum卸载 根据列表上的名字 yumremovemysql-community-clientmysql-community-commonmysql-community-libsmysql-community-libs-compatmysql-commun......
  • mysql8.0修改root密码
    修改密码按大部分教程的操作结束,进行登录的时候还是会出现ERROR1045(28000):Accessdeniedforuser‘root’@‘localhost’(usingpassword:YES)经过多次尝试,终于解决这个问题。以下是操作过程记录。关键为第二步。1.确保mysqlserver已经停止运行查询mysqlserver......
  • MySql8.0.30忽略大小写配置
    说明:此文档只是针对已经初始化了的数据库,如果是新安装的数据库直接在/etc/my.cnf文件中新增一行配置:lower_case_table_names=1即可。因为默认配置是0. 步骤1:备份mysql所有数据,并删掉data目录里的所有文件。可能是因为数据库里的表默认设置了lower_case_table_names=0,如果不删......
  • MySQL带排序的分页查询优化
    MySQL带排序的分页查询优化需求在日常开发中,经常会遇到这么一种情况,一张表的数据量较大(500万左右)的时候,对其进行分页查询的时候,在分页比较深的情况下,查询效率会急剧下降。对于这种情况,我们需要做一些分页查询的优化。准备创建脚本CREATETABLEstudent(idINTNOTNULL......
  • 如何理解MySQL的MVCC多版本并发控制
    前言我们知道在mysql中存在四种隔离级别(读未提交、读已提交、可重复读、序列化),它默认的就是隔离级别就是可重复读,它能够解决脏读、不可重复读问题,并且在innodb引擎下能部分解决幻读问题。在mysqlinnodb存储引擎下RC(读已提交),RR(可重复读)基于MVCC(多版本并发控制)进行并发事务控......
  • MYSQL基础知识之DQL语句
    1、DQL概念DQL英文全称是DataQueryLanguage(数据查询语言),用来查询数据库中的表的记录2、基本查询语法:#查询全部字段SELECT*FROM表名; #查询多个字段SELECT字段1,字段2,字段3...FROM表名; #去重 语法:SELECTDISTINCT字段列表FROM表名;   3、条......