使用flask链接mysql

问题描述 投票:0回答:1

我的老师给了我一个任务来链接一个表格,该表格需要使用

name
和html
制作的
email
flask
地址。他说将其链接到mysql
中的
数据库。该数据库将存储从表格收到的信息。如何设置数据库,以便获得的姓名和电子邮件将显示在数据库中的表格上

我查看了 GeekForGeeks 网站,但他们都在代码中输入了他们想要添加到表格中的名称和其他详细信息,这不是我想要的。

python html mysql flask
1个回答
0
投票

首先,您必须使用

pip install package_name
安装 Rowling 软件包:

  • 烧瓶(
    flask
    )
  • Flask SQLAlchemy (
    flask_sqlalchemy
    )
  • MySQL (
    mysql
    )

与您分享管理模板的代码示例,希望这可以帮助您解决问题。

admin.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Admin register</title>
    <style>
        .register-form {
            width: 500px;
            margin: 0 auto;
            text-align: center;
            padding: 10px;
            color: #fff;
            background: #396;
            border-radius: 10px;
            -webkit-border-radius: 10px;
            -moz-border-radius: 10px;
        }

        .register-form form input {
            padding: 5px;
        }

        .register-form .btn {
            padding: 5px;
            border-radius: 5px;
            text-decoration: none;
            width: 100px;
            display: inline-block;
            color: #fff;
            background: #36f;
        }

        .register-form .register {
            border: 0;
            width: 60px;
            padding: 8px;
        }
    </style>
</head>
<body>
<div class="register-form">
    <h1>Admin Register</h1>
    <form action="adminregister.php" method="POST">
        <p><label>E-Mail :</label>
            <input id="email" type="email" name="email" required/></p>

        <p><label>Password :</label>
            <input id="password" type="password" name="password" required/></p>
        <span id="message"></span>

        <input class="btn register" id="adminsubmit" type="submit" name="submit" value="Register"/>
        <span id="message"></span>
    </form>
</div>
</body>
</html>

admin.py


from flask import Blueprint, render_template, Flask, request, session, redirect, url_for
import pymysql
pymysql.install_as_MySQLdb()
from flask_mysqldb import MySQL
import MySQLdb.cursors
import re 

admin = Blueprint("admin", __name__, static_folder="static", template_folder="templates")
app = Flask(__name__)
app.secret_key = 'bb2fb443b5d32e26c08ba803de5beab1'

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'adminpythonlogin'

mysql = MySQL(app)


@admin.route('/main')
def adminindex():
    return render_template('adminhome.html')

@admin.route('/adminpythonlogin/', methods=['GET', 'POST'])
def adminlogin():
    msg = ''
    if request.method == 'POST' and 'adminusername' in request.form and 'adminpassword' in request.form:
        adminusername = request.form['adminusername']
        adminpassword = request.form['adminpassword']
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute('SELECT * FROM adminaccounts WHERE adminusername = %s AND adminpassword = %s', (adminusername, adminpassword,))
        adminaccount = cursor.fetchone()
        if adminaccount:
            session['adminloggedin'] = True
            session['adminid'] = adminaccount['adminid']
            session['adminusername'] = adminaccount['adminusername']
            return redirect(url_for('admin.adminhome'))
        else:
            msg = 'Incorrect username/password!'
    return render_template('adminindex.html', msg=msg)

@admin.route('/adminpythonlogin/adminlogout')
def adminlogout():
    session.pop('adminloggedin', None)
    session.pop('adminid', None)
    session.pop('adminusername', None)
    return redirect(url_for('adminlogin'))

@admin.route('/adminpythonlogin/adminregister', methods=['GET', 'POST'])
def adminregister():
    msg = ''
    if request.method == 'POST' and 'adminusername' in request.form and 'adminpassword' in request.form and 'adminemail' in request.form:
        adminusername = request.form['adminusername']
        adminpassword = request.form['adminpassword']
        adminemail = request.form['adminemail']
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute('SELECT * FROM adminaccounts WHERE adminusername = %s', (adminusername,))
        adminaccount = cursor.fetchone()
        if adminaccount:
            msg = 'Account already exists!'
        elif not re.match(r'[^@]+@[^@]+\.[^@]+', adminemail):
            msg = 'Invalid email address!'
        elif not re.match(r'[A-Za-z0-9]+', adminusername):
            msg = 'Username must contain only characters and numbers!'
        elif not adminusername or not adminpassword or not adminemail:
            msg = 'Please fill out the form!'
        else:
            cursor.execute('INSERT INTO adminaccounts VALUES (NULL, %s, %s, %s)', (adminusername, adminpassword, adminemail,))
            mysql.connection.commit()
            msg = 'You have successfully registered!'
    elif request.method == 'POST':
        msg = 'Please fill out the form!'
    return render_template('adminregister.html', msg=msg)

@admin.route('/adminpythonlogin/adminhome')
def adminhome():
    if 'adminloggedin' in session:
        return render_template('adminhome.html', adminusername=session['adminusername'])
    return redirect(url_for('adminlogin'))

@app.route('/adminpythonlogin/adminprofile')
def adminprofile():
    if 'adminloggedin' in session:
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute('SELECT * FROM adminaccounts WHERE adminid = %s', (session['adminid'],))
        account = cursor.fetchone()
        return render_template('adminprofile.html', account=account)
    return redirect(url_for('adminlogin'))

adminpythonlogin.sql

CREATE DATABASE IF NOT EXISTS `adminpythonlogin` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `adminpythonlogin`;

CREATE TABLE IF NOT EXISTS `adminaccounts` (
    `adminid` int(11) NOT NULL AUTO_INCREMENT,
    `adminusername` varchar(50) NOT NULL,
    `adminpassword` varchar(255) NOT NULL,
    `adminemail` varchar(100) NOT NULL,
    PRIMARY KEY (`adminid`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

INSERT INTO `adminaccounts` (`adminid`, `adminusername`, `adminpassword`, `adminemail`) VALUES (1, 'test', 'test', '[email protected]');

SELECT * FROM adminaccounts;
© www.soinside.com 2019 - 2024. All rights reserved.