Sinatra中间件中的访问会话 [英] Accessing session in Sinatra Middleware

查看:96
本文介绍了Sinatra中间件中的访问会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Sinatra项目,并在会话中设置了一些变量以供以后使用.

I am working on a Sinatra Project and have set some variables in the session for later usage.

我需要帮助的情况是,我想访问中间件类中的会话对象.我正在使用管理员进行身份验证.

The scenario for which I need help for is that I want to access the session object in a middleware class. I am using warden for authentication.

我想在Middleware类中做以下类似的事情:

I want to do something similar below in the Middleware class:

class MyMiddleware
    def initialize(app, options={})
        @app = app
    end

    def call(env)
        puts "#{session.inspect}" 
    end
end

有可能这样做吗?

有想法吗?

推荐答案

您不能在Rack中间件中使用Sinatra的session方法,但是您可以直接通过env哈希访问会话.

You can't use Sinatra's session method in Rack middleware, but you can access the session directly through the env hash.

确保会话中间件在中间件​​之前(因此,在Sinatra enable :sessions中应在use MyMiddleware之前),然后可以通过键'rack.session'使用会话:

Make sure the session middleware is before your middleware (so in Sinatra enable :sessions should be before use MyMiddleware), then the session is available through the key 'rack.session':

class MyMiddleware
  def initialize(app, options={})
    @app = app
  end

  def call(env)
    puts env['rack.session'].inspect
    @app.call(env)
  end
end

您可能更喜欢使用 Rack::Request 对象来简化操作访问会话和env哈希的其他部分:

You might prefer to use a Rack::Request object to make it easier to access the session and other parts of the env hash:

def call(env)
  request = Rack::Request.new(env)
  puts request.session.inspect
  # other uses of request without needing to know what keys of env you need
  @app.call(env)
end

这篇关于Sinatra中间件中的访问会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆