简体   繁体   中英

Creating a sqlite database connection for a flask app

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM