使用Python3在Flask中访问数据库时出现未绑定本地错误

时间:2018-12-17 17:08:51

标签: python-3.x flask flask-sqlalchemy

我有一个简单的flask Web应用程序,它记录了本地用户时间和用户代理字符串,并通过ajax将其发布到数据库(userdatabase.db)中,该数据库是我在python解释器(使用Python3)上单独创建的。

这是我的模板/home.html:

<html>
  <head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  <script type=text/javascript>
   $(document).ready(function () {
     console.log('Date Being Posted'); // this will fire at first
       $.ajax({

            url:"{{url_for('home')}}",
            clock: new Date(),
            type = 'POST',
            success: function(response){
                console.log(response);
            },
            error: function(error){
                console.log(error);
            }
       });
    });

  </script>

  </head>
  <body>    
    <p>Recording time!</p>

    {% for user in users %}
    <p>{{user.clock}}</p>
    {% endfor %}
  </body>
</html>

这是我的主文件:

import os
from flask import Flask
from flask import render_template
from flask import request
from sqlalchemy import exc
from flask_sqlalchemy import SQLAlchemy


project_dir = os.path.dirname(os.path.abspath(__file__))

#path to the database
database_file = "sqlite:///{}".format(os.path.join(project_dir, "userdatabase.db"))

app = Flask(__name__)

#indicate to the web application where the database will be stored
app.config["SQLALCHEMY_DATABASE_URI"] = database_file

#initialize a connection to the database; use the db variable to interact with the databse
db = SQLAlchemy(app)

##define a model for the user

class User(db.Model):

    user_id = db.Column(db.Integer, primary_key=True)
    user_agent = db.Column(db.String(1024), index=True)
    clock = db.Column(db.String(1024), index=True)

    def __repr__(self):
        return "<User-Agent: {}, Clock: {}".format(self.user_agent, self.clock)

@app.route("/home", methods=["GET", "POST"])
def home():

    if request.method == "POST":

        user_agent_received = request.headers.get('User-Agent')
        clock_received = request.json['clock']
        user = User(user_agent=user-agent_received, clock=clock_received)
        print (user)
        try:
            db.session.add(user)
            db.session.commit()
        except exc.IntegrityError as e:
            db.session().rollback()

        users = User.query.all()

    return render_template("home.html", users=users)



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

我用来创建数据库的命令是:

from main import db

db.create_all()

但是当我运行main.py文件时,出现以下错误:

UnboundLocalError: local variable 'users' referenced before assignment

我看不到控制台内显示任何错误,我相信情况可能是这样的,因为它们在发布AJAX中的数据时出现了一些错误。我是flask的新手,并且主要通过遵循在线教程来创建此代码。任何人都可以帮忙解决这里的问题吗?谢谢!

1 个答案:

答案 0 :(得分:1)

您需要移动代码

users = User.query.all()

街区之外(之前)

if request.method == "POST":

这是因为如果使用request.method == "GET",则未定义变量用户

注意代码

return render_template("home.html", users=users)

仅在当前代码中请求方法不是POST的情况下运行 因此,可以选择缩进该行以在方法为POST时运行(在这种情况下,您可能会得到以下错误:方法为GET时视图未返回响应)