0

I am working on a web back-end which reads from a database file, processes the data and returns a json object. I am not really informed about flask and the way the variables life in a flask app.

As you can see below, i am calling the flaskApp from a wsgi file. I created the "get_db()" function according to the flask documentation, but there is no improvement by using this function.

Is there a way to connect to the database only once and not every time the URL is called?

#file flaskApp.py
#!/usr/bin/env python3.6
from flask import Flask
...

def get_db():
    if 'db' not in g:
        g.db = sqlite3.connect("database.db")
    return g.db

app = Flask(__name__)

@app.route('/getResourceUsage/<string:buildingNumber>')
def getResource(buildingNumber):
    cursor = get_db().cursor()

    cursor.execute("SELECT * FROM room WHERE building='" + buildingNumber + "'")
    ...
    return json
#file wsgi.py
#!/usr/bin/env python3.6

from flaskApp import app

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=40800)

1 Answer 1

1

You can do it like this:

#file flaskApp.py
#!/usr/bin/env python3.6
from flask import Flask
...


app = Flask(__name__)

g.db = sqlite3.connect("database.db")
cursor = get_db().cursor()

@app.route('/getResourceUsage/<string:buildingNumber>')
def getResource(buildingNumber):
    cursor.execute("SELECT * FROM room WHERE building='" + buildingNumber + "'")
    ...
    return json

Now you can access cursor to make queries in all endpoints

Sign up to request clarification or add additional context in comments.

2 Comments

And this will not recreate a new database connection on every url call?
No. It will create just one

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.