Creating a sqlite database connection for a flask app

百般思念 提交于 2021-01-29 10:20:08

问题


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:


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



来源:https://stackoverflow.com/questions/58876713/creating-a-sqlite-database-connection-for-a-flask-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!