NameError:未定义全局名称“flash”

时间:2017-09-03 23:48:48

标签: python sqlite sqlalchemy flask-sqlalchemy

我正在通过以下教程构建基本的Flask应用程序来学习数据库:https://www.tutorialspoint.com/flask/flask_sqlalchemy.htm我目前正处于需要通过SQLAlchemy连接到SQLITE3数据库的位置。说实话,它并不顺利。我收到此错误:NameError:全局名称'flash'未定义

这是我的 app.py

#!/usr/bin/python

from flask import Flask, render_template, json, request
from flask_sqlalchemy import SQLAlchemy
import sqlite3



conn = sqlite3.connect('test.db')




app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3'
db = SQLAlchemy(app)


class Students(db.Model):
    id = db.Column('student_id',db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True)

    def __init__(self, name, id):
        self.name = name
        self.id = id

    def __repr__(self):
        return '<Students %r>' % self.name


db.create_all()


@app.route("/")
def main():
    return render_template('index.html')




@app.route('/new', methods = ['GET', 'POST'])
def new():
   if request.method == 'POST':
      if not request.form['name'] or not request.form['id']:
         flash('Please enter all the fields', 'error')
      else:
         student = Students(request.form['name'], request.form['id'])
         db.session.add(student)
         db.session.commit()

         flash('Record was successfully added')
         return redirect(url_for('show_all'))
   return render_template('new.html')



@app.route("/admin")
def show_all():
   return render_template('show_all.html', students = students.query.all() )



    # create user code will be here !!


if __name__ == "__main__":
    app.run(debug=True)

的index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Attendance System</title>


    <link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">

    <link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">


</head>

<body>

    <div class="container">
        <div class="header">
            <nav>
                <ul class="nav nav-pills pull-right">
                    <li role="presentation" class="active"><a href="#">Home</a>
                    </li>
                    <li role="presentation"><a href="#">Sign In</a>
                    </li>
                    <li role="presentation"><a href="new">Sign Up</a>
                    </li>
                </ul>
            </nav>
            <h3 class="text-muted">Python Flask App</h3>
        </div>

        <div class="jumbotron">
            <h1>Attendance App</h1>
            <p class="lead"></p>
            <p><a class="btn btn-lg btn-success" href="new" role="button">Sign up today</a>
                <a class="btn btn-lg btn-success" href="show_all" role="button">Administrate</a>
            </p>
        </div>

        <footer class="footer">
            <p>&copy; Company 2015</p>
        </footer>

    </div>
</body>

</html>

show_all.html

    <!DOCTYPE html>
    <html lang = "en">
       <head></head>
       <body>

          <h3>
             <a href = "{{ url_for('show_all') }}">Comments - Flask 
                SQLAlchemy example</a>
          </h3>

          <hr/>
          {%- for message in get_flashed_messages() %}
             {{ message }}
          {%- endfor %}

          <h3>Students (<a href = "{{ url_for('new') }}">Add Student
             </a>)</h3>

          <table>
             <thead>
                <tr>
                   <th>Name</th>
                   <th>Id</th>
                </tr>
             </thead>

             <tbody>
                {% for student in students %}
                   <tr>
                      <td>{{ student.name }}</td>
                      <td>{{ student.id }}</td>

                {% endfor %}
             </tbody>
          </table>

       </body>
    </html>

**new.html**

<!DOCTYPE html>
<html>
   <body>

      <h3>Attendance</h3>
      <hr/>

      {%- for category, message in get_flashed_messages(with_categories = true) %}
         <div class = "alert alert-danger">
            {{ message }}
         </div>
      {%- endfor %}

      <form action = "{{ request.path }}" method = "post">
         <label for = "name">Name</label><br>
         <input type = "text" name = "name" placeholder = "Name" /><br>
         <label for = "id">Id Number</label><br>
         <input type = "text" name = "id" placeholder = "Student Id" /><br>
         <input type = "submit" value = "Sign-in!" />

      </form>

   </body>
</html>

问题:

我不知道连接是否有效,即使错误得到了修复NameError,因为它是我的第一个,起初我尝试使用MySQL但不推荐使用flask.ext.mysql,所以我尝试切换到SQLAlchemy和SQLite3。对于像我这样的新手,我感激不尽。谢谢!

1 个答案:

答案 0 :(得分:9)

<form asp-action="Edit"> <div class="form-horizontal"> <h4>Edit Customer</h4> <hr /> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <input type="hidden" asp-for="Id" /> <div class="form-group"> <label asp-for="Name" class="col-md-2 control-label"></label> <div class="col-md-10"> <input id="Name" name="Name" class="form-control" /> <span asp-validation-for="Name" class="text-danger"></span> </div> </div> <h4>Home Address</h4> <input type="hidden" asp-for="HomeAddress_Id" /> <div class="form-group"> <label asp-for="HomeAddress_AddressLine1" class="col-md-2 control-label"></label> <div class="col-md-10"> <input id="HomeAddress_AddressLine1" name="HomeAddress_AddressLine1" class="form-control" /> </div> </div> <div class="form-group"> <label asp-for="HomeAddress_AddressLine2" class="col-md-2 control-label"></label> <div class="col-md-10"> <input id="HomeAddress_AddressLine2" name="HomeAddress_AddressLine2" class="form-control" /> </div> </div> <div class="form-group"> <label asp-for="HomeAddress_City" class="col-md-2 control-label"></label> <div class="col-md-10"> <input id="HomeAddress_City" name="HomeAddress_City" class="form-control" /> </div> </div> <div class="form-group"> <label asp-for="HomeAddress_StateCode" class="col-md-2 control-label"></label> <div class="col-md-10"> <input id="HomeAddress_StateCode" name="HomeAddress_StateCode" class="form-control" /> </div> </div> <div class="form-group"> <label asp-for="HomeAddress_PostalCode" class="col-md-2 control-label"></label> <div class="col-md-10"> <input id="HomeAddress_PostalCode" name="HomeAddress_PostalCode" class="form-control" /> </div> </div> <h4>Work Address</h4> <input type="hidden" asp-for="WorkAddress_Id" /> <div class="form-group"> <label asp-for="WorkAddress_AddressLine1" class="col-md-2 control-label"></label> <div class="col-md-10"> <input id="WorkAddress_AddressLine1" name="WorkAddress_AddressLine1" class="form-control" /> </div> </div> <div class="form-group"> <label asp-for="WorkAddress_AddressLine2" class="col-md-2 control-label"></label> <div class="col-md-10"> <input id="WorkAddress_AddressLine2" name="WorkAddress_AddressLine2" class="form-control" /> </div> </div> <div class="form-group"> <label asp-for="WorkAddress_City" class="col-md-2 control-label"></label> <div class="col-md-10"> <input id="WorkAddress_City" name="WorkAddress_City" class="form-control" /> </div> </div> <div class="form-group"> <label asp-for="WorkAddress_StateCode" class="col-md-2 control-label"></label> <div class="col-md-10"> <input id="WorkAddress_StateCode" name="WorkAddress_StateCode" class="form-control" /> </div> </div> <div class="form-group"> <label asp-for="WorkAddress_PostalCode" class="col-md-2 control-label"></label> <div class="col-md-10"> <input id="WorkAddress_PostalCode" name="WorkAddress_PostalCode" class="form-control" /> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Save" class="btn btn-default" /> </div> </div> </form> 添加到您的代码中。所有HTML文件都与问题无关。