如何在 Rack 应用程序中设置/获取会话变量? [英] How do I set/get session vars in a Rack app?

查看:40
本文介绍了如何在 Rack 应用程序中设置/获取会话变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

use Rack::Session::Pool
...
session[:msg]="Hello Rack"

会话这个词似乎没有解决.我在 config.ru 中包含了会话池中间件,并尝试在 ERB 文件中设置一个变量(我使用的是 Ruby Serve)并且它抱怨未定义的局部变量或方法`session'"

The word session doesn't seem to resolve. I included the Session pool middleware in my config.ru, and try to set a variable in an ERB file (I'm using Ruby Serve) and it complains "undefined local variable or method `session'"

谢谢!

推荐答案

session 是一些 web 框架的一部分,例如 SinatraRailssession 方法.普通的 rack 应用程序没有 session 方法,除非你自己添加.

session is a method that is part of some web frameworks, for example Sinatra and Rails both have session methods. Plain rack applications don’t have a session method, unless you add one yourself.

会话哈希存储在键 rack.session 下的 rack env 哈希中,因此您可以像这样访问它(假设您已将机架环境命名为您的应用程序 env):

The session hash is stored in the rack env hash under the key rack.session, so you can access it like this (assuming you’ve named the rack environment to your app env):

env['rack.session'][:msg]="Hello Rack"

或者,您可以使用 Rack 的内置 request 对象,像这样:

Alternatively, you could use Rack’s built in request object, like this:

request = Rack::Request.new(env)
request.session[:msg]="Hello Rack"

这篇关于如何在 Rack 应用程序中设置/获取会话变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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