Commit 37a02320 authored by Nelso Jost's avatar Nelso Jost

FIX: Makefile usage, board routes, missing files

parent db1fa7d9
logs/
.venv/
.tag*
*.swp
*.autosave
*.sqlite
*.pyc
datalog.csv
outgoing.json
*.log
.pid_gunicorn
.gunicorn.conf.py
__pycache__
......@@ -11,13 +11,12 @@ help:
@ echo " debreq apt-get install Debian-based system dependencies"
@ echo " venv create local Python virtualenv with PYBIN variable"
@ echo ""
@ echo " mysql-setup create MySQL user ctaemm and emmdb (not tables)"
@ echo " mysql-info return MySQL info: users, dbs and emmdb usage"
@ echo " mysql-chroot change MySQL root password"
@ echo " mysql-enter starts MySQL interactive session as root"
@ echo " mysql-schema shows the database schema"
@ echo " mysql-init create MySQL user and DB (not tables)"
@ echo " mysql-summary shows all current users and DBs"
@ echo " mysql-describe show current DB schema"
@ echo " mysql-reset allows root password reset"
@ echo ""
@ echo " dbinit recreate database from scratch (drop data) and populate it"
@ echo " dbinit recreate DB schema (drop data if exists) and populate it"
@ echo " shell start ipython3 interactively for high level DB admin"
@ echo ""
@ echo " run start Flask's development server at"
......@@ -67,21 +66,24 @@ tree:
mysql-init:
${VENVPY} production/manage_mysql.py init
mysql-getinfo:
${VENVPY} production/manage_mysql.py getinfo
mysql-user:
${VENVPY} production/manage_mysql.py user
mysql-showschema:
${VENVPY} production/manage_mysql.py showschema
mysql-resetroot:
sudo dpkg-reconfigure mysql-server-5.5
mysql-summary:
${VENVPY} production/manage_mysql.py summary
mysql-describe:
chmod +x production/mysql_describe.sh && ./production/mysql_describe.sh
mysql-showschema:
${VENVPY} production/manage_mysql.py showschema
mysql-enter:
mysql -uroot -p
mysql-reset:
sudo dpkg-reconfigure mysql-server-5.5
gunicorn:
cd production/nginx-gunicorn && ${VENVDIR}/bin/gunicorn wsgi:app
......
......@@ -14,7 +14,8 @@ from flask.ext.login import current_user
from pprint import pprint
__all__ = ['BoardSelectForm', 'BoardManageForm', 'SensorListItemForm',
__all__ = ['BoardSelectForm', 'BoardInsertForm', 'SensorListItemForm',
'BoardManageForm',
'MyFileField', 'ImportCSVForm', 'ExportCSVForm']
......@@ -77,6 +78,13 @@ class BoardManageForm(Form):
board_userhash = MyStringField('Hash (utilizado para autenticar na API)',
htmlattr={'readonly': True, 'style': 'width: 150%'})
def __init__(self, board):
super().__init__()
self.board_userhash.data = board._userhash
class BoardInsertForm(Form):
board_nickname = MyStringField('Apelido', validators=[
Required("Preenchimento obrigatório!"),
Length(3, 20, "Deve possuir entre 3 e 20 caracteres!")],
......@@ -96,19 +104,11 @@ class BoardManageForm(Form):
board_longitude = MyStringField('Lon', htmlattr={'readonly': True})
board_description = TextAreaField('Descrição')
def __init__(self, board=None):
def __init__(self):
super().__init__()
if request.method == 'POST':
self.sensors = self.gather_request_sensors()
if board != None:
self.board_userhash.data = board._userhash
self.board_nickname.data = board.nickname
self.board_description.data = board.description
self.board_exposition.data = board.exposition.name
self.board_longitude.data = board.longitude
self.board_latitude.data = board.latitude
else:
self.sensors = [Sensor.get(name=sensor_name).dump(
include=['measurement_name', 'unity_label'])
......@@ -121,9 +121,7 @@ class BoardManageForm(Form):
def validate_and_save(self):
try:
print('Trying to validate new board')
if self.validate():
print('Validated!')
r = request.form
kwargs = {k.replace('board_', ''): v
for k, v in request.form.items()
......@@ -131,13 +129,10 @@ class BoardManageForm(Form):
kwargs['sensors'] = [s['name'] for s in
self.gather_request_sensors()]
kwargs['user_id'] = current_user.id
print('gather sensors: ', kwargs['sensors'])
b = Board.add(**kwargs)
db.session.commit()
print('new board:', b)
return b
except Exception as e:
print('validation exception:', e)
db.session.rollback()
def gather_request_sensors(self):
......@@ -176,9 +171,6 @@ class MyFileField(FileInput):
def __call__(self, field, **kwargs):
#~ class="filestyle" data-buttonName="btn-primary"
#~ data-buttonText=" Escolher "
kwargs['class'] = 'filestyle'
kwargs['data-buttonName'] = 'btn-primary'
kwargs['data-buttonText'] = ' Escolher '
......
......@@ -75,17 +75,17 @@ def sensor(id, sensor_nickname):
board_select_form = BoardSelectForm(selected_id=b.id))
@board.route('/manage/<int:id>', methods=['GET', 'POST'])
@board.route('/insert', methods=['GET', 'POST'])
@login_required
def manage(id):
''' GET: --> templates/manageboard.html
POST: --> cancel procedure; save board; add/remove sensors
def insert():
''' GET --> templates/insertboard.html
POST | btn_cancel --> main.index
| btn_save --> main.view_board (new board)
'''
b = Board.query.get_or_404(id)
board_manage_form = BoardManageForm(board=b)
board_insert_form = BoardInsertForm()
if request.method == 'POST':
# pprint(request.form)
pprint(request.form)
# got any button click? if so, the btn will appear on the request.form
if 'btn_cancel' in request.form:
return redirect(url_for('main.index'))
......@@ -97,34 +97,24 @@ def manage(id):
mu_map = json.dumps({m.name: m.unities for m in measurements.ls})
return render_template('board/manage.html', board_form=board_manage_form,
return render_template('board/insert.html', board_form=board_insert_form,
mu_map=mu_map, sensor_form=SensorListItemForm())
@board.route('/insert', methods=['GET', 'POST'])
@login_required
def insert():
''' GET --> templates/insertboard.html
POST | btn_cancel --> main.index
| btn_save --> main.view_board (new board)
@board.route('/manage/<int:id>', methods=['GET', 'POST'])
def manage(id):
''' GET --> board_main.html
'''
board_manage_form = BoardManageForm()
b = Board.query.get_or_404(id)
board_manage_form = BoardManageForm(board=b)
if request.method == 'POST':
pprint(request.form)
# got any button click? if so, the btn will appear on the request.form
if 'btn_cancel' in request.form:
return redirect(url_for('main.index'))
elif 'btn_save' in request.form:
board = board_manage_form.validate_and_save()
if board:
return redirect(url_for('board.main', id=board.id))
return BoardSelectForm.handle_post(b)
mu_map = json.dumps({m.name: m.unities for m in measurements.ls})
return render_template('board/manage.html', board=b,
board_select_form=BoardSelectForm(selected_id=b.id),
board_form=board_manage_form)
return render_template('board/insert.html', board_form=board_manage_form,
mu_map=mu_map, sensor_form=SensorListItemForm())
@board.route('/clean/<int:id>')
......
This diff is collapsed.
......@@ -38,21 +38,16 @@ class DBInitCommand(Command):
Sensor.import_from_json(*db_init['SENSORS'])
Board.add(nickname='Pezzi', user=user_admin,
longitude='-51.11948668956755',
latitude='-30.072849663041758',
Board.add(nickname='PezziProto', user=user_admin,
longitude='-51.098163127899156',
latitude='-30.085322758845493',
exposition='outdoor', default_sensors=True)
Board.add(nickname='CAP', user=user_admin,
longitude='-51.12238079309464',
latitude='-30.07583926435496',
exposition='indoor', default_sensors=True)
db.session.commit()
CSV_FILENAME = path_here('data/26-Fev-2013_-_04-Mar-2013.log')
print('\nImporting data from:\n {}'.format(CSV_FILENAME))
boards.get(nickname = 'Pezzi').import_csv_sensor_data(
boards.get(nickname = 'PezziProto').import_csv_sensor_data(
filename=CSV_FILENAME, sep='\t', debug=True)
print('Writing changes on the disc..', end='')
......
......@@ -61,6 +61,7 @@ class Board(db.Model, BaseMixin):
last_data = self.rawdata.order_by(RawSensorData.datetime.desc())\
.first()
d['data'] = last_data.json if last_data else None
d['board_url'] = url_for('board.main', id=self.id)
d['sensors'] = []
for bs in self.sensors:
s = bs.json
......
......@@ -21,8 +21,8 @@ class Sensor(db.Model, BaseMixin):
def __repr__(self):
return "<Sensor id={} name='{}' measurement='{}' unity='{}'>"\
.format(self.id, self.name, self.measurement.name,
self.unity.label)
.format(self.id, self.name, self.measurement_name,
self.unity_label)
@property
def measurement_name(self):
......
......@@ -61,16 +61,15 @@
session['current_board']['user_id'] == current_user.id %}
<li><a href="#">Importar dados</a></li>
<li role="separator" class="divider"></li>
<li><a href={{ url_for('board.manage', id=session['current_board']['id']) }}
>Gerenciar</a></li>
<li><a href={{ url_for('board.manage', id=session['current_board']['id']) }}>Gerenciar</a></li>
{% endif %}
</ul>
</li>
{% endif %}
{% if current_user.is_authenticated() %}
{% if current_user.is_authenticated() %}
<li><a href={{ url_for('board.insert') }}
>Cadastrar Estação</a></li>
{% endif %}
{% endif %}
</ul>
<ul class="nav navbar-nav navbar-right">
......
......@@ -21,7 +21,9 @@
{{ super() }}
<!-- http://www.tutorialrepublic.com/codelab.php?topic=bootstrap&file=create-dynamic-tabs-via-javascript
-->
<div class="bs-example">
<ul class="nav nav-tabs" id="myTab">
<!--
<li class="active"><a href="#sectionB">Log</a></li>
......
{% extends "base.html" %}
{% block styles %}
{{ super() }}
<link rel="stylesheet" href="{{url_for('static', filename='css/ol.css')}}" type="text/css"/>
<link rel="stylesheet" href="{{url_for('static', filename='css/popup.css')}}" type="text/css"/>
<!-- <link rel="stylesheet" href="{{url_for('static', filename='css/font-awesome.min.css')}}" type="text/css"/> -->
<!-- <link rel="stylesheet" href="{{url_for('static', filename='css/validationEngine.jquery.css')}}" type="text/css"/> -->
{% endblock %}
{% block scripts %}
{{ super() }}
<script src="http://openlayers.org/en/v3.13.1/build/ol.js" type="text/javascript"></script>
<script src="{{ url_for('static', filename='js/validator.js') }}"></script>
<!-- <script src="{{ url_for('static', filename='js/jquery.validate.min.js') }}"></script> -->
<!-- <script src="{{ url_for('static', filename='js/messages_pt_BR.js') }}"></script> -->
<!-- <script src="{{ url_for('static', filename='js/jquery.validationEngine.js') }}"></script> -->
<!-- <script src="{{ url_for('static', filename='js/jquery.validationEngine-pt_BR.js') }}"></script> -->
<script language="javascript">
var mu_map = {{ mu_map|safe }};
var sensors = {{ board_form.sensors|safe }};
var $nickname = $($.parseHTML(
'{{ sensor_form.nickname(class="form-control") }}')[0]);
var $measurement_name = $($.parseHTML(
'{{ sensor_form.measurement_name(class="form-control") }}')[0]);
var $unity_label = $($.parseHTML(
'{{ sensor_form.unity_label(class="form-control") }}')[0]);
var $description = $($.parseHTML(
'{{ sensor_form.description(class="form-control") }}')[0]);
</script>
<script src="{{ url_for('static', filename='js/mapinsert.js') }}"></script>
<script src="{{ url_for('static', filename='js/managesensors.js') }}"></script>
<script src="{{ url_for('static', filename='js/validateboard.js') }}"></script>
{% endblock %}
{% block content %}
<div class="container">
<h2>Cadastrar Estação</h2><hr>
<h2>Gerenciar Estação</h2><hr>
<div style="position: relative; top=-50px;">
<form id="board_form" role="form" method='POST' class="form-horizontal"
enctype=multipart/form-data data-toggle="validator"
......@@ -57,117 +17,6 @@
{{ board_form.board_userhash(class="form-control") }}
</div>
</div>
<div class="form-group
{% if board_form.board_nickname.errors %}has-error{% endif %}">
{{ board_form.board_nickname.label(class="col-xs-3 control-label") }}
<div class="col-xs-5 selectContainer">
{{ board_form.board_nickname(class="form-control", autofocus=True) }}
<!-- <span class="glyphicon form-control-feedback" aria-hidden="true"></span> -->
<div class="help-block with-errors"></div>
<!-- server-side validation results -->
{% if board_form.board_nickname.errors %}
<p class="help-block"> {{ board_form.board_nickname.errors|join(', ') }} </p>
{% endif %}
</div>
</div>
<div class="form-group">
{{ board_form.board_description.label(class="col-xs-3 control-label") }}
<div class="col-xs-5 selectContainer">
{{ board_form.board_description(class="form-control") }}
</div>
</div>
<div class="form-group
{% if board_form.board_exposition.errors %}has-error{% endif %}">
{{ board_form.board_exposition.label(class="col-xs-3 control-label") }}
<div class="col-xs-5 selectContainer">
{{ board_form.board_exposition(class="form-control", style="width: 30%") }}
<!-- <span class="glyphicon form-control-feedback" aria-hidden="true"></span> -->
<div class="help-block with-errors"></div>
{% if board_form.board_exposition.errors %}
<p class="help-block">{{ board_form.board_exposition.errors|join(', ') }}</p>
{% endif %}
</div>
</div>
<div class="form-group {% if board_form.board_latitude.errors %}has-error
{% endif %}">
<label class="col-xs-3 control-label">Localização </label>
<div class="col-xs-5 selectContainer">
{% if board_form.board_latitude.errors %}
<p class="help-block">
{{ board_form.board_latitude.errors|join(', ') }}</p>
{% endif %}
<div id="map" class="map"></div>
<!-- <div id="popup" class="ol-popup"> -->
<!-- <a href="#" id="popup-closer" class="ol-popup-closer"></a> -->
<!-- <div id="popup-content"></div> -->
<!-- </div> -->
<div class="row">
<div class="col-xs-1">
{{ board_form.board_longitude.label(class="control-label") }}
</div>
<div class="col-xs-5 ">
{{ board_form.board_longitude(class="form-control") }}
</div>
<div class="col-xs-1 ">
{{ board_form.board_latitude.label(class="control-label") }}
</div>
<div class="col-xs-5 ">
{{ board_form.board_latitude(class="form-control") }}
</div>
</div>
</div>
</div>
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Sensores</h3>
</div>
<table class="table table-striped" id="table_sensors">
<thead>
<tr>
<th>Apelido</th>
<th>Medição</th>
<th>Unidade</th>
<th>Descrição</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div class="panel-body">
<button type="button" name="btn_add_sensor"
class="btn btn-default"
onclick="add_sensor_row()">
<span class="glyphicon glyphicon-plus" ></span>
</button>
</div>
</div>
<div class="form-group">
<div class="col-xs-5 submitContainer">
<button type="submit" method="POST" name="btn_save"
class="btn btn-default btn-lg">
<span class="glyphicon glyphicon-floppy-disk" ></span> Salvar
</button>
<button type="submit" method="POST" name="btn_cancel"
class="btn btn-default btn-lg">
<span class="glyphicon glyphicon-remove-sign" ></span> Cancelar
</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
......
......@@ -14,32 +14,27 @@ EMMDBNAME = cp['db']['name']
EMMDBUSER = cp['db']['user']
EMMDBPASS = cp['db'].get('pass') or cp['app']['pass']
SCRIPT_SETUP_USER =\
SCRIPT_USER =\
"""\
#DROP USER '{EMMDBUSER}'@'localhost';
CREATE USER '{EMMDBUSER}'@'localhost' IDENTIFIED BY '{EMMDBPASS}';
"""
SCRIPT_DB_INIT =\
SCRIPT_INIT =\
"""\
CREATE DATABASE IF NOT EXISTS {EMMDBNAME}
CHARACTER SET utf8 COLLATE utf8_bin;
GRANT ALL on {EMMDBNAME}.* TO '{EMMDBUSER}'@'localhost'
IDENTIFIED BY '{EMMDBPASS}';
IDENTIFIED BY '{EMMDBPASS}' WITH GRANT OPTION;
FLUSH PRIVILEGES;
"""
SCRIPT_GET_INFO =\
SCRIPT_SUMMARY =\
"""\
SELECT User, Host FROM mysql.user;
SHOW DATABASES;
SELECT table_schema {EMMDBNAME},
sum( data_length + index_length ) / 1024 / 1024 "Data Base Size in MB",
sum( data_free )/ 1024 / 1024 "Free Space in MB"
FROM information_schema.TABLES
GROUP BY table_schema ;
"""
SHSCRIPT_SHOW_SCHEMA =\
......@@ -78,10 +73,13 @@ def exec_mysql_script(script):
if len(sys.argv) > 1:
if sys.argv[1] == 'init':
exec_mysql_script(SCRIPT_SETUP_USER + SCRIPT_DB_INIT)
exec_mysql_script(SCRIPT_INIT)
elif sys.argv[1] == 'getinfo':
exec_mysql_script(SCRIPT_GET_INFO)
elif sys.argv[1] == 'user':
exec_mysql_script(SCRIPT_USER)
elif sys.argv[1] == 'summary':
exec_mysql_script(SCRIPT_SUMMARY)
elif sys.argv[1] == 'showschema':
sysexec(SHSCRIPT_SHOW_SCHEMA)
......
File mode changed from 100644 to 100755
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment