[英]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.我正在开发 web 后端,它从数据库文件中读取数据,处理数据并返回 json object。 I am not really informed about flask and the way the variables life in a flask app.
我并不真正了解 flask 以及变量在 flask 应用程序中的生活方式。
As you can see below, i am calling the flaskApp from a wsgi file.正如您在下面看到的,我正在从 wsgi 文件调用 flaskApp。 I created the "get_db()" function according to the flask documentation, but there is no improvement by using this function.
我根据 flask 文档创建了“get_db()”function,但是使用这个 function 没有任何改进。
Is there a way to connect to the database only once and not every time the URL is called?有没有办法只连接一次数据库,而不是每次调用 URL 时?
#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现在您可以访问
cursor
以在所有端点中进行查询
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.