Как уведомить всех пользователей о добавлении файла? - PullRequest
0 голосов
/ 28 ноября 2018

Я хотел бы отправить уведомление с сервера всем пользователям одновременно, когда один из них загрузит новый файл.Добавление файлов работает правильно.Я построил свое веб-приложение, используя Python с Flask.

@app.route('/upload')
@login_required
def file_add():
    redis.expire(session['current_user'], time=300)
    user_path = app.upload_path.joinpath(redis.get(session['current_user']).decode()).resolve()
    files = [x.name for x in user_path.glob('**/*') if x.is_file()]
    files_len = len(files)
    token = creating_token("allow", 240).decode('utf-8')
    return render_template('upload.html', files_len=files_len, token=token)

Когда я попытался сделать это с Pub / Sub (мой код ниже), я получил ошибку:

assert isinstance(data, bytes), 'applications must write bytes'
AssertionError: applications must write bytes

Код:

def event_stream():
    pubsub = red.pubsub()
    pubsub.subscribe('message')
    for message in pubsub.listen():
        #print(message)
        yield message['data']


@app.route('/post', methods=['POST'])
def post():
    now = datetime.datetime.now().replace(microsecond=0).time()
    red.publish('message', 'File has been sent')
    return Response(status=204)


@app.route('/stream')
def stream():
    return Response(event_stream(),
                          mimetype="text/event-stream")

Вот мой код JS:

function sse() {
                var source = new EventSource('http://127.0.0.1:5002/slyko/stream');
                source.onmessage = function(e) {
                    console.log(e.data);
                };
            }

sse()
...