I have a bare minimum Flask App which talks to the Cloud SQL Postgres Database. This application works fine when run it from local server and connect to the cloud postgres instance. But I receive 502 Bad Gateway if I run the same code from App Engine.
app.config['TIMEOUT'] = 300 # set timeout to 300 seconds (5 minutes)
# Replace with your actual PostgreSQL database credentials
DB_USER = os.environ.get('CLOUD_SQL_USERNAME')
DB_PASSWORD = os.environ.get('CLOUD_SQL_PASSWORD')
DB_NAME = os.environ.get('CLOUD_SQL_DATABASE_NAME')
DB_HOST = os.environ.get('CLOUD_SQL_CONNECTION_NAME')
# Initialize SQLAlchemy
app.config['SQLALCHEMY_DATABASE_URI'] = f"postgresql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}/{DB_NAME}"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
def init_db():
db.create_all()
@App .route('/')
def index():
return '<a href="{}">Login with GCP</a>'.format(get_login_url())
@App .route('/test-db-connection')
def test_db_connection():
try:
db.session.execute(text('SELECT 1'))
return 'Database connection successful.'
except Exception as e:
return f'Database connection error: {e}'```