首页 文章

动态数据库连接Flask-SQLAlchemy

提问于
浏览
7

我需要连接两个数据库 . 默认数据库是固定的,但另一个是动态的,它基于URL .

例如,如果url是:yourapp.myweb.com那么第二个数据库名称将是 yourapp

我尝试将数据库连接到 init .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.

这是我的 init .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:root@localhost/main_database"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SQLALCHEMY_BINDS'] = {
    'user_db': 'mysql+pymysql://root:root@localhost/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

1 回答

  • 3

    正如我在其中一条评论中所说,这可能是数据库连接的问题 . 这是我要检查的内容:

    • 首先,确保在您的虚拟环境中安装了正确的引擎(您可以通过运行 pip list 轻松检查;以防万一,让我坚持要求库需要安装在virtual environment中) . 确保你没有 pymysql ,而是Python3的端口,名为mysqlclient . pymysql 仅适用于Python2 . 要安装此库,您需要先安装Python和MySQL开发头 . 例如,在Debian / Ubuntu中:
    sudo apt-get install python-dev libmysqlclient-dev
    

    然后,您可以使用以下命令安装库:

    pip install mysqlclient
    
    • 如果已安装,请确保您可以使用库实际连接到数据库 . 在虚拟环境中打开Python shell并键入以下内容(来自github中的示例):
    import pymysql.cursors
    
    connection = pymysql.connect(host='<you_host>',
                                 user='<user>',
                                 password='<password>',
                                 db='<database_name>',
                                 charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor)
    
    try:
        with connection.cursor() as cursor:
            do_something()
    except:
        pass
    
    • 如果一切正常,请确保您运行的是最新烧瓶版本(0.12 at the moment;这一次,你可以通过运行 pip list 检查),因为有与在已固定的一段时间调试模式下运行瓶的几个错误 .

    • 这肯定不是这种情况,但另一个健全性检查是验证您要用于Flask的端口上没有运行其他进程 .

    如果上述所有方法都正常工作,我需要看一下堆栈跟踪以找出实际发生的情况 .

相关问题