gpt4 book ai didi

ruby - Sinatra 中的 session : Used to Pass Variable

转载 作者:数据小太阳 更新时间:2023-10-29 08:01:37 28 4
gpt4 key购买 nike

所以我有一段代码看起来像:

post '/calendar' do
#pull variables from form
@cal = a.makeCal(form, variables) #do some work here with variables
session["value"] == @cal
haml :calendar
end

然后我有这个:

get '/print' do
@cal = session["value"]
haml :print
end

我所做的测试是通过将表单发布到/calendar 创建一个日历。接下来我手动转到/print,我希望我的变量 @cal 保留在 cookie 中。我应该有吗?我这样做对吗?

我想做的是获取 @cal 值,它是四个数组,并将其传递到打印页面上,而无需重新计算 @cal。尝试通过 session 来做到这一点是正确的方法吗?

最佳答案

您的post route 有错别字:

session["value"] == @cal
# ^^ compares for equality, does not set.

这不会影响 session ,但只会评估为 true 或(更有可能)false

@cal 是什么类型的对象,您使用什么来支持您的 session ? (这些 cookie 支持的 session ,又名 Rack::Session::Cookie,是否通过 enable :sessions 启用?如果是这样,您的对象是否肯定能够通过 Marshal 序列化?)

编辑

是的,如果您更正了那个拼写错误,您所拥有的应该可以工作。

这是一个适合我的测试应用程序...

require 'sinatra'
enable :sessions
get('/'){ haml :show_and_go }
post '/' do
session["foo"] = [[[1,2],[3,4]],[5,6]]
"Now get it!\n"
end
__END__
@@show_and_go
%p= session["foo"].inspect
%form(method='post' action='/')
%button go

...这是实际测试。我们看到没有 cookie 就没有 session ,但是一旦 cookie 被写入,下一个请求就会正常工作。这在浏览器中也同样有效:

phrogz$ cat cookies.txt
cat: cookies.txt: No such file or directory

phrogz$ curl http://localhost:4567/ # GET
<p>nil</p>
<form action='/' method='post'>
<button>go</button>
</form>

phrogz$ curl -d "" -c cookies.txt http://localhost:4567 # POST
Now get it!

phrogz$ curl -b cookies.txt http://localhost:4567 # GET, with cookies
<p>[[[1, 2], [3, 4]], [5, 6]]</p>
<form action='/' method='post'>
<button>go</button>
</form>

关于ruby - Sinatra 中的 session : Used to Pass Variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7408322/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com