Forums

Flask, uWSGI, SQLAlchemy, Postgres, Error running WSGI application

I have a flask web app that uses Postgres and Flask-SQLAlchemy. I also have an always on task that sends a request to the homepage of this web app every 5 minutes. If the web response is anything but 200, it sends me an email. Every day I get at least one email and when I check the logs its an error similar to the following:

2022-08-17 15:30:35,726: Error running WSGI application
2022-08-17 15:30:35,774: sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) SSL error: decryption failed or bad record mac

I've tried various configurations but this is what its currently running.

SQLALCHEMY_ENGINE_OPTIONS = {
    'pool_size': 10,
    'pool_recycle': 270,
    'pool_pre_ping': True
}

In general the web app works great, all the queries are working fine. The only thing I can find is this could be caused by the application forking. I found this StackOverflow link related to setting the uWGSI lazy-apps=True due to multiple processes sharing a connection. But I see on other posts, users cannot modify the uWGSI configuration here.

StackOverflow Link

I'm currently stumped and have no idea how to get this web app to run reliably.

Make sure you're not connecting to and querying the database at import time. That is before the fork. If you make sure that your only database accesses are in your request handlers, then those will be after the fork, so they will not have the issue.

That makes a lot of sense, I suspected the error was caused on the user_loader query which I tried adding a try/except to fix the error. Your suggestion helped me realize I was actually initializing the user_loader before the database connection. I'll update my code so the db is initialized before the user_loader and hopefully that will resolve the issue. Thanks Glenn