Howard S
Howard S

Reputation: 163

uWSGI (PythonAnywhere), Flask, SQLAlchemy, and PostgreSQL: SSL error: decryption failed or bad record mac

I have a Flask application running on PythonAnywhere and a PostgreSQL managed database from DigitalOcean. I'm using Flask-SQLAlchemy to connect to the database.

My app works fine locally when connecting to the remote database. However, the app fails when I run it on PythonAnywhere. I suspect that it's uWSGI's multiple workers that are causing the problem, as described on this Stack Overflow post: uWSGI, Flask, sqlalchemy, and postgres: SSL error: decryption failed or bad record mac

This is the error message that I get

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) SSL error: decryption failed or bad record mac

The error is triggered by a simple Flask-SQLAlchemy method:

user = User.query.get(id)

The other Stack Overflow post provided a solution where I can change the uWSGI's configuration. But in PythonAnywhere, I am unable modify the uWSGI's configuration. Also, disposing the database engine after initializing the app did not resolve the issue. Is there an alternate fix?

Edit 1: I have a paid account.

Upvotes: 1

Views: 878

Answers (1)

Howard S
Howard S

Reputation: 163

Disposing the database engine after initializing the app DID resolve the issue. This is a link to the post that helped me: https://github.com/pallets/flask-sqlalchemy/issues/745#issuecomment-499970525

This is how I fixed it in my code.

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from tms_sola.config import Config  # my custom config object

db = SQLAlchemy()

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)
    app.app_context().push()

    with app.app_context(): 
        db.init_app(app)

        # https://github.com/pallets/flask-sqlalchemy/issues/745#issuecomment-499970525
        db.session.remove()
        db.engine.dispose()

    from tms_sola.blueprints.some_blueprint.routes import some_blueprint

    # https://github.com/pallets/flask-sqlalchemy/issues/745#issuecomment-499970525
    db.session.remove()
    db.engine.dispose()

    return app

Upvotes: 2

Related Questions