调试(显示)SQLAlchemy 发送到数据库的 SQL 命令 [英] Debugging (displaying) SQL command sent to the db by SQLAlchemy
问题描述
我有一个名为 Person 的 ORM 类,它环绕一个人表:
I have an ORM class called Person, which wraps around a person table:
建立与数据库等的连接后,我运行语句:
After setting up the connection to the db etc, I run the statement:
people = session.query(Person).all()
person 表不包含任何数据(到目前为止),所以当我打印变量 people
时,我得到一个空列表.
The person table does not contain any data (as yet), so when I print the variable people
, I get an empty list.
我将 ORM 类 People
中引用的表重命名为 people_foo
(不存在).
I renamed the table referred to in my ORM class People
, to people_foo
(which does not exist).
然后我再次运行脚本.我很惊讶在尝试访问不存在的表时没有抛出异常.
I then run the script again. I was surprised that no exception was thrown when attempting to access a table that does not exist.
因此我有以下两个问题:
I therefore have the following 2 questions:
- 如何设置 SQLAlchemy 以便将数据库错误传播回脚本?
- 如何查看(即打印)发送到数据库引擎的 SQL?
如果有帮助,我正在使用 PostgreSQL.
If it helps, I am using PostgreSQL.
我正在写一个包.在我的 __main__.py
脚本中,我有以下代码(此处缩短):
I am writing a package. In my __main__.py
script, I have the following code (shortened here):
### __main__.py
import common # imports logging and defines logging setup funcs etc
logger = logging.getLogger(__name__)
def main():
parser = OptionParser(usage="%prog [options] <commands>",
version="%prog 1.0")
commands = OptionGroup(parser, "commands")
parser.add_option(
"-l",
"--logfile",
dest="logfile",
metavar="FILE",
help="log to FILE. if not set, no logging will be done"
)
parser.add_option(
"--level",
dest="loglevel",
metavar="LOG LEVEL",
help="Debug level. if not set, level will default to low"
)
# Set defaults if not specified
if not options.loglevel:
loglevel = 1
else:
loglevel = options.loglevel
if not options.logfile:
logfilename = 'datafeed.log'
else:
logfilename = options.logfile
common.setup_logger(False, logfilename, loglevel)
# and so on ...
#### dbfuncs.py
import logging
# not sure how to 'bind' to the logger in __main__.py
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
engine = create_engine('postgres://postgres:pwd@localhost:port/dbname', echo=True)
Common 模块正确设置了记录器,我可以在导入 common 的其他模块中使用记录器.
Common module sets the logger up correctly, and I can use the logger in my other modules that import common.
但是在 dbfuncs
模块中,我收到以下错误/警告:
However in dbfuncs
module, I am getting the following error/warning:
找不到记录器sqlalchemy.engine.base.Engine"的处理程序
No handlers could be found for logger "sqlalchemy.engine.base.Engine
推荐答案
除了 create_engine()
的 echo
参数之外,还有一种更灵活的方式:配置 logging
以回显引擎语句:
In addition to echo
parameter of create_engine()
there is a more flexible way: configuring logging
to echo engine statements:
import logging
logging.basicConfig()
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
请参阅文档的配置日志记录部分了解更多信息信息.
See Configuring Logging section of documentation for more information.
这篇关于调试(显示)SQLAlchemy 发送到数据库的 SQL 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!