Download as odp, pdf, or txt
Download as odp, pdf, or txt
You are on page 1of 42

Dancer2

Prasad
What is a Web framework?

It is a software framework that is designed to


support the development of web applications
including web services, web resources, and web
APIs.
Web frameworks provide a standard way to build and
deploy web applications on the World Wide Web.
Many web frameworks provide libraries for database
access, templating frameworks, and session
management, and they often promote code reuse.
Dancer2

Dancer is an open source lightweight


web application framework written in Perl
and inspired by Ruby's Sinatra.
Dancer was rewritten from scratch and
released as Dancer2. The reason for the
rewrite was to fix architectural issues and
eliminate the use of singletons.
Installing Dancer2

Install curl on Ubuntu,


#apt-get install curl

Install Dependencies for cpanminus,


#apt-get update
#apt-get upgrade
#apt-get install perl build-essential libssl-dev
Installing Dancer2

● Install cpanminus,
#curl -L https://cpanmin.us | perl - --sudo
App::cpanminus

● Update cpanminus,
#cpanm --self-upgrade –sudo
● Installing Dancer2,
#curl -L http://cpanmin.us | perl
- --sudo Dancer2
Dancer Application

Dancer constructs web applications by building a list of


HTTP verbs, URLs (called routes) and methods to handle
that type of traffic to that specific URL.
get '/' => sub {
return 'Hello World!';
};
HTTP verb "GET" followed by the root URL "/" and
an anonymous subroutine which returns the string
"Hello World!"
Static Patterns

#!/usr/bin/env perl
use Dancer2;
get '/' => sub {
"Hello World!"
};
dance;
Static Patterns contd..

#!/usr/bin/env perl
use Dancer2;
get '/hello' => sub {
"Hello World!"
};
dance;
Patterns (Named Tokens)

#!/usr/bin/perl
use Dancer2;
get '/hello/:name' => sub {
return "Why, hello there " . params->{name};
};
dance;
Patterns (Anonymous Tokens)

#! /usr/bin/env perl
use Dancer2;
get '/hello/*.*' => sub {
return "Why, hello there "
};
dance;
Patterns (Regex)

#! /usr/bin/env perl
use Dancer2;
get qr{/quello/([\w]+)} => sub {
my($name)=splat;
return "Hello $name";
};
dance;
Patterns (Regex)

#! /usr/bin/env perl
use Dancer2;
get qr{/hello/(\d+)-(\d+)-(\d+)} => sub {
my($d,$m,$y)=splat;
return "Hello $d/$m/$y";
};
dance;

Creating a Dancer Project

$ dancer2 -a MyWeb::App

● MyWeb::App/bin/app.psgi (A standalone
Server)

To run,
$ plackup -r MyWeb::App/bin/app.psgi
Description

Main configuration file (plugins, modules etc):


● MyWeb::App/config.yml

Configuration files for production & development:


● MyWeb::App/environments/production.yml
● MyWeb::App/environments/development.yml
(defines what to report, where to report etc.
Description

Templates & Layouts:

● MyWeb::App/views/index.tt
● MyWeb::App/views/layouts/main.tt

(Templates are page portions/scraps and layouts


are full page designs)
Description

● MyWeb::App/public/javascripts/jquery.js
● MyWeb::App/public/css/style.css
● MyWeb::App/public/css/error.css
● MyWeb::App/public/images/...
 Javascript (dancer2 ships with jsquery)
 Cascade style sheets
 Images (for default design)
Description

● MyWeb::App/public/500.html
● MyWeb::App/public/404.html
(Pages for 500 and 404 errors)

● MyWeb::App/public/dispatch.fcgi
● MyWeb::App/public/dispatch.cgi
(Wrappers to cofigure fast-cgi & cgi backends)
Description

● MyWeb::App/MakeFile.PL
(Main module MakeFile, useful to make module of
your application)
● MyWeb::App/t/002_index_route.t
● MyWeb::App/t/001_base.t
(test suite)
● MyWeb::App/lib/MyWeb-App.pm (application)
ROUTES

get '/hello/:name' => sub {


return "Hi there " . params-
>{name};
};
A route declaration indicates for which HTTP
method(s) it is valid, the path it matches (e.g.
/hello/:computer), and a coderef to execute, which
returns the response.
Handling multiple HTTP request methods

Routes can use any to match all, or a specified list of HTTP


methods.

The following will match any HTTP request to the path /myaction:
any '/myaction' => sub {
# code
}
GET/POST

The following will match GET or POST requests to


/myaction:
any ['get', 'post'] => '/myaction' =>
sub {
# code
};
There are 8 defined HTTP verbs defined OPTIONS, GET, HEAD,
POST, PUT, DELETE, TRACE, CONNECT.
Retrieving request parameters

The params keyword returns a hashref of request


parameters; these will be parameters supplied on the query
string, within the path itself (with named placeholders), and,
for HTTP POST requests, the content of the POST body.
get '/company/view/:companyid' => sub {
my $company_id = params->{companyid};
# Look up the company and return appropriate
page
};
Before hooks - processed before a request

A before hook declares code which should be handled before


a request is passed to the appropriate route.
hook 'before' => sub {
var note => 'Hi there';
request->path_info('/foo/oversee')
};
Routes

get '/foo/*' => sub {


my ($match) = splat; # 'oversee';
vars->{note}; # 'Hi there'
};
The above declares a before hook which uses var to set a
variable which will later be available within the route handler,
then amends the path of the request to /foo/oversee; this
means that, whatever path was requested, it will be treated as
though the path requested was /foo/oversee.
Default route

In case you want to avoid a 404 error, or handle


multiple routes in the same way and you don't feel
like configuring all of them, you can set up a
default route handler.
The default route handler will handle any request
that doesn't get served by any other route.
All you need to do is set up the following route as
the last route:
Default route
any qr{.*} => sub {
status 'not_found';
template 'special_404', { path => request-
>path };
};
Then you can set up the template as such:
You tried to reach <% path %>, but it is unavailable at the moment.

Please try again or contact us at our email at


<...>.
Handling Sessions

To make use of sessions you must first enable the


session engine. Pick the session engine you want
to use, then declare it in your config file:
session: Simple (or)
Session: YAML (or)
Inside the code,
set session => 'YAML';
Storing/Retrieving data from
session
Storing data in the session
session varname => 'value';

Retrieving data from the session


session('varname')
Or, alternatively,
session->{varname}
Controlling where sessions are stored

For disc-based session back ends like Dancer::Session::YAML,


Dancer::Session::Storable etc, session files are written to the
session dir specified by the session_dir setting, which defaults
to appdir/sessions.
If you need to control where session files are created, you can do
so quickly and easily within your config file. For example:
session_dir: /tmp/dancer-sessions
If the directory you specify does not exist, Dancer will attempt to
create it for you.
Destroying a session

When you're done with your session, you can


destroy it:
session->destroy

Retrieve complete hash stored in session


Get complete hash stored in session:
my $hash = session;
Using templates - views and layouts

Views
It's possible to render the action's content with a template,
this is called a view. The `appdir/views' directory is the place
where views are located.
You can change this location by changing the setting 'views'.
By default, the internal template engine
Dancer::Template::Simple is used, but you may want to
upgrade to Template::Toolkit. If you do so, you have to enable
this engine in your settings as explained in
Dancer::Template::TemplateToolkit. If you do so, you'll also
have to import the Template module in your application code
Using templates - views and layouts

Note that, by default, Dancer configures the Template::Toolkit


engine to use <% %> brackets instead of its default [% %]
brackets. You can change this by using the following in your config
file:
template: template_toolkit
engines:
template_toolkit:
start_tag: '[%'
stop_tag: '%]'
All views must have a '.tt' extension. This may change in the future.
Layout

A layout is a special view, located in the 'layouts'


directory (inside the views directory) which must
have a token named 'content'. That token marks
the place to render the action view. This lets you
define a global layout for your actions, and have
each individual view contain only the specific
content. This is a good thing to avoid lots of
needless duplication of HTML :)
Here is an example of a layout:
views/layouts/main.tt :
Layout

<html>

<head>...</head>

<body>

<div id="header">

...

</div>

<div id="content">

<% content %>

</div>

</body>

</html>
Layout

You can tell your app which layout to use with


layout: name in the config file, or within your
code:
set layout => 'main';
Template and unicode

If you use Plack and have some unicode problem with your
Dancer application, don't forget to check if you have set your
template engine to use unicode, and set the default charset to
UTF-8. So, if you are using template toolkit, your config.yml
will look like this:
charset: UTF-8
engines:
template_toolkit:
ENCODING: utf8
Configuration Option

To use sessions in our application, we have to tell


Dancer2 to activate the session handler and
initialize a session manager. To do that, we add
some configuration directives toward the top of
our 'dancr.pl' file. But there are more options than
just the session engine we want to set.
Configuration Options

set 'database' => File::Spec-


>catfile(File::Spec->tmpdir(), 'dancr.db');
set 'session' => 'Simple';
set 'template' => 'template_toolkit';
set 'logger' => 'console';
set 'log' => 'debug';
set 'show_errors' => 1;
set 'startup_info' => 1;
set 'warnings' => 1;
Configuration Options

Accessing configuration information from your app


A Dancer application can use the 'config' keyword
to easily access the settings within its config file,
for instance:
get '/appname' => sub {
return "This is " . config-
>{appname};
};
Serving Static Files

In Dancer2, static files should go into the public/ directory, but in the
application itself be sure to omit the public/ element from the path. For
example, the stylesheet for Dancr lives in
dancr/public/css/style.css but is served from
http://localhost:3000/css/style.css.
If you wanted to build a mostly static web site you could simply write
route handlers like this one:
get '/' => sub {
send_file 'index.html';
};
where index.html would live in your public/ directory.
send_file does exactly what it says: it loads a static file, then sends
the contents of that file to the user.
Writing a REST application

With Dancer, it's easy to write REST applications.


Dancer provides helpers to serialize and
deserialize for the following data formats:
JSON/YAML/XML/Data::Dumper
To activate this feature, you only have to set the serializer setting to
the format you require, for instance in your config.yml:
serializer: JSON
Or right in your code:
set serializer => 'JSON';
Rest Application

From now, all HashRefs or ArrayRefs returned by


a route will be serialized to the format you chose,
and all data received from POST or PUT requests
will be automatically deserialized.

You might also like