python看门狗在文件更改时使用uwsgi api

时间:2014-06-19 07:53:04

标签: python uwsgi python-watchdog

每当我尝试使用此代码并更新文件时,我会在命令行中收到以下消息:

  

SystemError:你只能从main调用uwsgi api函数   调用

有人可以向我解释如何做到这一点吗?

谢谢!

#!/usr/bin/env python
import logging
import time
from flask import Flask, render_template
from flask.ext.uwsgi_websocket import WebSocket
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer

logging.basicConfig(level=logging.ERROR)

app = Flask(__name__)
ws = WebSocket(app)

class MyEventHandler(FileSystemEventHandler):
    def __init__(self, observer, filename, ws):
        self.observer = observer
        self.filename = filename
        self.ws = ws

    def on_modified(self, event):
        self.ws.send('The file is updated!')

@ws.route('/')
def websocket_server(ws):
    path = '/var/lib/omniwallet/addr/'
    observer = Observer()

    while True:
        address = ws.receive()
        if address is not None:
            filename = address + '.json'

            event_handler = MyEventHandler(observer, filename, ws)
            observer.schedule(event_handler, path, recursive=False)
            observer.start()

            try:
                while True:
                    time.sleep(1)
            except KeyboardInterrupt:
                observer.stop()
            observer.join()

        else: return

if __name__ == '__main__':
    app.run(debug=True, threads=16)

1 个答案:

答案 0 :(得分:0)

您无法使用该方法,因为观察者在另一个线程中运行,与管理请求的线程完全无关。您可以使用线程队列更改逻辑:MyEventHandler写入队列,而主可调用队列等待它并发送回websocket消息。