我正在使用烧瓶记录高度的 Udemy 课程。我现在正在使用 PostgreSQL,我安装了它,并且准确地复制了他的代码:
from flask import Flask, render_template, request
from flask.ext.sqlalchemy import SQLAlchemy
app=Flask(__name__)
app.config(['SQLALCHEMY_DATABASE_URI']='postgresql://postgres:password
@localhost/height_collector')
db=SQLAlchemy(app)
class Data(db.Model):
__tablename__='data'
id=db.Column(db.Integer, primary_key=True)
email_=db.Column(db.String(120), unique=True)
height_=db.Column(db.Integer)
def __init__(self, email_, height_):
self.email_=email_
self.height_=height_
@app.route("/")
def index():
return render_template("index.html")
@app.route("/success", methods=["post"])
def success():
if request.method=='POST':
email=request.form['email_name']
height=request.form['height_name']
print(height,email)
return render_template("success.html")
if __name__=='__main__':
app.debug=True
app.run()
问题来了,当他说在虚拟环境中运行 python,然后输入 :db.create_all() 在 PostgreSQL 中创建数据库时,我得到了这个错误:File <‘stdin’>, line 1 in NameError: Name ‘db’ 未定义
不确定如何进行,任何输入将不胜感激。
原文由 user8341748 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以制作一个 db.py,您可以在其中存储代码
db = SQLAlchemy()
。然后在app.py中导入。现在你可以调用 db.或者只是删除APP
在db=SQLAlchemy(app)