BAE BAE - 10 months ago 49
Python Question

re-structure Flask routes which share common open db connection

I am trying to re-factor and re-structure my routes into views/, but all these routes are using one common open cassandra connection. open means that the cassandra connection will be connected when starting server and will stay open during the server running. The connected connection will be used by all routes. I am thinking about blueprints. But how to re-factor and re-structure my codes?

app = Flask(__name__)
dbConnection = None

@app.route('/api/v1/<para1>', methods=['GET', 'OPTIONS'])
def funnel(para1):
# codes using cassandra Connection

@app.route('/api/v1/xxx/<para2>', methods=['GET', 'OPTIONS'])
def funnel(para2):
# codes using cassandra Connection

@app.route('/api/v1/yyy/<para3>', methods=['GET', 'OPTIONS'])
def funnel(para3):
# codes using cassandra Connection

if __name__ == '__main__':
# Connect db connection'', port=8080, debug=True)

Answer Source

The following codes seem work. But any comments welcomed.

from flask import Blueprint

class MyBlueprint(Blueprint):
    dbconnection = None
    def setDb( self, db ):
        self.dbconnection = db

my_api = MyBlueprint('my_api', __name__ )
@my_api.route('/api/v1/yyy/<para3>', methods=['GET', 'OPTIONS'])
def myapi(para3):
    # codes using funnel_api.dbconnection

app = Flask(__name__)
cassandraConnection = None
if __name__ == '__main__':
    my_api.setDb( cassandraConnection )
    app.register_blueprint( my_api )

    #SETUP RESOURCE AND START SERVER'', port=5000, debug=True)