Arithmetic calculations (sum) in the Flask-Sqlalchemy database

Asked

Viewed 146 times

0

I have a table in my database that the user places the total flight hours he has done. I wanted to know how to add all the hours of the user who is in the database and show in templates.

inserir a descrição da imagem aqui

Backend:

from flask import Flask, render_template, flash, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired 

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db = SQLAlchemy(app)
app.config['SECRET_KEY'] = 'askdjrw83845gkdksjs1234jdjsyqerdsdfkgji9547djfh4'

class MyForm(FlaskForm):
  username = StringField('Nome', validators=[DataRequired()])
  horas = StringField('Horas de Voo', validators=[DataRequired()])

class Horas(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  username = db.Column(db.String(120))
  hora = db.Column(db.String(10))

db.create_all()

@app.route('/', methods=['GET', 'POST'])
def index():
  posts = Horas.query.all()
  form = MyForm()
  if form.validate_on_submit():
    post = Horas(username=form.username.data, hora=form.horas.data)
    db.session.add(post)
    db.session.commit()
    flash("valor Registrador")
    return redirect(url_for('index'))
  return render_template('index.html', form=form, posts=posts)

if __name__ == '__main__':
  app.run(host='0.0.0.0', port='3000')

Frontend:

<html>
  <head>
    <style>
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
</style>
<
  </head>
  <body>
    <form method="POST" action="/">
    {{ form.hidden_tag() }}
    <p>{{ form.username.label }} {{ form.username(size=20) }}</p>
    <p>{{ form.horas.label }} {{ form.horas(size=5) }}</p>
    <input type="submit" value="Enviar">
</form>
<hr>
<br>
<table>
  <tr>
    <th>Nome</th>
    <th>Horas</th>
  </tr>
  {% for posts in posts %}
  <tr>  
    <td>{{ posts.username }}</td>
    <td>{{ posts.hora }}</td>
  </tr>

  {% endfor %}

  </body>

</html>
  • 1

    You save as string, then just separate each value in the character :, sum up all hours, sum up all minutes and turn over minutes into hours by dividing and catching the rest of the split by 60. Want to try?

1 answer

0

You can use datetime.timedelta for this

from datetime import timedelta
hh = 0
mm = 0
for post in posts:
    h, m = post.hora.split(':')
    hh += int(h)
    mm += int(m)
hora = timedelta(hours=hh) + timedelta(minutes=mm)
print(hora)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.