`查询.count()`sFlask炼金术和多重绑定的悲哀

2024-04-25 03:31:07 发布

您现在位置:Python中文网/ 问答频道 /正文

摘要

我在使用多重绑定烧瓶SQLAlchemy时遇到了麻烦。尤其是,查询对象上的count()方法似乎不起作用。在

细节

我的Flask应用程序在PostgreSQL数据库上工作。此外,它还从MySQL上运行的旧的Simple Machines Forum安装中检索数据。在

为了方便使用,我对MySQL数据库使用第二个Flask SQLAlchemy绑定,并通过反射设置类。查询通常可以正常工作,但是使用count()会产生一个sqlalchemy.exc.ProgrammingError,相应的表将不存在。在

代码

myapp/app.py

from flask import Flask

class Config(object):
    SQLALCHEMY_DATABASE_URI = 'postgres://localhost/igor'
    SQLALCHEMY_BINDS = {
        'smf': 'mysql://myuser:mypass@localhost/my_db',
    }

app = Flask('myapp')
app.config.from_object(Config)

myapp/model.py

^{pr2}$

示例(错误堆栈跟踪中的文件路径为易读而缩短):

% python
Python 2.7.6 (default, Dec  2 2013, 11:07:48)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from myapp.model import Topics
>>> len(Topics.query.all())
10162
>>> Topics.query.count()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "…/sqlalchemy/orm/query.py", line 2573, in count
    return self.from_self(col).scalar()
  File "…/sqlalchemy/orm/query.py", line 2379, in scalar
    ret = self.one()
  File "…/sqlalchemy/orm/query.py", line 2348, in one
    ret = list(self)
  File "…/sqlalchemy/orm/query.py", line 2391, in __iter__
    return self._execute_and_instances(context)
  File "…/sqlalchemy/orm/query.py", line 2406, in _execute_and_instances
    result = conn.execute(querycontext.statement, self._params)
  File "…/sqlalchemy/engine/base.py", line 717, in execute
    return meth(self, multiparams, params)
  File "…/sqlalchemy/sql/elements.py", line 317, in _execute_on_connection
    return connection._execute_clauseelement(self, multiparams, params)
  File "…/sqlalchemy/engine/base.py", line 814, in _execute_clauseelement
    compiled_sql, distilled_params
  File "…/sqlalchemy/engine/base.py", line 927, in _execute_context
    context)
  File "…/sqlalchemy/engine/base.py", line 1076, in _handle_dbapi_exception
    exc_info
  File "…/sqlalchemy/util/compat.py", line 185, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb)
  File "…/sqlalchemy/engine/base.py", line 920, in _execute_context
    context)
  File "…/sqlalchemy/engine/default.py", line 425, in do_execute
    cursor.execute(statement, parameters)
sqlalchemy.exc.ProgrammingError: (ProgrammingError) relation "smf_topics" does not exist
LINE 3: FROM smf_topics) AS anon_1
             ^
 'SELECT count(*) AS count_1 \nFROM (SELECT smf_topics.id_topic AS smf_topics_id_topic, […] \nFROM smf_topics) AS anon_1' {}

在后一种情况下,该语句显然是针对主PostgreSQL绑定而不是MySQL绑定运行的。(这可以通过在连接的PostgreSQL数据库中创建smf_topics表来轻松证明。)

在创建类时,我还尝试在创建类时提供__tablename__属性(也可以代替)__table__属性,但是没有用。在

我想我错过了一些重要的东西。不幸的是,时间限制禁止将论坛迁移到PostgreSQL。感谢任何帮助。在

更新(2015年2月23日)

下面是一个重现错误的最小示例。使用count()与另一个绑定上的常规模型类一起使用,请参见class Topic(db.Model)-工作。在

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy import MetaData

# Application setup
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://localhost/igor'
app.config['SQLALCHEMY_BINDS'] = {
    'smf': 'mysql://myuser:mypass@localhost/my_db',
}
db = SQLAlchemy(app)

# Database reflection
smf_meta = MetaData(bind=db.get_engine(app, bind='smf'))
smf_meta.reflect()
topic_class = type(db.Model)('Topic', (db.Model,), {
    '__bind_key__': 'smf',
    '__tablename__': 'smf_topics',
    '__table__': smf_meta.tables['smf_topics'],
})

# Conventional model class
class Topic(db.Model):
    __bind_key__ = 'smf'
    __tablename__ = 'smf_topics'
    id_topic = db.Column(db.Integer, primary_key=True)
    num_replies = db.Column(db.Integer, nullable=False, default=0)

# Run it
if __name__ == '__main__':
    print('1. {}'.format(Topic.query.count()))
    print('2. {}'.format(len(topic_class.query.all())))
    print('3. {}'.format(topic_class.query.count()))

以及运行脚本时的输出:

1. 10400
2. 10400
Traceback (most recent call last):
  File "./test.py", line 35, in <module>
    print('3. {}'.format(topic_class.query.count()))
  File "…/sqlalchemy/orm/query.py", line 2640, in count
    return self.from_self(col).scalar()
  File "…/sqlalchemy/orm/query.py", line 2426, in scalar
    ret = self.one()
  File "…/sqlalchemy/orm/query.py", line 2395, in one
    ret = list(self)
  File "…/sqlalchemy/orm/query.py", line 2438, in __iter__
    return self._execute_and_instances(context)
  File "…/sqlalchemy/orm/query.py", line 2453, in _execute_and_instances
    result = conn.execute(querycontext.statement, self._params)
  File "…/sqlalchemy/engine/base.py", line 729, in execute
    return meth(self, multiparams, params)
  File "…/sqlalchemy/sql/elements.py", line 322, in _execute_on_connection
    return connection._execute_clauseelement(self, multiparams, params)
  File "…/sqlalchemy/engine/base.py", line 826, in _execute_clauseelement
    compiled_sql, distilled_params
  File "…/sqlalchemy/engine/base.py", line 958, in _execute_context
    context)
  File "…/sqlalchemy/engine/base.py", line 1159, in _handle_dbapi_exception
    exc_info
  File "…/sqlalchemy/util/compat.py", line 199, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb)
  File "…/sqlalchemy/engine/base.py", line 951, in _execute_context
    context)
  File "…/sqlalchemy/engine/default.py", line 436, in do_execute
    cursor.execute(statement, parameters)
sqlalchemy.exc.ProgrammingError: (ProgrammingError) relation "smf_topics" does not exist
LINE 3: FROM smf_topics) AS anon_1
             ^
 'SELECT count(*) AS count_1 \nFROM (SELECT smf_topics.id_topic AS smf_topics_id_topic, […] \nFROM smf_topics) AS anon_1' {}

Tags: infrompyselfexecutedbsqlalchemycount
1条回答
网友
1楼 · 发布于 2024-04-25 03:31:07

下面是它的工作原理。^^关键是使用db.reflect(),然后提供db.Model.metadata作为新创建的类的元数据:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://localhost/igor'
app.config['SQLALCHEMY_BINDS'] = {
    'smf': 'mysql://myuser:mypass@localhost/my_db',
}
db = SQLAlchemy(app)
db.reflect(bind='smf', app=app)
topic_class = type(db.Model)('Topic', (db.Model,), {
    '__bind_key__': 'smf',
    '__table__': db.Model.metadata.tables['smf_topics'],
    '__tablename__': 'smf_topics',
    '__module__': __name__,
    'metadata': db.Model.metadata,
})

if __name__ == '__main__':
    print('1. {}'.format(len(topic_class.query.all())))
    print('2. {}'.format(topic_class.query.count()))

相关问题 更多 >