无法使用Flask和Flask-WTF

时间:2017-10-02 03:52:00

标签: python database sqlite flask flask-wtforms

我一直坚持这个问题。我试图在我的SQLite数据库中添加一行,其中包含来自提交表单的数据。但是,似乎没有数据添加到我的数据库中。奇怪的是,当我运行手动向数据库添加数据的功能(详见下文)时,工作正常。 :/非常感谢任何帮助!

下面我有四个代码部分,创建注册表单,烧瓶路由功能,数据库插入方法,最后是表单的HTML。

我使用Flask-WTF创建我的SignupForm,如下所示,

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, Email, Length

class SignupForm(FlaskForm):
    username = StringField("Username", validators=[DataRequired("Username required!")])
    first_name = StringField("First Name", validators=[DataRequired("First name required!")])
    last_name = StringField("Last Name", validators=[DataRequired("Last name required!")])
    email = StringField("E-Mail", validators=[DataRequired("E-mail required!"), Email("Please enter a valid e-mail!")])
    password = PasswordField("Password", validators=[DataRequired("Password required!"), Length(min=5, message=("Password must be at least 5 characters."))])
    submit = SubmitField("Sign up!")

然后,我的路由文件中的signup()函数。

from flask import Flask, render_template, request, session, redirect, url_for, flash
from forms import SignupForm 
import database_methods

app = Flask(__name__)
app.secret_key = "development key"

@app.route('/signup', methods=["GET", "POST"])
def signup():
    """ Signs a user up for an account so that they may log in """
    form = SignupForm()

    if request.method == 'POST':
        if not form.validate(): # ensure that a user enters all fields correctly
            return render_template('signup.html', form=form)
        else:
            username = form.username.data
            first_name = form.first_name.data
            last_name = form.last_name.data
            email = form.email.data
            password = form.password.data
            database_methods.insert_row_in_db(username, first_name, last_name, email, password)

            return "All right! Signed up!"

    elif request.method == 'GET':
        return render_template('signup.html', form=form)

最后,我们有实际的方法来插入用户输入到表单中的数据。

import sqlite3
import os
from werkzeug.security import generate_password_hash
from uuid import uuid4

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DB_PATH = os.path.join(BASE_DIR, "chat.sqlite")


def insert_row_in_db(username, firstname, lastname, email, password):
    """ Creates a row in chat.sqlite's users table """
    uid = uuid4().hex
    pwd_hash = generate_password_hash(password)
    login_time = set_lastlogin(uid)
    row_data = (uid, username, firstname, lastname, email, pwd_hash, login_time, True)

    with sqlite3.connect(DB_PATH) as conn:
        c = conn.cursor()
        c.execute('''INSERT INTO users (uid, username, firstname, lastname, email, passwordhash, 
                  lastlogin, loggedin) VALUES (?, ?, ?, ?, ?, ?, ?, ?);''', row_data)

如果需要HTML文件供参考,这里就是。

{% extends "layout.html" %}

{% block content %}

<main>
    <div>
         <h2>Create an Account</h2>

         <form method="POST" action="/signup">
             {{ form.hidden_tag() }}

             <div>
                {{ form.username.label }}

                {% if form.username.errors %}
                    {% for error in form.username.errors %}
                        <p> {{ error }}</p>
                    {% endfor %}
                {% endif %}

                {{ form.username }}
            </div>

            <div>
                {{ form.first_name.label }}

                {% if form.first_name.errors %}
                    {% for error in form.first_name.errors %}
                        <p> {{ error }}</p>
                    {% endfor %}
                {% endif %}

                {{ form.first_name }}
            </div>

            <div>
                {{ form.last_name.label }}

                {% if form.last_name.errors %}
                    {% for error in form.last_name.errors %}
                        <p> {{ error }}</p>
                    {% endfor %}
                {% endif %}

                {{ form.last_name }}
            </div>

            <div>
                {{ form.email.label }}

                {% if form.email.errors %}
                    {% for error in form.email.errors %}
                        <p> {{ error }}</p>
                    {% endfor %}
                {% endif %}

                {{ form.email }}
            </div>

            <div>
                {{ form.password.label }}

                {% if form.password.errors %}
                    {% for error in form.password.errors %}
                        <p> {{ error }}</p>
                    {% endfor %}
                {% endif %}

                {{ form.password }}
            </div>

            {{ form.submit(class="btn btn-primary") }}
        </form>
    </div>
</main>

{% endblock content %}

我现在谷歌搜索了几个小时,并尝试了很多事情无济于事。您可以提供的任何帮助将非常感谢!!

提前谢谢! :)

2 个答案:

答案 0 :(得分:0)

为什么在查询后不尝试调用commit方法?在Flask文档http://flask.pocoo.org/docs/0.12/patterns/sqlite3/#initial-schemas中,它在查询之后提交。

def init_db():
    with app.app_context():
        db = get_db()
        with app.open_resource('schema.sql', mode='r') as f:
            db.cursor().executescript(f.read())
        db.commit()

我希望这会对你有所帮助。

答案 1 :(得分:0)

我使用的是Docker,之前从未使用过它。事实证明,docker正在创建一个我在PyCharm中使用的数据库。我的代码确实在工作,只是将它添加到与我期望的数据库不同的数据库中。