'Python Flask SQLAlchemy check if database is available

before rendering the template I want to check if the database that I am using is available. The database is only available with specific IP, therefore, if someone tries to access the page, I don't want to error everything out, but redirect to a different template without the need for a database.

The error message:

(2003, "Can't connect to MySQL server on 'db-test' (110)")
(Background on this error at: https://sqlalche.me/e/14/e3q8)

There is no issue with the error itself, I just want to be able to check if the database is accessible without waiting until the error occurs while loading the page.

storage.py:

from flask_sqlalchemy import SQLAlchemy

db_req = SQLAlchemy()


class Requests(db_req.Model):
    __tablename__ = 'requests'
    id = db_req.Column(db_req.Integer, primary_key=True, nullable=False)
    created = db_req.Column(db_req.DateTime, nullable=False)
    name = db_req.Column(db_req.String, nullable=False)

app.py:

from flask import Flask
from models import db_req
from views.requests import requests

app = Flask(__name__)
app.register_blueprint(requests)
app.config.from_object("config.Config")
db_req.init_app(app)

if __name__ == '__main__':
    app.run(debug=True)

requests.py:

from flask import Blueprint, render_template, request
from query_request_db import get_fields

requests = Blueprint("requests", __name__)


@requests.route("/", methods=["GET", "POST"])
def requests_page():
    # need to check before everything if I can access database not to error out
  return render_template("requests_page.html", names=get_fields.get_field_data("name"))

I am trying to find a way to check if the database is available without erroring out. Any help is welcome!



Solution 1:[1]

Hope I understand you right? that u want to check ip Addresse of the viewer of your Page.

Then u can use

request.remote_addr

to validate the IP Adress that has access to database ohterwise just do a redirect.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Christoph