HTML表单中的数据不会使用Flask(Python)传递给MySQL

时间:2019-01-10 00:34:25

标签: python mysql flask sqlalchemy pythonanywhere

在这里我需要一些帮助。我只是无法获得将HTML表单中的数据插入MySQL的代码。这些行总是插入而没有任何数据。完全是空的。让我知道你的想法!

PS:MySql还有2个字段,我尚未使用,这些文件都托管在PythonAnywhere上。

HTML(仅表单):

<form action="{{ url_for('register_user') }}" method="post">
    <div class="register-form">

        <input type="text" class="register-field" id="firstname" value="" placeholder="First name" name="firstname">
        <label class="register-field-icon fui-user" for="register-name"></label>

        <input type="text" class="register-field" id="lastname" value="" placeholder="Last name" name="lastname">
        <label class="register-field-icon fui-user" for="register-name"></label>

        <input type="text" class="register-field" id="email" value="" placeholder="Email" name="email">
        <label class="register-field-icon fui-user" for="register-name"></label>

        <input type="password" class="register-field" id="password" value="" placeholder="Password" name="password">
        <label class="register-field-icon fui-lock" for="register-pass"></label>

        <label class="register-field-icon fui-lock" for="register-pass"></label>
        <input type="submit" value="Register" id="register-btn" class="btn register-btn">

    </div>
</form>

FLASK(没有MySql的连接详细信息):

from datetime import datetime
from flask import Flask, redirect, render_template, request, url_for, session
from flask_login import current_user, login_required, login_user, LoginManager, logout_user, UserMixin
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import check_password_hash
from flask import session as login_session


@app.route("/register/", methods=["GET", "POST"])
    def register_user():
    if request.method == "GET":
        return render_template("register.html")

    else:

        User_Data = Reg_User(firstname=request.form["firstname"],lastname=request.form["lastname"],email=request.form["email"],password_hash=request.form["password"])#,groups="freeuser")
        db.session.add(User_Data)
        db.session.commit()

        return redirect(url_for('login'))



class Reg_User(db.Model):

    __tablename__ = 'users'

    def __init__(self, firstname, lastname, email, password_hash):#, groups):

        id = db.Column(db.Integer, primary_key=True)
        firstname = db.Column(db.String(20), unique=False, nullable=False)
        lastname = db.Column(db.String(45), unique=False, nullable=False)
        email = db.Column(db.String(45), unique=True, nullable=False)
        password_hash = db.Column(db.String(128), unique=False, nullable=False)


    def __repr__(self):
        return '<Reg_User %r>'.format(self.username)

MYSQL:

+--------------------------------------------------------------------------

|  id  |  username  |  password_hash  |  firstname  |  lastname  |  email  |   groups  |  regtime  |

+--------------------------------------------------------------------------

|  43  |     NULL     |          NULL           |     NULL      |     NULL     |  NULL  |   NULL   |  2019-01-09 22:00:56 |

|  44  |     NULL     |          NULL           |     NULL      |     NULL     |  NULL  |   NULL   |  2019-01-09 22:55:09 |

|  45  |     NULL     |          NULL           |     NULL      |     NULL     |  NULL  |   NULL   |  2019-01-09 23:04:15 |

|  46  |     NULL     |          NULL           |     NULL      |     NULL     |  NULL  |   NULL   |  2019-01-09 23:10:32 |

1 个答案:

答案 0 :(得分:3)

您正在错误地创建和使用模型类。

在您的情况下,您实际上根本不需要__init__。另外,您在构造函数中做了一些不正确的事情,关于Python类的简短复习教程在这里不会受到损害。

这是您可以遵循的用户模型模式

您不需要定义__init__

class User(db.Model):
    """Users"""

    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    first_name = db.Column(db.String(25), nullable=False)
    last_name = db.Column(db.String(25), nullable=False)
    image_url = db.Column(db.Text, default=DEFAULT_IMG_URL)
    email = db.Column(db.String(45), unique=True, nullable=False)
    password = db.Column(db.String(128), unique=False, nullable=False)

    def __repr__(self):
        return f'<User id:{self.id} first_name:{self.first_name} last_name:{self.last_name} image_url:%.8s' % self.image_url

    def get_full_name(self):
        return f'{self.first_name} = {self.last_name}'

您可以通过创建模型实例然后提交到数据库来创建新用户

@app.route("/register/", methods=["GET", "POST"])
    def register_user():
    if request.method == "GET":
        return render_template("register.html")

    else:
        first_name = request.form.get('first_name')
        last_name = request.form.get('last_name') 
        email = request.form.get('email')
        password = request.form.get('password')

        # hash your password, this is a separate topic
        hashed = bcrypt.generate_password_hash(password).decode('utf-8')

        user = User(first_name=first_name, last_name=last_name, email=email, password=hashed)

        db.session.add(user)
        db.session.commit()

        return redirect(url_for('login'))