【问题标题】:Flask socket.io redirect to template after socket.io event finishes在 socket.io 事件完成后烧瓶 socket.io 重定向到模板
【发布时间】:2016-11-16 22:20:39
【问题描述】:

我收到了一些 socket.io 事件。处理完事件后,我想将用户重定向到某个页面。但是,重定向不起作用。我不知道出了什么问题。以下是我的代码:

from flask import Flask, render_template, send_from_directory, redirect, url_for
from flask_socketio import SocketIO, emit
import base64
import os
import random, string

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

@app.route('/')
def index():
    try:
        image_names = os.listdir('./images')
        print image_names
        return render_template("gallery.html", image_names=image_names)
    except Exception as ex:
        print ex

@socketio.on('takephoto')
def takePhoto(*args): 
    try:
        decoded = base64.b64decode(args[0])
        filename = ''.join(random.choice(string.lowercase) for x in range(6)) + '.jpg'
        with open("./images/" + filename, "wb") as fh:
            fh.write(args[0].decode('base64'))
    except Exception, ex:
        print ex

    redirect(url_for('index')) #This doesnt work
    #how can i go to index from this point?

if __name__ == '__main__':
    from gevent import pywsgi
    from geventwebsocket.handler import WebSocketHandler
    app.debug = True
    server = pywsgi.WSGIServer(('', 5001), app, handler_class=WebSocketHandler)
    server.serve_forever()

【问题讨论】:

  • 我也需要这个!
  • 经过一番搜索,我找到了this question。是你想要的吗?

标签: python flask socket.io


【解决方案1】:

我认为您缺少return 声明。

return redirect(url_for('index'))

【讨论】:

  • 我不认为是这样,因为 socket.io 上下文中的 return 语句会将确认返回给客户端,而不是呈现给浏览器的页面。我可能需要人工获取请求之类的东西?或类似 app.navigate_to(url)
  • 另外我在想将上下文切换到应用程序可能会有所帮助,但我真的不知道该怎么做。
【解决方案2】:

聚会有点晚了,但我刚刚遇到了这个。发送'redirect' 事件并通过套接字发送url_for('index') 是您最好的选择。

服务器端:

emit('redirect', url_for('auth.login'), namespace=request.namespace, room=[request.sid])

客户端:

socket.on('redirect', (dest) => {
   window.location.href = dest;
});

【讨论】:

    猜你喜欢
    • 2015-01-22
    • 2021-03-09
    • 2016-01-24
    • 1970-01-01
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    • 2022-06-28
    • 1970-01-01
    相关资源
    最近更新 更多