Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use after_request in flask to close database connection and python?

How to use after_request decorator to close a connection after the request is processed? I use the before_request for opening the connection for each api request as follows: Using sqlalchemy core 1.0.8 and postgresql 9.5:

#engine = create_engine(os.environ.get("DB_URL"))
DB_URL="postgresql://mowner:passwd@localhost/mydb"

@app.before_request
def before_request():
    engine = create_engine(DB_URL, strategy='threadlocal')
    conn = engine.connect()


@app.after_request
def after_request(conn):
     if conn is not None:
         print 'closing connection'
         conn.close()

sample api call:

@app.route('/api/v1.0/categories', methods=['GET'])
def categories_list():
    '''
    Return categories list
    '''
    if 'id' in session:
        categories_list = []
        s = select([categories])
        rs = conn.execute(s)
        if rs.rowcount > 0:
            for r in rs:
                categories_list.append(dict(r))
            rs.close()
        # print 'this doesnt execute'
        return jsonify({'categories list': categories_list}), 200

    return jsonify({'message': "UNAUTHORIZED"}), 401

The views are api calls which only return a list of objects, added, or edit object and a message. How exactly to pass the connection object to the after_request decorator? I couldn't really follow the documentation Exact code will help me.

like image 623
user956424 Avatar asked Dec 29 '17 10:12

user956424


People also ask

How do you close a database connection in python?

To disconnect Database connection, use close() method. If the connection to a database is closed by the user with the close() method, any outstanding transactions are rolled back by the DB.

How does Python connect to database 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).

How can we request database connection in Flask?

To preserve the database connection within the same flask session you may use the application context and assign database connection. If the connection breaks,the context will try to establish the connection back as it polls the connection object continuously.

How do you use a database with a Flask?

Step 1 - Install the Flask-SQLAlchemy extension. Step 2 - You need to import the SQLAlchemy class from this module. Step 3 - Now create a Flask application object and set the URI for the database to use. Step 4 - then use the application object as a parameter to create an object of class SQLAlchemy.


1 Answers

You can use flask.g to refer to create a global db connection object and use it everywhere

from flask import Flask, g

#engine = create_engine(os.environ.get("DB_URL"))
DB_URL="postgresql://mowner:passwd@localhost/mydb"

@app.before_request
def before_request():
   engine = create_engine(DB_URL, strategy='threadlocal')
   conn = engine.connect()
   g.db = conn

Then use connection in your route like this

@app.route('/api/v1.0/categories', methods=['GET'])
def categories_list():
    '''
    Return categories list
    '''
    if 'id' in session:
        categories_list = []
        s = select([categories])
        rs = g.db.execute(s) # change in variable
        if rs.rowcount > 0:
           for r in rs:
             categories_list.append(dict(r))
        rs.close()
        # print 'this doesnt execute'
       return jsonify({'categories list': categories_list}), 200
    return jsonify({'message': "UNAUTHORIZED"}), 401

Then finally close it like this:

@app.after_request
def after_request(response):
    if g.db is not None:
        print 'closing connection'
        g.db.close()
     return response
like image 180
Sohaib Farooqi Avatar answered Sep 28 '22 00:09

Sohaib Farooqi