动态数据库连接Flask-SQLAlchemy

时间:2017-06-03 07:45:09

标签: python-3.x flask sqlalchemy flask-sqlalchemy

我需要连接两个数据库。默认数据库是固定的,但另一个是动态的,它基于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 个答案:

答案 0 :(得分:3)

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

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

    sudo apt-get install python-dev libmysqlclient-dev
    

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

    pip install mysqlclient
    
  2. 如果已安装,请确保您可以使用库实际连接到数据库。在虚拟环境中打开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
    
  3. 如果这样做,请确保您正在运行最新版本的Flask(0.12 at the moment;这可以通过运行pip list再次检查),因为有几个错误与在DEBUG模式下运行Flask有关,已经修复了一段时间。

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

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