我是Flask Web开发(仍在学习中)的新手。 我尝试从flask应用程序的注册页面注册新用户,然后出现此错误。
"SQLite DateTime type only accepts Python "
sqlalchemy.exc.StatementError: (builtins.TypeError) SQLite DateTime type only accepts Python datetime and date objects a
s input.
[SQL: INSERT INTO user (username, email, password_hash, about_me, last_seen) VALUES (?, ?, ?, ?, ?)]
[parameters: [{'password_hash': 'pbkdf2:sha256:150000$Wknz8xPs$b1694e1d9b6b8f6a2c171147c37a1f96ff27be9da39ee825cf442f382
0c32313', 'email': 'test@example.com', 'username': 'test', 'about_me': None}]]
127.0.0.1 - - [08/Jun/2019 15:07:18] "POST /register HTTP/1.1" 500 -
这是我的模特。py
from datetime import datetime
from app import db
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
from hashlib import md5
from app import login
@login.user_loader
def load_user(id):
return User.query.get(int(id))
class User(UserMixin ,db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
password_hash = db.Column(db.String(128))
posts = db.relationship('Post', backref='author', lazy='dynamic')
about_me = db.Column(db.String(140))
last_seen = db.Column(db.DateTime, default="datetime.utcnow")
def __repr__(self):
return '<User {}>'.format(self.username)
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
def avatar(self, size):
digest = md5(self.email.lower().encode('utf-8')).hexdigest()
return 'https://www.gravatar.com/avatar/{}?d=identicon&s={}'.format(
digest, size)
这是我的注册视图功能
@app.route('/register', methods=['GET', 'POST'])
def register():
if current_user.is_authenticated:
return redirect(url_for('index'))
form = RegistrationForm()
if form.validate_on_submit():
user = User(username=form.username.data, email=form.email.data)
user.set_password(form.password.data)
db.session.add(user)
db.session.commit()
flash('Congratulations, you are now a registered user!')
return redirect(url_for('login'))
return render_template('register.html', title='Register', form=form)
答案 0 :(得分:2)
您正在尝试将函数传递给default
参数。如the docs所示,这应该是一个函数引用(但不能调用)。在您的示例中,您提供了一个字符串。
更改:
last_seen = db.Column(db.DateTime, default="datetime.utcnow")
收件人:
last_seen = db.Column(db.DateTime, default=datetime.utcnow)
这就是Mega Tutorial让您from datetime import datetime
做的原因。
侧面说明:对于SQLite,此错误消息实际上是不正确的。 SQLite不强制使用严格的列类型,因此您可以将字符串插入整数类型的列等。这并不是说该错误没有用,因为SQLAlchemy仍然会依赖于列数据类型,但是SQLite本身并不严格执行,这可能会让您措手不及。
import sqlite3
with sqlite3.connect(':memory:') as conn:
c = conn.cursor()
# Create a table and try enforce a datetime type
c.execute("""
CREATE TABLE IF NOT EXISTS test(
id PRIMARY KEY,
datetime DATETIME)
""")
conn.commit()
c.execute("""
INSERT INTO test
VALUES (?, ?)
""", (None, '123')) # Insert non-datetime value into datetime col
conn.commit()
c.execute("SELECT * FROM test")
print(c.fetchall()) # Worked just fine