我有一个flask应用程序,用于监视日志文件的更改,并在每次更改后将其写入数据库。
当我在开发服务器上运行它时,一切正常,但是当使用uwsgi或gunicorn在生产环境中运行时,看门狗不会收到任何更改,因此没有数据库输入。
from datetime import datetime as dt
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from application.models import db, RecordDB, LogDB
from application.parser import get_last_n_records, parse_record
from application import create_app
app = create_app()
class MyHandler(FileSystemEventHandler):
def on_modified(self, event):
if event.event_type == "modified" and event.src_path == "/var/log/icecast/song-history.log":
title, artist, album, started_at = parse_record(get_last_n_records(n=1))
with app.app_context():
try:
record = RecordDB(title=title,
artist=artist,
album=album,
started_at=started_at,
added_at=dt.now())
db.session.add(record)
db.session.commit()
except Exception as e:
print(e)
elif event.event_type == "modified" and event.src_path == "/var/log/icecast/access.log":
with app.app_context():
try:
record = LogDB(message=get_last_n_records(n=1),
time=dt.now())
db.session.add(record)
db.session.commit()
except Exception as e:
print(e)
def notify():
event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, path='/var/log/icecast', recursive=False)
observer.start()
这是我的run.py文件作为入口点
import threading
from application.notifier import app, notify
def main():
notify_thread = threading.Thread(target=notify)
notify_thread.start()
app.run(host='localhost', port='5000')
notify_thread.join()
if __name__ == "__main__":
main()
当我使用python run.py
在dev上运行它时,它工作正常,并且每次发生更改时都会更新数据库。当我使用uwsgi --http-socket :5000 --plugin python3 --module run:app --processes 2 --enable-threads --threads 4
运行它时,没有文件系统事件发生,因此不会发生对db的输入。
我实际上在SO上找到了一些类似的问题,但它们都没有真正有用,因为唯一的答案是允许在我拥有的uwsgi上进行线程化。有人可以帮助解决问题吗?