【问题标题】:Using Flask Session with new EventSource将 Flask Session 与新的 EventSource 一起使用
【发布时间】:2017-12-31 20:26:17
【问题描述】:

抱歉标题措辞不佳。

我的目标是使用 AJAX 设置一个 Flask 页面,以便在 Python 程序运行时向页面添加动态内容。

我正在使用 flask_oauthlib 获取 REST API 的访问令牌,然后查询该 REST API 以获取分页内容。

当我们重复 REST 调用以从 API 获取不同的内容页面时,我想显示“进度”。 REST API 访问令牌存储在用户的会话变量中。

我已按照these 的步骤来启动并运行一个基本的动态页面。但是,当我开始修改“progress”函数以添加对会话变量的访问时,一切都开始失败。

我收到错误:RuntimeError: Working outside of request context.,它告诉我我不在正确的会话上下文中。

我的猜测是因为这个端点是使用 new EventSource 从 javascript 调用的...我怎样才能以这种方式访问​​会话上下文?

我是走在正确的道路上,还是有更好的选择?

这是我拥有的各种代码块:

<!DOCTYPE html>
<html>
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
    <script>

    var source = new EventSource("/progress");
    source.onmessage = function(event) {
        $('.text').text(event.data);
    }
    </script>
</head>
<body>
        <p class="text"></p>
</body>
</html>

@app.route('/sentMail')
def sentMail():  
    return render_template('progress.html')

@app.route('/progress')
def progress():
    def generate():
        #code using trying to use session here
    return Response(generate(), mimetype= 'text/event-stream')

【问题讨论】:

    标签: javascript python ajax session flask


    【解决方案1】:

    一旦 Web 服务器开始处理响应,您就无法访问请求上下文,但幸运的是 Flask 带有流装饰器@987654321@ 您可以使用它来访问流中的请求上下文...

    将您的代码修改为以下内容...

    from flask import stream_with_context
    
    
    @app.route('/progress')
    def progress():
        @stream_with_context
        def generate():
            ...
            Your remaining code
            ...
    

    【讨论】:

    • 这成功了!感谢您非常简洁明了的回答:)
    猜你喜欢
    • 2014-08-16
    • 2013-06-19
    • 1970-01-01
    • 1970-01-01
    • 2015-01-05
    • 2010-09-17
    • 1970-01-01
    • 2019-05-28
    • 2013-01-02
    相关资源
    最近更新 更多