Setting a global DB connection in Google App Engine

Question:

Are there suggested ways to set a global connection in Google App Engine? The approach I am currently using seems a bit crude, and I’m doing it like this:

import pymysql
from flask import Flask, jsonify

# lazy loading?
db_conn = None
db_cursor = None

def get_db():
    global db_conn, db_cursor
    if (db_conn, db_cursor) == (None, None):
        global_conn = pymysql.connect(user="x", password="y", database="z", host="w", charset='utf8')
        global_cursor = conn.cursor()
    return (db_conn, db_cursor)

app = Flask(__name__)

@app.route('/')
def hello():
    return jsonify(hello='world')

@app.route('/db')
def db():
    conn, cursor = get_db()
    cursor.execute("SELECT * FROM mytable LIMIT 50")
    res = cursor.fetchall()
    return res
Asked By: David542

||

Answers:

It’s not bad. However, if you always need your Database connection in your instance, soon or later, you can directly start your db connection at runtime

import pymysql
from flask import Flask, jsonify

# eager loading?
db_conn = pymysql.connect(user="x", password="y", database="z", host="w", charset='utf8')
db_cursor = db_conn.cursor()

app = Flask(__name__)
...

The code is simpler, but it will impact your startup time. No worries if you need DB connection at a time. But can be bad if many of your endpoints don’t need DB access. it’s up to you, as always, it depends!

Answered By: guillaume blaquiere
  1. Because DB connections can be dropped for one reason or the other, Google recommends using a connection pool for connecting to DBs (see documentation).

  2. They also have a worked example for a global connection which is part of a connection pool. In the linked example, you will note that they included comments to invoke the connection as soon as your App is loaded instead of when a request is first made

Answered By: NoCommandLine