为Flask应用创建sqlite数据库连接 [英] Creating a sqlite database connection for a flask app

查看:134
本文介绍了为Flask应用创建sqlite数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个Web后端,该后端从数据库文件读取,处理数据并返回json对象.我对瓶以及瓶应用中变量的生存方式并没有真正的了解.

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.

正如您在下面看到的,我正在从wsgi文件中调用flaskApp.我根据烧瓶文档创建了"get_db()"函数,但是使用此函数没有任何改善.

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.

有没有一种方法可以仅一次而不是每次调用URL时都连接到数据库?

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)

推荐答案

您可以这样做:

#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

现在,您可以访问 cursor 在所有端点中进行查询

Now you can access cursor to make queries in all endpoints

这篇关于为Flask应用创建sqlite数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆