0
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import io
from flask import Flask, render_template, send_file, make_response, request
from gpiozero import LED
import datetime
import gevent
import gevent.monkey
from gevent.pywsgi import WSGIServer

gevent.monkey.patch_all()

app = Flask(__name__)
import sqlite3

conn=sqlite3.connect('../sensorsData.db')
curs=conn.cursor()

led = LED(18)

def ledOn():
  led.blink()
  return "LED has been turned on"

def ledOff():
  led.off()
  return "LED has been turned off"

def ledStatus():
  if led.is_lit:
     return 'On'
  else:
    return 'Off'

@app.route("/readLED/")
def readPin():

   response = ledStatus()

   templateData = {
      'title' : 'Status of LED: ',
      'response' : response
   }

   return render_template('index.html', **templateData)


@app.route("/writeLED/<status>")
def writePin(status):

   if status == 'On':
     response = ledOn()
   else:
     response = ledOff()

   templateData = {
      'title' : 'Status of LED',
      'response' : response
   }

return render_template('index.html', **templateData)

# Retrieve LAST data from database
def getLastData():
    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

def getHistData (numSamples):
    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

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('index.html', **templateData)

@app.route('/plot/temp')
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=8080, debug=False)

Basically, i am trying to run my flask server but always keep getting indentation errors like "File "Server.py", line 90 global numSamples ^ IndentationError: unindent does not match any outer indentation level", what wrong with the code? i dont get whats wrong with that particular line. Would appreciate the help

Jason
  • 27
  • 2
  • You can't keep defining a function after the `return` statement, so Python is expecting that block to be unindented. If it's supposed to be only within the `maxRowsTable` function, move the lines before the `return` statement. – rst-2cv Jun 24 '18 at 08:53
  • 1
    Well, yeah, you've indented that code as though it's part of a function. I'm not going to through all of that code but why are you declaring `global` outside of a function and do you really want global variables in Flask? – roganjosh Jun 24 '18 at 08:53
  • 1
    The indentation is in return of writePin function – khelili miliana Jun 24 '18 at 09:01
  • I tried moving the numSample initializing and declaration line above, now the indentation errors at the return statement of post method – Jason Jun 24 '18 at 09:36
  • 1
    I'm assuming you left the comment unindented? Everything needs to be indented to the same level there. You would probably benefit from taking a step back and understanding why this isn't working because if you brute-force an approach to correct indentation just to get something to run then you're going to get really wonky results in Python. – roganjosh Jun 24 '18 at 09:37
  • 1
    I have marked this as a duplicate of a detailed thread on "Indentation Error". If the instructions there are followed, the error should be resolved. If it is not, a question should note specifically what part of the method described fails and why. – jpp Jun 24 '18 at 09:58

1 Answers1

0

You have to add some spaces to correct the indentation at line 61, 93, 120 and 121:

61: add three spaces before return.
93: add some spaces before numSamples.
120: add a space before }.
121: add a space before return.

You can refer to PEP 8 -- Style Guide for Python Code or to Python coding standards/best practices

Community
  • 1
  • 1
Kenly
  • 24,317
  • 7
  • 44
  • 60