BAE BAE - 1 month ago 5
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/routes.py, 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'])
@crossdomain(origin="*")
def funnel(para1):
# codes using cassandra Connection

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


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

if __name__ == '__main__':
# Connect db connection
app.run(host='0.0.0.0', port=8080, debug=True)

BAE BAE
Answer

The following codes seem work. But any comments welcomed.

myblueprint.py

from flask import Blueprint

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

myview.py

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

app.py

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

    #SETUP RESOURCE AND START SERVER
    app.run(host='0.0.0.0', port=5000, debug=True)
Comments