我正在尝试将我的第一个Flask应用程序与SQLAlchemy和PostGreSQL连接,但是遇到了以下错误。
UserWarning: Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. Defaulting SQLALCHEMY_DATABASE_URI to "sqlite:///:memory:".
'Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. '
经过几个小时的调试(可能很简单),我用光了所有选项。从错误来看,问题似乎出在SQLAlCHEMY_DATABASE_URI的变量上,但不是100%肯定。我尝试了localhost
和localhost:5000`,但是出现了相同的错误。
在SO中阅读其他答案,我看到有些时候在db = SQLAlchemy(app)
之后定义配置时会遇到此问题,但是我的代码中却没有这样的问题。任何线索都将不胜感激。
from flask import Flask, request, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.update(
SECRET_KEY='rafadbpw',
SQLAlCHEMY_DATABASE_URI='postgresql://postgres:rafadbpw@localhost:5000/catalog_db',
SQLALCHEMY_TRACK_MODIFICATIONS=False
)
db = SQLAlchemy(app)
@app.route('/index')
@app.route('/')
def hello_flask():
return "Hello Flask!"
class Publication(db.Model):
__tablename__ = 'publication'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
def __init__(self,id,name):
self.id = id
self.name = name
def __repr__(self):
return 'The id is {}, name is {}'.format(self.id, self.name)
if __name__ == '__main__':
db.create_all()
app.run(debug=True)