usr bin perl use Mojolicious Lite use DBI use Mojo JSON from_json app-

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!/usr/bin/perl
use Mojolicious::Lite;
use DBI;
use Mojo::JSON 'from_json';
app->attr(dbh => sub{
my $dbfile = join '/', (app->home->detect, 'timeline');
DBI->connect("dbi:SQLite:dbname=$dbfile", '', '', {sqlite_unicode => 1})
});
helper db => sub { return shift->app->dbh };
app->db->do("CREATE TABLE IF NOT EXISTS articles(
`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
`time` DATETIME DEFAULT (datetime(CURRENT_TIMESTAMP,'localtime')),
`type` VARCHAR(32) NOT NULL,
`title` VARCHAR(128) NOT NULL,
`text` TEXT
)");
get '/' => sub {
my $c = shift;
my $articles = $c->db->selectall_hashref("SELECT * FROM articles", 'time');
$c->render('index', articles => $articles);
};
post '/' => sub {
my $c = shift;
my $data = from_json $c->param('article');
my $sth = $c->db->prepare('INSERT INTO articles(time, type, title, text) VALUES(?,?,?,?)');
$sth->execute($data->{time}, $data->{type}, $data->{title}, $data->{text});
$sth->finish;
$c->render(json => {status => 'OK'}, status => 200);
};
app->start;