'Locking thread and creating new cursors not resolving sqlite3 "recursive use of cursors not allowed"
I am trying to make a simple flask web server that presents two graphs of data using matplotlib from a DHT22 sensor stored in a sqlite3 database. The code is based on that written by MRovai with a few changes (namely to resolve threading error messages):
https://medium.com/@rovai/from-data-to-graph-a-web-jorney-with-flask-and-sqlite-6c2ec9c0ad0
I assume there have been some changes to sqlite3 as I consistently receive "sqlite3.ProgrammingError: Recursive use of cursors not allowed" that obviously did not occur in MRovai's script.
I understand that sqlite 3 disallows sharing connections and cursors between threads have tried creating new cursors as well as locking as per:
Python and sqlite3.ProgrammingError: Recursive use of cursors not allowed
What I do not understand is how to correctly create a new cursor or lock for my particular code. Other examples elsewhere seem to be so different from my code as to not be comparable e.g.
Recursive query with ordered values in SQLite Android
My code is below with attempts at locking the thread and creating a new cursor commented out to show what I have been trying.
Any help or hints greatly appreciated.
from matplotlib.figure import Figure
import io
from flask import Flask, render_template, send_file, make_response, request
app = Flask(__name__)
import sqlite3
#import threading
conn=sqlite3.connect('/home/pi/Documents/Sensors_Database/sensorsData.db', check_same_thread=False)
#conn2=sqlite3.connect('/home/pi/Documents/Sensors_Database/sensorsData.db', check_same_thread=False)
curs=conn.cursor()
#curs2=conn2.cursor()
#lock=threading.Lock()
# Retrieve LAST data from database
def getLastData():
#lock.acquire(True)
for row in curs.execute("SELECT * FROM DHT_data ORDER BY timestamp DESC LIMIT 1"):
time = str(row[0])
temp = row[1]
hum = row[2]
# conn.close()
return time, temp, hum
#lock.release()
def getHistData (numSamples):
#lock.acquire(True)
curs.execute("SELECT * FROM DHT_data ORDER BY timestamp DESC LIMIT "+str(numSamples))
data = curs.fetchall()
dates = []
temps = []
hums = []
for row in reversed(data):
dates.append(row[0])
temps.append(row[1])
hums.append(row[2])
return dates, temps, hums
#lock.release(True)
def maxRowsTable():
for row in curs.execute("select COUNT(temp) from DHT_data"):
maxNumberRows=row[0]
return maxNumberRows
# define and initialize global variables
global numSamples
numSamples = maxRowsTable()
if (numSamples > 101):
numSamples = 100
# main route
@app.route("/")
def index():
time, temp, hum = getLastData()
templateData = {
'time' : time,
'temp' : temp,
'hum' : hum,
'numSamples' : numSamples
}
return render_template('index.html', **templateData)
@app.route('/', methods=['POST'])
def my_form_post():
global numSamples
numSamples = int (request.form['numSamples'])
numMaxSamples = maxRowsTable()
if (numSamples > numMaxSamples):
numSamples = (numMaxSamples-1)
time, temp, hum = getLastData()
templateData = {
'time' : time,
'temp' : temp,
'hum' : hum,
'numSamples' : numSamples
}
return render_template('./templates/index.html', **templateData)
def plot_temp():
times, temps, hums = getHistData(numSamples)
ys = temps
fig = Figure()
axis = fig.add_subplot(1, 1, 1)
axis.set_title("Temperature [°C]")
axis.set_xlabel("Samples")
axis.grid(True)
xs = range(numSamples)
axis.plot(xs, ys)
canvas = FigureCanvas(fig)
output = io.BytesIO()
canvas.print_png(output)
response = make_response(output.getvalue())
response.mimetype = 'image/png'
return response
@app.route('/plot/hum')
def plot_hum():
times, temps, hums = getHistData(numSamples)
ys = hums
fig = Figure()
axis = fig.add_subplot(1, 1, 1)
axis.set_title("Humidity [%]")
axis.set_xlabel("Samples")
axis.grid(True)
xs = range(numSamples)
axis.plot(xs, ys)
canvas = FigureCanvas(fig)
output = io.BytesIO()
canvas.print_png(output)
response = make_response(output.getvalue())
response.mimetype = 'image/png'
return response
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, debug=False)'''
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|