我正在尋找一種將 sqlite 資料庫中的檔案名與 windows 目錄中的檔案名(app.config ['UPLOAD_FOLDER'])進行比較的解決方案。
我有一個 sqlite 資料庫,其中有一個名為“檔案”的表,其中包含檔案中的所有資料。
檔案定義為:files = [file.to_displayable_dict() for file in File.query if is_file_visible(file)] 這是函式:
def to_displayable_dict(self):
return {
"Dateiname" : "<div class=hasTooltip> <a href=/download/" self.name ">" self.name "</a> <span>" self.beschreibung "</span></div>",
"Kategorie" : self.kategorie,
"Bezeichnung" : self.bezeichnung,
"TV" : self.tv,
"Stand" : self.stand,
"Upload-Benutzer" : self.uploadbenutzer,
"Vertraulichkeitsstufen" : self.Vertraulichkeitsstufen
}
在 sqlite 表檔案中,如果我 print("Files:", files) LOOK 添加了其他注釋,則我有這種資料。
如果我進入我的 Windows 實體檔案夾(app.config['UPLOAD_FOLDER'])并洗掉檔案(日期名稱:EPEX_SPOTPRICE_STROM),它應該會自動洗掉我的 database.db 檔案表中的檔案。
對于解決方案,必須比較 WIndows 目錄中的檔案名和表檔案中的檔案名。
由于href,我不知道如何進行比較。我的想法是,但不起作用。通過路由發布操作不是一個好的解決方案。
something like get_files = os.listdir(app.config['UPLOAD_FOLDER'])
for file in Files.query():
if file.filename not in files_in_folder:
db.session.delete(file.filename)
db.session.commit()
flash (data was deleted )
在 python 燒瓶下你會怎么做?有自己的代碼示例有什么建議嗎?謝謝!
我試圖解決這個問題:
import os
path = r"C:/Users/add706/Documents/NRL_webseite/instance/uploads"
def get_files(path):
for file in os.listdir(path):
if os.path.isfile(os.path.join(path, file)):
yield file
for file in get_files(path):
print("file:", file)
該檔案的輸出:EPEX_SPOTPRICE_STROM.docx
uj5u.com熱心網友回復:
如果您想要一個端點,使用該端點從資料庫中洗掉檔案系統中不再存在的所有檔案參考,代碼應如下所示。
@app.route('/sync')
def sync():
files = os.listdir(app.config['UPLOAD_FOLDER'])
if File.query.filter(File.name.notin_(files)).delete():
db.session.commit()
return redirect(url_for('index'))
另一種選擇是使用我不太熟悉的檔案系統事件。下面是使用watchdog的示例代碼。
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
# ...
class MyHandler(FileSystemEventHandler):
def on_deleted(self, event):
if not event.is_directory:
target = event.src_path[len(app.config['UPLOAD_FOLDER']) 1:]
if File.query.filter_by(name=target).delete():
db.session.commit()
def run_watcher(path):
fs_handler = MyHandler()
observer = Observer()
observer.schedule(fs_handler, path, recursive=False)
observer.start()
run_watcher(app.config['UPLOAD_FOLDER'])
也可以有一個定期執行并洗掉所有無效條目的腳本。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/467914.html
標籤:Python 视窗 sqlite 烧瓶 烧瓶-sqlalchemy
