我有以下Python代码
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://my_user_name:@localhost:5432/my_db'
db = SQLAlchemy(app)
@app.route("/submit_signup_email", methods=["POST"])
def submit_signup_email():
email = request.form["email"]
created_timestamp = int(time.time())
signup = Signup(email, created_timestamp)
db.session.add(signup)
db.session.commit()
# not working...
test = Signup.query.filter_by(email=email).first()
哪个工作正常,我可以检查我的数据库中是否正确插入了一行。
但如果我在“db.session.commit()”.....
之后运行此代码test = Signup.query.filter_by(email=email).first()
我收到以下错误。
OperationalError:(OperationalError)无法连接到服务器:否 此类文件或目录服务器是否在本地运行并接受 Unix域套接字“/var/pgsql_socket/.s.PGSQL.5432”上的连接?
我不确定问题是什么,我的注册模型在“models.py”中看起来像这样
from flask_sqlalchemy import SQLAlchemy
from app import app, db
class Signup(db.Model):
__tablename__ = "signups"
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String)
created_timestamp = db.Column(db.Integer)
def __init__(self, email, created_timestamp):
self.email = email
self.created_timestamp = created_timestamp
def __repr__(self):
return self.email
答案 0 :(得分:0)
db = SQLAlchemy()
db.init_app(APP)
db.app = app
init_app(app):
此回调可用于初始化应用程序以供此数据库设置使用。切勿在未以该方式初始化的应用程序的上下文中使用数据库,否则连接将泄漏。
和“来自app import app,db”不正确
答案 1 :(得分:-1)