如何通知所有用户有关添加文件的信息?

时间:2018-11-28 11:59:14

标签: javascript python flask push-notification

当其中一个用户上传新文件时,我想同时从服务器向所有用户发送通知。添加文件可以正常工作。我已经在Flask中使用python构建了我的webapp。

@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()

0 个答案:

没有答案