【问题标题】:Dynamic database connection Flask-SQLAlchemy动态数据库连接 Flask-SQLAlchemy
【发布时间】:2017-06-03 07:45:09
【问题描述】:

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

【问题讨论】:

  • 我认为当我启动我的应用程序时它没有任何 request.url 所以可能是..
  • 如果有上述问题,那么哪个.py文件最好连接数据库?
  • 尝试将from .model import Users 放在模块的顶层。
  • 我试过了。这是行不通的。 ):
  • 如果我使用 sqlite 而不是 mysql,该代码对我有用。我怀疑问题是您无法成功连接到数据库。您是否可能错过了Python3 port of pymysql

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


【解决方案1】:

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

  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 的端口上没有其他进程正在运行。

如果以上所有操作都正常,我需要查看一些堆栈跟踪来弄清楚实际发生了什么。

【讨论】:

  • Antonio Haro 感谢您的建议。但它仍然给出错误。
  • 问题是我需要从 url 获取数据库名称,我尝试像这样获取数据库 nane database = request.url.split("/")[2].split(".") [0] 它从这里停止。
猜你喜欢
  • 1970-01-01
  • 2016-08-21
  • 1970-01-01
  • 1970-01-01
  • 2021-11-02
  • 2014-10-26
  • 2018-02-09
  • 2017-07-07
  • 2018-06-13
相关资源
最近更新 更多