Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-SQLAlchemy check if database server is responsive

I am using flask-SQLAlchemy for my webservice. I would like to have an endpoint that checks status of the utilized MySQL database availability/responsiveness. How would I go about it? Thanks.

Here are relevant pieces of my code:

mywebsvc.py

...
app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://mylogin:mypw@localhost/mydb'

db.init_app(app)
...

models_shared.py

from flask.ext.sqlalchemy import SQLAlchemy

db = SQLAlchemy()

models.py

from models_shared import db

class Car(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    make = db.Column(db.String(64), index=True, unique=True)
    color = db.Column(db.String(64), index=False, unique=False)

routes.py

...
@app.route('/is_available', methods=['GET'])
def is_available():
    #???
like image 670
jazzblue Avatar asked May 18 '15 15:05

jazzblue


People also ask

How do I check my database connection in Flask?

In any directory where you feel comfortable create a folder and open the command line in the directory. Create a python virtual environment using the command below. Once the command is done running activate the virtual environment using the command below. Now, install Flask using pip(package installer for python).

What does db Create_all () do?

Creating and Dropping Database Tables create_all() creates foreign key constraints between tables usually inline with the table definition itself, and for this reason it also generates the tables in order of their dependency.

How do you use Flask-SQLAlchemy to interact with databases in a Flask application?

You then create a Flask application instance called app , which you use to configure two Flask-SQLAlchemy configuration keys: SQLALCHEMY_DATABASE_URI : The database URI to specify the database you want to establish a connection with. In this case, the URI follows the format sqlite:/// path/to/database. db .

What is difference between Flask-SQLAlchemy and SQLAlchemy?

One of which is that Flask-SQLAlchemy has its own API. This adds complexity by having its different methods for ORM queries and models separate from the SQLAlchemy API. Another disadvantage is that Flask-SQLAlchemy makes using the database outside of a Flask context difficult.


1 Answers

There is a fancy library for writing end-point checking condition of the service - healthcheck.

It's useful for asserting that your dependencies are up and running and your application can respond to HTTP requests. The Healthcheck functions are exposed via a user defined flask route so you can use an external monitoring application (Monit, Nagios, Runscope, etc.) to check the status and uptime of your application.

You can use it instead of manually creating end-point because there are some features out of the box (for example EnvironmentDump).

In my application, I had the same need so I implemented check if database is responsive

app = Flask(__name__)

# wrap the flask app and give a heathcheck url
health = HealthCheck(app, "/healthcheck")

def health_database_status():
    is_database_working = True
    output = 'database is ok'

    try:
        # to check database we will execute raw query
        session = DatabaseSession.get_database_session()
        session.execute('SELECT 1')
    except Exception as e:
        output = str(e)
        is_database_working = False

    return is_database_working, output

health.add_check(health_database_status)

As I see, in your application you can execute query with db.engine.execute('SELECT 1').

like image 157
Piotr Dawidiuk Avatar answered Sep 21 '22 09:09

Piotr Dawidiuk