from itertools import cycle from tracemalloc import start from flask import ( Blueprint, flash, g, redirect, render_template, request, url_for ) from werkzeug.exceptions import abort import pendulum # from flaskr.auth import login_required from period.db import get_db bp = Blueprint('cycles', __name__) @bp.route('/') def index(): db = get_db() cycles = db.execute( 'SELECT id, start_time, end_time, cycle_length' ' FROM cycle ORDER BY start_time DESC' ).fetchall() return render_template('cycle/index.html', cycles=cycles) @bp.route('/create', methods=('GET', 'POST')) def create(): if request.method == 'POST': start_time = pendulum.from_format(request.form['start_time'], 'YYYY-MM-DD') # start_time = start_time.to_datetime_string() try: end_time = pendulum.from_format(request.form['end_time'], 'YYYY-MM-DD') except ValueError: end_time = pendulum.datetime(1900,1,1) error = None print(request.form['end_time']) if not start_time: error = "You must provide a start date" if end_time > start_time: cycle_length = (end_time - start_time).days else: cycle_length = (pendulum.now() - start_time).days if error is not None: flash(error) else: db = get_db() if end_time > start_time: db.execute( 'INSERT INTO cycle (start_time, end_time, cycle_length) VALUES (?, ?, ?)', (start_time.to_datetime_string(), end_time.to_datetime_string(), cycle_length) ) else: db.execute( 'INSERT INTO cycle (start_time, cycle_length) VALUES (?, ?)', (start_time.to_datetime_string(), cycle_length) ) db.commit() return redirect(url_for('index')) return render_template('cycle/create.html')