【问题标题】:How to prevent serialisation in one route in a perl dancer app?如何防止 perl dancer 应用程序中的一条路线序列化?
【发布时间】:2018-03-23 10:19:21
【问题描述】:

我有一个 perl dancer 应用程序(提供一个 rest api),它可以很好地与 JSON(反)序列化配合使用。 现在我需要一个额外的特殊路由,它提供一个(动态创建的)csv 文件供下载。

这里是示例代码:

#!/usr/bin/env perl
use Dancer2;
set serializer => 'JSON';

get '/normal' => sub {
    { 'I say ' => 'the json serializer works' };
};

get '/download' => sub {
    content_type 'text/csv';
    return  generateCsv();
};

sub generateCsv {
    return '
    1,2,3
    4,5,6
    ';
}

dance;

发送给客户端的响应没有正文,只有一个 http-header(具有正确的内容类型)

$> curl  -I  http://localhost:3000/download
HTTP/1.0 200 OK
Date: Fri, 23 Mar 2018 10:10:14 GMT
Server: Perl Dancer2 0.205002
Server: Perl Dancer2 0.205002
Content-Length: 0
Content-Type: text/csv

舞者序列化器对此不满意:

Failed to serialize content: hash- or arrayref expected 
(not a simple scalar, use allow_nonref to allow this) 
at /usr/local/share/perl/5.22.1/Dancer2/Serializer/JSON.pm line 40. 
in /usr/local/share/perl/5.22.1/Dancer2/Core/Response.pm 

我在 Dancer 文档或源代码中找不到关于 allow_nonref 的任何信息。

有人给我提示吗?

【问题讨论】:

    标签: perl dancer


    【解决方案1】:

    使用send_as:

    get '/download' => sub {
        send_as Mutable => generateCsv();
    };
    

    【讨论】:

      【解决方案2】:

      我发现send_file 也可以:

      get '/download' => sub {
              send_file (\&generateCsv(), content_type => 'text/csv', filename => 'articleEbayStatus.csv');
      };
      

      【讨论】:

        猜你喜欢
        • 2012-10-10
        • 1970-01-01
        • 1970-01-01
        • 2014-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多