json (buildins.TypeError)SQLite日期类型仅接受Python日期对象作为输入

wmomyfyw  于 2023-03-13  发布在  SQLite
关注(0)|答案(2)|浏览(129)

我尝试了很多方法在SQLAlchemy对象中插入日期,但是都出现错误。
我的路线文件:

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)

我的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))

我的查询的JSON正文:我正在将其发送到localhost。http://127.0.0.1:5001/signup

{
    "username":"amandesai01",
    "fullname":"Aman Desai",
    "password":"xyz123",
    "email":"amandesai01@gmail.com",
    "birthdate":"2000-10-14"
}

我得到的响应:

{
  "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': 'amandesai01@gmail.com', 'username': 'amandesai01'}]]",
  "status": "FAIL"
}
5t7ly7z5

5t7ly7z51#

错误说明了问题。试试这个
1.首先,您需要导入datetime类。

from datetime import datetime, date

1.现在将此更改应用于"birthdate"列。

{
    "username":"amandesai01",
    "fullname":"Aman Desai",
    "password":"xyz123",
    "email":"amandesai01@gmail.com",
    "birthdate": datetime.date(2000-10-14)
}

1.要获取当前日期(今天日期),请使用以下命令

datejoined = db.Column(db.Date, default = date.today())
brvekthn

brvekthn2#

您可以从数据中获取字符串形式的日期,然后进行如下转换:

from datetime import datetime

date = data['birthdate']

bdate = datetime.strptime(date, '%Y-%m-%d').date()

查看此处了解更多信息

相关问题