我尝试了很多方法在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"
}
2条答案
按热度按时间5t7ly7z51#
错误说明了问题。试试这个
1.首先,您需要导入
datetime
类。1.现在将此更改应用于
"birthdate"
列。1.要获取当前日期(今天日期),请使用以下命令
brvekthn2#
您可以从数据中获取字符串形式的日期,然后进行如下转换:
查看此处了解更多信息