LoginSignup
0
0

More than 5 years have passed since last update.

CGI::Session のバックエンドデータベースに SQLite を使う

Last updated at Posted at 2018-04-05

2018年になっても、小規模な CGI を書く時には CGI::Session は重宝するのですが、問題はセッションを格納するバックエンドデータベースです。流石に、複数の CGI が同時に動作するケースを考えないわけにはいかないので、SQLite を使おうとしたのですが、CGI::Session::Driver::sqlite のマニュアル通りに記述しても動作しませんでした…。

散々試行錯誤して、ようやく sessions というテーブルが必要だということが分かりました。そのテーブルを作成する SQL 文も含むコード例を示します。

session-example.cgi
#!/usr/bin/perl

use CGI;
use CGI::Session qw/ -ip-match /;
use DBI;
use strict;
use warnings;
use utf8;
use open qw/ :utf8 :std /;

my $filename = "データベースファイル名";

my $dbh = DBI->connect( sprintf( 'dbi:SQLite:dbname=%s', $filename ), undef, undef ) or die;
$dbh->do( <<'__create_table__' );
CREATE TABLE if not exists sessions (
    id CHAR(32) NOT NULL UNIQUE,
    a_session TEXT NOT NULL
);
__create_table__

my $cgi = CGI->new();
my $session = CGI::Session->new( 'driver:SQLite', $cgi, { Handle => $dbh } );
$session->param( 'count' => ( $session->param('count') || 0 ) + 1 );
print $cgi->header( -status => 200,
                    -type => 'text/plain',
                    -charset => 'UTF-8',
                    -cookie => $cgi->cookie( -name => $session->name,
                                             -value => $session->id,
                                             -domain => $cgi->server_name,
                                             -path => $cgi->script_name ) );
printf "Current Session ID = %s\n", $session->id;
printf "Current Counter = %d\n", $session->param('count');
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0