如何在具有不同序列化程序的 Dancer2 应用程序之间共享会话数据?

How can I share session data between Dancer2 apps with different serializers?

我正在尝试将应用程序从 Dancer 迁移到 Dancer2。我的想法是将代码分成由模板提供的路由和 Ajax (API) 调用的路由。

我的基础应用是:

use strict;
use warnings;
use FindBin; 
use Plack::Builder;

use Routes::Templates;
use Routes::Login; 

builder {
    mount '/'    => Routes::Templates->to_app;
    mount '/api' => Routes::Login->to_app;
};

我在想 Routes::Templates 包不会有任何序列化程序,而 Routes::Login 包会有 JSON 序列化。我用了

set serializer => 'JSON';

Routes::Login 包中。

但是,我也希望它们共享会话数据,以便每个都有一个共同的应用程序名称

use Dancer2 appname => 'myapp';

在每个文件中。这似乎 运行 在序列化方面遇到了麻烦。 Routes::Template 路由没有正确返回,因为它试图被编码为 JSON。这是错误:

Failed to serialize content: hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)

我已阅读所有文档,包括:

但是我还是不清楚序列化器是如何被包分开的。

无需使用 appname 组合您的应用;只要两个应用程序对会话引擎使用相同的配置,就会共享会话数据。 (另外,serializers are an all-or-nothing prospect 在 Dancer2 中,所以你真的 必须 使用两个单独的应用程序。)

这是我在 dancer-users mailing list 上给出的例子:

MyApp/lib/MyApp.pm

package MyApp;
use Dancer2;

our $VERSION = '0.1';

get '/' => sub {
    session foo => 'bar';
    template 'index';
};

true;

MyApp/lib/MyApp/API.pm

package MyApp::API;
use Dancer2;

set serializer => 'JSON';

get '/' => sub {
    my $foo = session('foo') // 'fail';
    return { foo => $foo };
};

true;

MyApp/bin/app.psgi

#!/usr/bin/env perl

use strict;
use warnings;
use FindBin;
use lib "$FindBin::Bin/../lib";

use MyApp;
use MyApp::API;
use Plack::Builder;

builder {
    mount '/'    => MyApp->to_app;
    mount '/api' => MyApp::API->to_app;
};

如果您在同一浏览器中访问 / 路由,然后访问 /api 路由,您将获得

{"foo":"bar"}

表示两个请求使用了相同的会话变量。