[Flask] Data Logger with flask

Andreas Dorfner andreas.dorfner at stud.hs-regensburg.de
Mon Apr 18 09:11:43 EDT 2016


Hi all,

I would like to realize a data logger for energy meter ALE3 with a 
beaglebone black running debian on it (for datasheet see link below).
After an initialization time of 30 sec. for the ALE3 module, the 
framework pymodbus is used to read data from the energy meter (refresh 
time for new data is 10 sec.) and display it on the therminal.

Ok, that part is still working with the following code (code without 
initialization).

time.sleep(30) #communication is ready 30 sec. after power on

while 1:
     val = client.connect()
     if not val:
             print "Error in Client Connection"
     rcv_data = client.read_holding_registers(35, count = 17, unit = 1) 
#read registers 36 to 52 and save it in rcv_data
     print("Registers are")
     for i in range (17):
         print(rcv_data.registers[i])
     client.close()
     time.sleep(10) #refresh time for the data of the energy meter is 10 
sec.

Next, I would like to save that data in a database and create a website 
to edit the informations as a graph or a diagram.
For that, I will use flask, but I'm not sure if flask is the right 
framework for this project?

Does someone have experience with the implementation of a data logger 
using flask or does anybody knows another framework which better fits to 
my project?

Is it possible to run the webserver for the website and the Pymodbus 
code in the same Python-File or is it a problem because of the while 
infinite loop? Maybe it's better to split it to two separate files, one 
for read data and save it in a database; the second one for the 
webserver. But how can I link that two files, because I think they have 
to run simultaneously.

I'm a newbie in python and flask, so hopefully you have a lot of 
informations and suggestions for me and my project.
All I did with flask is the tutorial (see also attachment).
http://flask.pocoo.org/docs/0.10/tutorial/#tutorial

Maybe I can use some parts of that tutorial and save the data of the 
energy meter in the database I have initiazized there?

Thanks in anticipation for all your help!

Andreas


Datasheet energy meter ALE3:
http://www.meterbuy.com/fileadmin/user_upload/Data_sheets/120102_SAIA_-_Data_sheet_26-527_EN_DS_Energy-Meter-ALE3-with-Modbus.pdf


---
Diese E-Mail wurde von Avast Antivirus-Software auf Viren geprüft.
https://www.avast.com/antivirus
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/flask/attachments/20160418/c4827bd5/attachment.html>
-------------- next part --------------
#all the imports
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, \
     abort, render_template, flash
from contextlib import closing

# configuration
DATABASE = '/tmp/flaskr.db'
DEBUG = True
SECRET_KEY = 'development key'
USERNAME = 'admin'
PASSWORD = 'default'
#---------------------------------------------------------------------------

# create my little application :)
app = Flask(__name__)
app.config.from_object(__name__)
#---------------------------------------------------------------------------

#connects to the specific database
def connect_db():
   return sqlite3.connect(app.config['DATABASE'])
#---------------------------------------------------------------------------

#initializes the database
def init_db():
   with closing(connect_db()) as db:
        with app.open_resource('schema.sql', mode='r') as f:
            db.cursor().executescript(f.read())
        db.commit()
#---------------------------------------------------------------------------

#open the database before each request
@app.before_request
def before_request():
    g.db = connect_db()
#---------------------------------------------------------------------------

#shut down the database afterwards
@app.teardown_request
def teardown_request(exception):
    db = getattr(g, 'db', None)
    if db is not None:
        db.close()
#---------------------------------------------------------------------------

#That function pass the entries as dicts to the show_entries.html template
#and return the broadcasted one.
@app.route('/')
def show_entries():
    cur = g.db.execute('select title, text from entries order by id desc')
    entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]
    return render_template('show_entries.html', entries=entries)
#---------------------------------------------------------------------------

#This view lets the user add new entries if he is logged in. There is a check 
#if the user is logged in as well.
@app.route('/add', methods=['POST'])
def add_entry():
    if not session.get('logged_in'):
        abort(401)
    g.db.execute('insert into entries (title, text) values (?, ?)',
                 [request.form['title'], request.form['text']])
    g.db.commit()
    flash('New entry was successfully posted')
    return redirect(url_for('show_entries'))
#---------------------------------------------------------------------------
	
#---------------------------------------------------------------------------
# The following two functions are used to sign the user in and out. Login
# checks the username and password against the ones from the configuration 
# above and sets the logged_in key in the session. Logout remove that key 
# from the session.
#---------------------------------------------------------------------------

#Login function
@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['username'] != app.config['USERNAME']:
            error = 'Invalid username'
        elif request.form['password'] != app.config['PASSWORD']:
            error = 'Invalid password'
        else:
            session['logged_in'] = True
            flash('You were logged in')
            return redirect(url_for('show_entries'))
    return render_template('login.html', error=error)
#---------------------------------------------------------------------------

#Logout function
@app.route('/logout')
def logout():
    session.pop('logged_in', None)
    flash('You were logged out')
    return redirect(url_for('show_entries'))
#---------------------------------------------------------------------------

#Run the file as a standalone application on IP address 192.168.7.2 (BBB)
#at Port 5000
if __name__ == '__main__':
	app.run(host = '192.168.7.2')
#---------------------------------------------------------------------------


More information about the Flask mailing list