Turn off a warning in sqlalchemy
Asked Answered
K

2

39

I'm using sqlalchemy with reflection, a couple of partial indices in my DB make it dump warnings like this:

SAWarning: Predicate of partial index i_some_index ignored during reflection

into my logs and keep cluttering. It does not hinder my application behavior. I would like to keep these warnings while developing, but not at production level. Does anyone know how to turn this off?

Koo answered 7/3, 2011 at 22:0 Comment(0)
C
67

Python's warning module provides a handy context manager that catches warnings for you.

Here's how to filter out the SQLAlchemy warning.

import warnings
from sqlalchemy import exc as sa_exc

with warnings.catch_warnings():
    warnings.simplefilter("ignore", category=sa_exc.SAWarning)
    # code here...

As for development vs production, you can just have this warning wrap around your application's entry point or an external script that invokes your application in your production environment.

Usually, I solve this by having an environment variable that executes a slightly different code path than when developing, for example, wrapping around different middleware etc.

Cutlip answered 7/3, 2011 at 22:17 Comment(4)
Thanks, I'll try this. Though, I wonder if it can be turn of in some sense?Koo
This is brilliant. Python has everything!Microwatt
It doesn't work for me. The warning still pops up: usr/local/lib/python3.5/dist-packages/pymysql/cursors.py:170: Warning: (1364, "Field 'external_id' doesn't have a default value")Inherited
I figured out my issue. It's not a "sa_exc.SAWarning". I just need to remove the category, then the warning can be suppressed.Inherited
P
14

the warning means you did a table or metadata reflection, and it's reading in postgresql indexes that have some complex condition which the SQLAlchemy reflection code doesn't know what to do with. This is a harmless warning, as whether or not indexes are reflected doesn't affect the operation of the application, unless you wanted to re-emit CREATE statements for those tables/indexes on another database.

Pasto answered 16/3, 2011 at 20:5 Comment(3)
Thanks. I know they're harmless, my application works very good. But each time the daemon restarts, these warnings are sent to my apache error log and they clutter. Is there a way to actually turn off index reflection all-together?Koo
I think the suggestion to tune your warnings filter at the start is a good idea here. We do this via warnings for this purpose. There's no option for the index reflection right now (though not terribly hard to implement).Pasto
OK, I'll go with the answer above, probably catch the warnings in the part where I do the reflection. The index reflection is really no significant overhead, so I wouldn't give it much effort :) Thanks a lot!Koo

© 2022 - 2024 — McMap. All rights reserved.