在 Sinatra 中间件中访问会话
我正在开发一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法在 Rack 中间件中使用 Sinatra 的
session
方法,但可以通过env
哈希直接访问会话。确保会话中间件位于您的中间件之前(因此在 Sinatra 中
enable :sessions
应该位于use MyMiddleware
之前),然后可以通过密钥'rack 来使用会话.session'
:您可能更喜欢使用
Rack::Request
对象,以便更轻松地访问会话和env
哈希的其他部分:You can't use Sinatra's
session
method in Rack middleware, but you can access the session directly through theenv
hash.Make sure the session middleware is before your middleware (so in Sinatra
enable :sessions
should be beforeuse MyMiddleware
), then the session is available through the key'rack.session'
:You might prefer to use a
Rack::Request
object to make it easier to access the session and other parts of theenv
hash:对我来说,马特的回答有效,但我必须确保 sinatra 中的
use
语句顺序正确。 cookie 声明必须位于我的中间件之前: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: