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?

vonPetrushev
  • 5,457
  • 6
  • 39
  • 51

2 Answers2

64

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.

Mahmoud Abdelkader
  • 23,011
  • 5
  • 41
  • 54
  • Thanks, I'll try this. Though, I wonder if it can be turn of in some sense? – vonPetrushev Mar 16 '11 at 21:05
  • 3
    This is brilliant. Python has everything! – Thomas Dignan Apr 04 '13 at 22:04
  • 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") – ywan Jan 03 '20 at 17:21
  • 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. – ywan Jan 03 '20 at 17:28
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.

zzzeek
  • 72,307
  • 23
  • 193
  • 185
  • 2
    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? – vonPetrushev Mar 16 '11 at 21:10
  • 2
    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). – zzzeek Mar 19 '11 at 14:40
  • 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! – vonPetrushev Mar 19 '11 at 18:42