我正在通过youtube(Corey Schafer)进行一些项目制作Web应用程序,并且部分引入SQLite的情况是在类中定义 repr 方法时出现错误。
这是代码的一部分:
from datetime import datetime
from flask import Flask, render_template, url_for, flash, redirect
from flask_sqlalchemy import SQLAlchemy
...
app = Flask(__name__)
app.config["SECRET_KEY"] = "..."
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///site.db"
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
image_file = db.Column(db.String(20), nullable=False, default="default.jpg")
password = db.Column(db.String(60), nullable=False)
posts = db.relationship("Post", backref="author", lazy=True)
def __repr__(self):
return f"User('{self.username}', '{self.email}', '{self.image_file}')"
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
date_posted = db.Column(db.DateTime, nullable=False,
default=datetime.utcnow)
content = db.Column(db.Text, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=False)
def __repr__(self):
return f"Post('{self.title}', '{self.date_posted}')"
我可以创建用户和帖子,并且所有这些都保存在数据库中,但是在使用时
User.query.all()
it(PyCharm)失败并发送错误:
sqlalchemy.exc.ProgrammingError: (sqlite3.ProgrammingError) SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 6844 and this is thread id 7584. [SQL: 'SELECT user.id AS user_id, user.username AS user_username, user.email AS user_email, user.image_file AS user_image_file, user.password AS user_password \nFROM user'] [parameters: [{}]] (Background on this error at: http://sqlalche.me/e/f405)
因此,我查看了链接并找出了导致这种情况的问题的 repr ,因此当我评论该方法或将其删除时,该方法起作用了,但是给出的数据信息微弱或非常有限在数据库中。
我正在使用Windows 10,Python 3.7,PyCharm
我看到他们在某处不使用'',但仍然如此:
def __repr__(self):
return f"User({self.username}, {self.email}, {self.image_file})"
这是怎么了?