0

I'm just join the stackoverflow community right now because I trying to complete my first Python-flask application and I got some problem to fetch and compare a single date for single user with sqlalchemy & sqlite.

Here my imports:

from flask import Flask, request, jsonify, render_template, url_for, redirect, flash
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine, MetaData, func
import datetime

Here my table database model:

class BloodDonation(db.Model):
   id = db.Column(db.Integer, primary_key = True)
   name = db.Column(db.String, nullable=False)
   age = db.Column(db.Integer, nullable=False)
   blood_groups = db.Column(db.String, nullable=False)
   city = db.Column(db.String, nullable=False)
   phone_no = db.Column(db.String, nullable=False)
   latest_donation = db.Column(db.Date, nullable=False)
   next_donation = db.Column(db.Date)
   donation_counter = db.Column(db.Integer, default=1)

This is a easy CRUD application where I should store blood donations inside a database with 3 months threshold donation per user. To do that I use the mobile number as user identifier and I use datetime module, so when an user try to do more than an donation before 90 days the application have to show the message donation forbidden.

Here my code:

@app.route('/blood_donation', methods=['GET','POST'])
def blood_donation():
     if request.method == 'GET':
        blood_groups = ['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-']
        return render_template('donate.html', blood_groups = blood_groups)

     else:
    donation_day = datetime.date.today()
    next_donation_date = threshold_time(donation_day) # this func return donation date + 90 days
    
    data_fields = ['name','age','blood_groups','city','phone_no']

    data_dict = {}
    data_dict['latest_donation'] = donation_day
    data_dict['next_donation'] = next_donation_date
                  

    for field in data_fields:
        data_dict[field] = request.form.get(field).lower()

    for value in data_dict.values():
       if value == "":
            return "Please enter all the details." 
              
    counter = db.session.query(BloodDonation).filter(BloodDonation.phone_no == data_dict['phone_no']).count() 
    next_bd_date = db.session.query(BloodDonation).filter(func.DATE(BloodDonation.latest_donation) >= 0)
                
    if counter >= 0 and next_bd_date and\
    db.session.query(BloodDonation).filter(func.DATE(BloodDonation.latest_donation)\ 
    <= data_dict['latest_donation']):
       counter += 1
       data_dict['donation_counter'] = counter
       blood_donation = BloodDonation(**data_dict)
       db.session.add(blood_donation)
       db.session.commit()
       return redirect(url_for('home'))   

    return "Donation forbidden!!!"

I think the problem is in the if statement to compare dates and mobile number that I use as donation counter and user identifier since the application continue update the database without return donation forbidden.

Here the wrong code:

    if counter >= 0 and next_bd_date and \
        db.session.query(BloodDonation).filter(func.DATE(BloodDonation.latest_donation) <= 
        data_dict['latest_donation']):

I hope somebody can help me since I am not a pro but a beginner

Thanks in advance!

Hamundo
  • 1
  • 2
  • well get the last donated date and current date and find difference in days, more that 90 then allow else forbid, or create a dummy coloumn which keep the date upto which cant do donation and check if donation trying date is less then that or not – sahasrara62 Oct 28 '20 at 19:20
  • I tried to do the difference between last donation day and current date but I got this error: TypeError: unsupported operand type(s) for -: 'BloodDonation' and 'datetime.date' – Hamundo Oct 29 '20 at 11:25
  • However I need to get a single latest donation date for single user and not a keys values pair list – Hamundo Oct 29 '20 at 11:31
  • https://stackoverflow.com/questions/151199/how-to-calculate-number-of-days-between-two-given-dates this may help the no of days, you can use datetime.datetime.utcnow for current date – sahasrara62 Oct 29 '20 at 11:33

1 Answers1

0

It looks like you might have several spacing issues. Python doesn't like it if you don't have proper spacing. Try this. Also I wasn't sure where you wanted that final return statement so I'm not sure if I spaced it correctly.

@app.route('/blood_donation', methods=['GET','POST'])
def blood_donation():
    if request.method == 'GET':
        blood_groups = ['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-']
        return render_template('donate.html', blood_groups = blood_groups)

    else:
        donation_day = datetime.date.today()
        next_donation_date = threshold_time(donation_day)
        
        data_fields = ['name','age','blood_groups','city','phone_no']

        data_dict = {}
        data_dict['latest_donation'] = donation_day
        data_dict['next_donation'] = next_donation_date
                    

        for field in data_fields:
            data_dict[field] = request.form.get(field).lower()

        for value in data_dict.values():
            if value == "":
                return "Please enter all the details." 
                
        counter = db.session.query(BloodDonation).filter(BloodDonation.phone_no == data_dict['phone_no']).count() 
        next_bd = db.session.query(BloodDonation).filter(func.DATE(BloodDonation.latest_donation) >= 0)
                    

        if counter >= 0 and next_bd and \
            db.session.query(BloodDonation).filter(func.DATE(BloodDonation.latest_donation) <= data_dict['latest_donation']):
                counter += 1
                data_dict['donation_counter'] = counter

                blood_donation = BloodDonation(**data_dict)
                db.session.add(blood_donation)
                db.session.commit()
                
                return redirect(url_for('home'))   

        return "Donation forbidden!!!"
Andrew Clark
  • 850
  • 7
  • 13
  • it is finding the difference between no of days from last donation to present one if less than 90 then no donation or if more than 90 eligible for donation – sahasrara62 Oct 29 '20 at 11:34
  • TypeError: unsupported operand type(s) for -: 'BaseQuery' and 'datetime.date' – Hamundo Oct 29 '20 at 17:39
  • I got that error because I'm trying to store and fetch next_donation date from my database with this statement : `next_bd_date = db.session.query(BloodDonation).filter(func.DATE(BloodDonation.latest_donation) >= 0)` – Hamundo Oct 29 '20 at 18:07