[英]Getting an Internal 500 error with flask/python/sqlalchemy in reading/displaying data
The code runs fine in flask, until I add the code to return data using sqlalchemy from the database and display it using the corresponding tag in the html section.代码在 flask 中运行良好,直到我添加代码以使用数据库中的 sqlalchemy 返回数据并使用 html 部分中的相应标签显示它。 The error in pycharm is stating that:UnboundLocalError: local variable 'unames' referenced before assignment.
pycharm 中的错误说明:UnboundLocalError: local variable 'unames' referenced before assignment。 I'm not sure that I can reference the tags as global?
我不确定我可以将标签引用为全局标签吗? Am I missing something obvious?
我错过了一些明显的东西吗?
This is a proof of concept to show that data from mysql can be returned and displayed using flask for a small project.这是一个概念证明,表明可以使用 flask 为小型项目返回和显示来自 mysql 的数据。
this is the app.py这是app.py
import os
from flask import Flask
from flask import render_template
from flask import request
from flask_sqlalchemy import SQLAlchemy
project_dir = os.path.dirname(os.path.abspath(__file__))
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = 'mysql://username:password@localhost:3306/database'
db = SQLAlchemy(app)
class Users(db.Model):
uname = db.Column(db.String(80), unique=True, nullable=False, primary_key=True)
def __repr__(self):
return "<uname: {}>".format(self.uname)
@app.route("/", methods=["GET", "POST"])
def home():
if request.form:
users = Users(uname=request.form.get("uname"))
db.session.add(users)
db.session.commit()
unames = Users.query.all()
return render_template("home.html", unames=unames)
if __name__ == "__main__":
app.run(debug=True)'
This is the home.html code:这是家html代码:
<h1>UserNames:</h1>
{% for uname in unames %}
<p>{{Users.uname}}</p>
{% endfor %}
Expected results should be displaying 2 usernames that are in the uname column from the Users table.预期结果应显示用户表中 unname 列中的 2 个用户名。
There is a mistake in the HTML HTML 有错误
<p>{{Users.uname}}</p>
You are referencing to Users.uname
instead it should refer to the loop variable uname.uname
您引用的是
Users.uname
而不是它应该引用循环变量uname.uname
<h1>UserNames:</h1>
{% for user in unames %}
<p>{{user.uname}}</p>
{% endfor %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.