0

I have sadly come into an issue with flask, blueprints, and restful with using a global db connection with mysql. How on earth does the blueprints resource get the global db conn? So if I define a global conn to python.connector then how can I use a database with blueprints? I dont see a way to pass my db conn to a blueprint.

Note, I do not and cannot use flask mysql ext etc. It must be a pure conn from python connector since I use fabric.

Here is my main code:

# views.py 
from flask import Blueprint
from flask_restful import Api
from resources.register import register
from app import app 

db = "This is my global mysql conn"


api_bp = Blueprint('api', __name__)
api = Api(api_bp)
api.add_resource(register, '/api/driver/register')
app.register_blueprint(api_bp)

Here is my resource:

from flask_restful import Resource
from flask import  request, jsonify

class register(Resource):
def post(self):
    data = request.json
    partner_ref = data['ref']
    partner_driver_ref = data['\driver_ref']
    query = """INSERT INTO %s (partner_ref,partner_driver_ref) VALUES ('%s','%s')""" % (ref,driver_ref)
    db.execute_query(query,select=False,table=None,key=None)
    status = {'status':'OK'}
    return jsonify(status)
Tampa
  • 75,446
  • 119
  • 278
  • 425

1 Answers1

0

How about putting the database connection in the g object?

@api_bp.before_app_request
def connect_db():
    if not hasattr(g, 'db'):
        g.db = db

@api_bp.teardown_app_context
def close_db():
    if hasattr(g, 'db'):
        # close your db connection here.

And when you want to use it, just use g.db.execute_query(...)

lord63. j
  • 4,500
  • 2
  • 22
  • 30