티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
Debugging (displaying) SQL command sent to the db by SQLAlchemy
SQLAlchemy를 사용하여 db에 전송된 SQL 명령을 디버깅(출력)하는 방법
문제 내용
I have an ORM class called Person, which wraps around a person table:
Person ORM 클래스가 person 테이블을 감싸고 있습니다.
After setting up the connection to the db etc, I run the statement:
db와의 연결을 설정한 후 다음 명령을 실행합니다.
people = session.query(Person).all()
The person table does not contain any data (as yet), so when I print the variable people
, I get an empty list.
person 테이블에는 아직 데이터가 없기 때문에 변수 people을 출력하면 빈 목록이 표시됩니다.
I renamed the table referred to in my ORM class People
, to people_foo
(which does not exist).
ORM 클래스에서 참조하는 테이블 이름을 People에서 people_foo로 변경했습니다. 그러나 해당 테이블은 존재하지 않습니다.
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:
그래서 다음 두 가지 질문이 있습니다.
- How may I setup SQLAlchemy so that it propagates db errors back to the script?
- How may I view (i.e. print) the SQL that is being sent to the db engine?
1. SQLAlchemy를 어떻게 설정하여 db 오류를 스크립트로 전파할 수 있을까요?
2. db 엔진으로 전송되는 SQL을 어떻게 볼 수 있을까요?
If it helps, I am using PostgreSQL.
도움이 된다면, PostgreSQL을 사용하고 있습니다.
[Edit]
[편집]
I am writing a package. In my __main__.py
script, I have the following code (shortened here):
패키지를 작성하고 있습니다. main.py 스크립트에서 다음 코드가 있습니다 (여기서는 축소했습니다).
### __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)
[Edit2]
[편집2]
Common module sets the logger up correctly, and I can use the logger in my other modules that import common.
Common 모듈에서 로거를 올바르게 설정하고, common을 가져오는 다른 모듈에서 로거를 사용할 수 있습니다.
However in dbfuncs
module, I am getting the following error/warning:
그러나 dbfuncs 모듈에서 다음 오류/경고가 발생합니다.
No handlers could be found for logger "sqlalchemy.engine.base.Engine
"sqlalchemy.engine.base.Engine" 로거에 핸들러를 찾을 수 없습니다.
높은 점수를 받은 Solution
In addition to echo
parameter of create_engine()
there is a more flexible way: configuring logging
to echo engine statements:
create_engine()의 echo 매개변수 외에도 더 유연한 방법이 있습니다: 로깅을 구성하여 engine 문을 echo합니다.
import logging
logging.basicConfig()
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
See Configuring Logging section of documentation for more information.
자세한 내용은 문서의 로깅 구성 섹션을 참조하세요.
출처 : https://stackoverflow.com/questions/2950385/debugging-displaying-sql-command-sent-to-the-db-by-sqlalchemy
'개발 > 파이썬' 카테고리의 다른 글
파이썬에서 리스트(list)와 튜플(tuple)을 사용하는 각각의 경우 고찰 (0) | 2023.02.21 |
---|---|
두 개의 딕셔너리를 비교하고 (key, value) 쌍이 얼마나 일치하는지 확인하기 (0) | 2023.02.20 |
파이썬 판다스에서 데이터프레임을 두 개 이상의 열(column)로 정렬하기 (0) | 2023.02.20 |
groupby를 사용하여 그룹 내에서 최대 값을 가진 행을 가져오는 방법 (0) | 2023.02.20 |
Windows에서 tkinter를 pip 또는 easy_install로 설치하기 (0) | 2023.02.19 |