制作flask-app,使用.docx文件(home/user/WebApp/app/docxfiles/*.docx)并使用sqlalchemy显示它们。使用MySQL。列是从 Flask-admin 写入的。这是一段你无法正确执行的代码。如何将默认值写入列,其中默认值是从使用另一个列的函数创建的值?
class Item(db.Model):
def getinfo(namefile):
path_file = os.path.abspath(os.path.dirname(__file__)) + "/docxfiles/" + namefile
doc = docx.Document(path_file)
fulltext = []
for i in doc.paragraphs:
fulltext.append(i.text)
body = '\n\n'.join(fulltext)
return re.sub('<(.|\n)*?>','',body)
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
namefile = db.Column(db.String(200), unique=True)
info = db.Column(db.String(16777216), server_default = getinfo(namefile))
最佳答案
作为 server_default
或 default
值传递的列默认值对于设置固定默认值或日期或时间戳很有用,但不接受运行时参数以允许更复杂的处理,例如在你的例子中。放置此类代码的正确位置是模型类的构造函数中,该构造函数仅在创建新对象时调用,但在从数据库检索对象时不会调用。要实现此功能,代码中所需的唯一更改是将 getinfo
函数转换为 __init__
方法,并手动设置 namefile
的值和信息
。
class Item(db.Model):
def __init__(self, namefile):
path_file = os.path.abspath(os.path.dirname(__file__)) + "/docxfiles/" + namefile
doc = docx.Document(path_file)
fulltext = []
for i in doc.paragraphs:
fulltext.append(i.text)
body = '\n\n'.join(fulltext)
self.info = re.sub('<(.|\n)*?>','',body)
self.namefile = namefile
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
namefile = db.Column(db.String(200), unique=True)
info = db.Column(db.String(16777216))
关于python - 如何将默认值写入列,其中默认值是从使用另一个列的函数创建的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53012428/