我正在嘗試使用 Flask-SQLAlchemy 及其綁定功能創(chuàng)建多個(gè)數(shù)據(jù)庫。使用創(chuàng)建單個(gè)數(shù)據(jù)庫SQLALCHEMY_DATABASE_URI效果很好。但是,當(dāng)我添加時(shí),SQLALCHEMY_BINDS它失敗并出現(xiàn)以下錯(cuò)誤:File "/usr/local/lib/python3.7/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync)sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) FATAL: database "customer1" does not exist這是我的config.py文件:class BaseConfig: """Base configuration""" SECRET_KEY = 'random_key' SQLALCHEMY_TRACK_MODIFICATIONS = False TESTING = Falseclass DevelopmentConfig(BaseConfig): """Development configuration""" SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') SQLALCHEMY_BINDS = { 'customer1': 'postgres://postgres:postgres@auth-db:5432/customer1' }這是我的init .py文件db = SQLAlchemy()migrate = Migrate()def create_app(): # instantiate app app = Flask(__name__) app_settings = os.getenv('APP_SETTINGS') app.config.from_object(app_settings) db.init_app(app) migrate.init_app(app, db) from project.api.auth import auth_blueprint app.register_blueprint(auth_blueprint) @app.shell_context_processor def ctx(): return { 'app': app, 'db': db } return app我正在通過命令行通過管理.py文件創(chuàng)建數(shù)據(jù)庫:@cli.command('recreate_db')def recreate_db(): db.drop_all() db.create_all() try: db.session.commit() except exc.SQLAlchemyError as e: logging.info(f'{e}')我正在創(chuàng)建一個(gè)多租戶應(yīng)用程序,并且我嘗試創(chuàng)建的模型應(yīng)該在兩個(gè)數(shù)據(jù)庫中創(chuàng)建;我的model.py文件是這樣的:class Widgets(db.Model): __tablename__ = 'widgets' id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(100), nullable=False, unique=True) create_date = db.Column(db.DateTime, default=datetime.datetime.utcnow)我到處尋找答案,找到了幾個(gè)答案,但即使在嘗試了所有答案之后,我仍然收到此錯(cuò)誤。我錯(cuò)過了什么嗎?Flask-migrate 也不起作用,但我懷疑我需要先修復(fù)這個(gè)錯(cuò)誤。任何幫助,將不勝感激。
1 回答

侃侃無極
TA貢獻(xiàn)2051條經(jīng)驗(yàn) 獲得超10個(gè)贊
db.drop_all()
并且db.create_all()
只刪除并創(chuàng)建所有表。(https://docs.sqlalchemy.org/en/13/core/metadata.html#sqlalchemy.schema.MetaData.create_all)
如果您想創(chuàng)建數(shù)據(jù)庫(customer1),您應(yīng)該使用 sqlalchemy-utils。下面的鏈接是用法。
如何使用 SQLAlchemy 創(chuàng)建新數(shù)據(jù)庫?
添加回答
舉報(bào)
0/150
提交
取消