2
votes

I Tried many ways of inserting date in my SQLAlchemy object. But gives error.

My route file:

app.route('/signup', methods=['POST'])
def signup():
    reply = {}
    try:
        data = request.get_json()
        password_hash = generate_password_hash(data['password'])
        datelist = data['birthdate'].split('-')
        bdate = datetime.date(int(datelist[0]), int(datelist[1]), int(datelist[2]))
        new_user = Entities.User(id = uuid.uuid4(), username = data['username'], fullname = data['fullname'], email = data['email'], password_hash = password_hash, birthdate = bdate)
        db.session.add(new_user)
        db.session.commit()
        reply['status'] = "OK"
        reply['message'] = ""
    except Exception as e:
        reply['status'] = "FAIL"
        reply['message'] = str(e)
    return jsonify(reply)

My User Class of SQLAlchemy:

class User(db.Model):
    id = db.Column(db.String(40), unique=True, primary_key=True)
    username = db.Column(db.String(25), index=True, unique=True)
    fullname = db.Column(db.String(25), index=True)
    email = db.Column(db.String(25), index=True, unique=True)
    password_hash = db.Column(db.String(128))
    imagelink = db.Column(db.String(300), default = "some.url.unspecified.com")
    bio = db.Column(db.String(700), default = "No Bio Added")
    datejoined = db.Column(db.Date, default = date.today().strftime("%Y-%m-%d"))
    birthdate = db.Column(db.String(10))

My Query's JSON Body: I am firing this to localhost. http://127.0.0.1:5001/signup

{
    "username":"amandesai01",
    "fullname":"Aman Desai",
    "password":"xyz123",
    "email":"[email protected]",
    "birthdate":"2000-10-14"
}

Response I am getting:

{
  "message": "(builtins.TypeError) SQLite Date type only accepts Python date objects as input.\n[SQL: INSERT INTO user (id, username, fullname, email, password_hash, imagelink, bio, datejoined, birthdate) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)]\n[parameters: [{'password_hash': 'pbkdf2:sha256:150000$CPZYKMPJ$b4e0f3a01e17e533a92cd21709b1e4f496f068bd19c8b31fa2723cbbf1ea6beb', 'id': UUID('0e8f6414-27af-4ca9-8e72-a0f4974a0b0d'), 'fullname': 'Aman Desai', 'birthdate': datetime.date(2000, 10, 14), 'email': '[email protected]', 'username': 'amandesai01'}]]",
  "status": "FAIL"
}
1
I can't understand, exactly which date object they need. I tried datetime.date but didn't work :( - Aman Desai
datejoined = db.Column(db.Date, default = date.today().strftime("%Y-%m-%d")) has an interesting default. - Ilja Everilä

1 Answers

0
votes

The error says the problem. Try this

  1. First you need to import datetime class.
from datetime import datetime, date
  1. Now apply this change to your "birthdate" column.
{
    "username":"amandesai01",
    "fullname":"Aman Desai",
    "password":"xyz123",
    "email":"[email protected]",
    "birthdate": datetime.date(2000-10-14)
}
  1. To get current date(today date) use this command
datejoined = db.Column(db.Date, default = date.today())