在 Sinatra 中间件中访问会话

发布于 2025-01-01 13:06:07 字数 359 浏览 0 评论 0原文

我正在开发一个 Sinatra 项目,并在会话中设置了一些变量以供以后使用。

我需要帮助的场景是我想访问中间件类中的会话对象。我正在使用典狱长进行身份验证。

我想在中间件类中做类似的事情:

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

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

有可能这样做吗?

想法?

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.

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

Is there a possibility for doing that?

Thoughts?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小情绪 2025-01-08 13:06:07

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

确保会话中间件位于您的中间件之前(因此在 Sinatra 中 enable :sessions 应该位于 use MyMiddleware 之前),然后可以通过密钥 '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 哈希的其他部分:

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

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

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

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
酒中人 2025-01-08 13:06:07

对我来说,马特的回答有效,但我必须确保 sinatra 中的 use 语句顺序正确。 cookie 声明必须位于我的中间件之前:

class ApiDocs < Sinatra::Base

use Rack::Session::Cookie, ... #etc
use MyMiddleware # my middleware that uses session

For me, matt's answer worked, but I had to make sure that my use statements in sinatra were in the right order. The cookie declaration has to come before my middleware:

class ApiDocs < Sinatra::Base

use Rack::Session::Cookie, ... #etc
use MyMiddleware # my middleware that uses session

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文