我需要連接兩個數據庫。默認數據庫是固定的,但另一個是動態的,它基於URL。動態數據庫連接Flask-SQLAlchemy
例如,如果網址是:yourapp.myweb.com然後第二個數據庫的名字將是yourapp
我嘗試連接到數據庫初始化的.py但它告訴我下面的錯誤
builtins.AssertionError
AssertionError: A setup function was called after the first request was handled. This usually indicates a bug in the application where a module was not imported and decorators or other functionality was called too late.
To fix this make sure to import all your view modules, database models and everything related at a central place before the application starts serving requests.
這裏是我的初始化的.py
from flask import Flask,session
from flask_sqlalchemy import SQLAlchemy
import os
app = Flask(__name__,static_url_path='/static')
# Database Connection
database = request.url.split("/")[2].split(".")[0]
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://root:[email protected]/main_database"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SQLALCHEMY_BINDS'] = {
'user_db': 'mysql+pymysql://root:[email protected]/database_'+str(database), #dynamic Connection
}
db = SQLAlchemy(app)
db.create_all()
db.create_all(bind=['user_db'])
# db.init_app(app)
from . import views
這裏是viwe.py
@app.route('/login', methods = ['GET'])
def index():
try:
from .model import Users
# Some Code
except Exception as e:
raise e
# return "Failed to login ! Please try again."
這裏是model.py
from application import db
class Users(db.Model):
__bind_key__ = 'user_db'
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key = True)
email = db.Column(db.String(50))
name = db.Column(db.String(50))
password = db.Column(db.String())
def __repr__(self):
return '<User %r>' % self.name
我認爲當我開始我的應用程序它沒有任何request.url因此可能是.. –
如果有上述問題,然後哪個.py文件最好連接數據庫? –
嘗試將'from .model import Users'放在模塊的頂層。 – Fian