Dancer::Cookbook
[[meta title="Dancer2::Cookbook - Example-driven quick-start to the Dancer2 web framework"]] [[meta author="Dancer Core Developers"]]
NAME
Dancer2::Cookbook - Example-driven quick-start to the Dancer2 web framework
VERSION
version 0.150000
DESCRIPTION
A quick-start guide with examples to get you up and running with the Dancer2 web framework.
BEGINNER'S DANCE
Your first Dancer2 web app
Dancer2 has been designed to be easy to work with - it's trivial to write a simple web app, but still has the power to work with larger projects. To start with, let's make an incredibly simple "Hello World" example:
Yes - the above is a fully-functioning web app; running that script will launch a webserver listening on the default port (3000); now you can make a request
(or the name of the machine you ran it on, if it's not your local system), and it will say hello. The :name
part is a named parameter within the route specification, whose value is made available through params
more on that later.
Note that you don't need to use the strict
and warnings
pragma, they are already loaded by Dancer2.
If you really do not want the warnings
pragma (for example, due to an undesired warning about use of undef values), add a no warnings
pragma to the appropriate block in your module or psgi file.
Starting a Dancer2 project
The first simple example is fine for trivial projects, but for anything more complex, you'll want a more maintainable solution - enter the dancer2
helper script, which will build the framework of your application with a single command:
As you can see, it creates a directory named after the name of the app, along with a configuration file, a views directory (where your templates and layouts will live), an environments directory (where environment-specific settings live), a module containing the actual guts of your application, a script to start it - or to run your web app via Plack/PSGI - more on that later.
DANCE ROUTINES: ROUTES
Declaring routes
To control what happens when a web request is received by your webapp, you'll need to declare routes
. A route declaration indicates which HTTP method(s) it is valid for, the path it matches (e.g. /foo/bar), and a coderef to execute, which returns the response.
The above route specifies that, for GET requests to '/hello/...', the code block provided should be executed.
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:
The following will match GET or POST requests to /myaction:
For convenience, any route which matches GET requests will also match HEAD requests.
Retrieving request parameters
The L<params|Dancer2/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 HTTTP POST requests, the content of the POST body.
Named parameters in route path declarations
As seen above, you can use :somename
in a route's path to capture part of the path; this will become available by calling L<params|Dancer2/params>.
So, for a web app where you want to display information on a company, you might use something like:
Wildcard path matching and splat
You can also declare wildcards in a path, and retrieve the values they matched with the L<splat|Dancer2/splat> keyword:
Before filters - processed before a request
A L<before|Dancer2/before> filter declares code which should be handled before a request is passed to the appropriate route.
The above declares a before filter which uses forward
to do an internal redirect to /foo/oversee
with an additional parameter note
.
See also the L<hook|Dancer2/hook> hook keyword.
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:
Then you can set up the template as such:
Using the auto_page feature for automatic route creation
For simple "static" pages, you can simply enable the auto_page
config setting; this means that you need not declare a route handler for those pages; if a request is for /foo/bar
, Dancer2 will check for a matching view (e.g. /foo/bar.tt
and render it with the default layout etc if found. For full details, see the documentation for the L<auto_page setting|Dancer2::Config/"auto_page">.
Why should I use the Ajax plugin
As an Ajax query is just a HTTP query, it's similar to a GET or POST route. You may ask yourself why you may want to use the ajax
keyword (from the L plugin) instead of a simple get
.
Let's say you have a path like '/user/:user' in your application. You may want to be able to serve this page, with a layout and HTML content. But you may also want to be able to call this same url from a javascript query using Ajax.
So, instead of having the following code:
you can have
and
Because it's an ajax query, you know you need to return a xml content, so the content type of the response is set for you.
Using the prefix feature to split your application
For better maintainability, you may want to separate some of your application components to different packages. Let's say we have a simple web app with an admin section, and want to maintain this in a different package:
The following routes will be generated for us:
get /
get /admin/
head /
head /admin/
By default, a separate application is created for every package that uses Dancer2. The appname
tag is used to collect routes and hooks into a single Dancer2 application. In the above example, appname => 'myapp'
adds the routes from myapp::admin
to the routes of the app myapp
.
When using multiple applications please ensure that your path definitions do not overlap. Eg, if using a default route as described above, once a request is matched to the default route then no further routes (or applications) would be reached.
MUSCLE MEMORY: STORING DATA
Handling sessions
It's common to want to use sessions to give your web applications state; for instance, allowing a user to log in, creating a session, and checking that session on subsequent requests.
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 like this:
The L backend implements very simple in-memory session storage. This will be fast and useful for testing, but sessions do not persist between restarts of your app.
You can also use the L backend included with Dancer2, which stores session data on disc in YAML files (since YAML is a nice human-readable format, it makes inspecting the contents of sessions a breeze):
Or, to enable session support from within your code,
(Controlling settings is best done from your config file, though). 'YAML' in the example is the session backend to use; this is shorthand for L. There are other session backends you may wish to use, for instance L, but the YAML backend is a simple and easy to use example which stores session data in a YAML file in sessions).
You can then use the L<session|Dancer2/session> keyword to manipulate the session:
Storing data in the session
Storing data in the session is as easy as:
Retrieving data from the session
Retrieving data from the session is as easy as:
Or, alternatively,
Controlling where sessions are stored
For disc-based session back ends like L, L etc, session files are written to the session dir specified by the session_dir
setting, which defaults to ./sessions
if not specifically set.
If you need to control where session files are created, you can do so quickly and easily within your config file, for example:
If the directory you specify does not exist, Dancer2 will attempt to create it for you.
Destroying a session
When you're done with your session, you can destroy it:
Sessions and logging in
A common requirement is to check the user is logged in, and, if not, require them to log in before continuing.
This can easily be handled with a before filter to check their session:
Here is what the corresponding login.tt
file should look like. You should place it in a directory called views:
Of course, you'll probably want to validate your users against a database table, or maybe via IMAP/LDAP/SSH/POP3/local system accounts via PAM etc. L is probably a good starting point here!
A simple working example of handling authentication against a database table yourself (using L which provides the database
keyword, and L to handle salted hashed passwords (well, you wouldn't store your users passwords in the clear, would you?)) follows:
Retrieve complete hash stored in session
Get complete hash stored in session:
APPEARANCE: TEMPLATES AND LAYOUTS
Returning plain content is all well and good for examples or trivial apps, but soon you'll want to use templates to maintain separation between your code and your content. Dancer2 makes this easy.
Your route handlers can use the L<template|Dancer2::Manual/template> keyword to render templates.
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'.
All views must have a '.tt' extension. This may change in the future.
In order to render a view, just call the L<template|Dancer2::Manual/template> keyword at the end of the action by giving the view name and the HASHREF of tokens to interpolate in the view (note that for convenience, the request, session, params and vars are automatically accessible in the view, named request
, session
, params
and vars
) - for example:
The template hello.tt
could contain, for example:
For a full list of the tokens automatically added to your template (like session
, request
and vars
, refer to L).
Layouts
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 where 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
:
... ... [% content %]
You can tell your app which layout to use with layout: name
in the config file, or within your code:
You can control which layout to use (or whether to use a layout at all) for a specific request without altering the layout setting by passing an options hashref as the third param to the template keyword:
If your application is not mounted under root (/), you can use a before_template instead of hardcoding the path to your application for your css, images and javascript:
Then in your layout, modify your css inclusion as follows:
From now on, you can mount your application wherever you want, without any further modification of the css inclusion
Templates and unicode
If you use L and have some unicode problem with your Dancer2 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 file will look like this:
TT's WRAPPER directive in Dancer2
Dancer2 already provides a WRAPPER-like ability, which we call a "layout". The reason we do not use TT's WRAPPER (which also makes us incompatible with it) is because not all template systems support it. Actually, most don't.
However, you might want to use it, and be able to define META variables and regular L variables.
These few steps will get you there:
Disable the layout in Dancer2
You can do this by simply commenting (or removing) the layout
configuration in the config file.
Use Template Toolkit template engine
Change the configuration of the template to Template Toolkit:
Tell the Template Toolkit engine who's your wrapper
in config.yml
...
engines: template: template_toolkit: WRAPPER: layouts/main.tt
Done! Everything will work fine out of the box, including variables and META variables.
SETTING THE STAGE: CONFIGURATION AND LOGGING
Configuration and environments
Configuring a Dancer2 application can be done in many ways. The easiest one (and maybe the dirtiest) is to put all your settings statements at the top of your script, before calling the dance() method.
Other ways are possible, you can define all your settings in the file appdir/config.yml
. For this, you must have installed the YAML module, and of course, write the config file in YAML.
That's better than the first option, but it's still not perfect as you can't switch easily from an environment to another without rewriting the config file.
An even solution is to have one config.yml file with default global settings, like the following:
And then write as many environment files as you like in appdir/environments
. That way, the appropriate environment config file will be loaded according to the running environment (if none is specified, it will be 'development').
Note that you can change the running environment using the --environment
command line switch.
Typically, you'll want to set the following values in a development config file:
And in a production one:
Accessing configuration information
From inside your application
A Dancer2 application can use the 'config' keyword to easily access the settings within its config file, for instance:
This makes keeping your application's settings all in one place simple and easy
you shouldn't need to worry about implementing all that yourself :)
From a separate script
You may well want to access your webapp's configuration from outside your webapp. You could, of course, use the YAML module of your choice and load your webapps's config.yml, but chances are that this is not convenient.
Use Dancer2 instead. Without any ado, magic or too big jumps, you can use the values from config.yml and some additional default values:
Note that config->{log}
should result undef error on a default scaffold since you did not load the environment and in the default scaffold log is defined in the environment and not in config.yml. Hence undef.
If you want to load an environment you need to tell Dancer2 where to look for it. One way to do so, is to tell Dancer2 where the webapp lives. From there Dancer2 deduces where the config.yml file is (typically $webapp/config.yml
).
By default Dancer2 loads development environment (typically $webapp/environment/development.yml
). In contrast to the example before, you do have a value from the development environment (environment/development.yml
) now. Also note that in the above example L and L are used. They are likely to be already loaded by Dancer2 anyways, so it's not a big overhead. You could just as well hand over a simple path for the app if you like that better, e.g.:
If you want to load an environment other than the default, try this:
By the way, you not only get values, you can also set values straightforward like we do above with config->{environment}='production'
. Of course, this value does not get written in any file; it only lives in memory and your webapp doesn't have access to it, but you can use it inside your script.
Logging
Configuring logging
It's possible to log messages generated by the application and by Dancer2 itself.
To start logging, select the logging engine you wish to use with the logger
setting; Dancer2 includes built-in log engines named file
and console
, which log to a logfile and to the console respectively.
To enable logging to a file, add the following to your config file:
Then you can choose which kind of messages you want to actually log:
If you're using the file
logging engine, a directory appdir/logs
will be created and will host one logfile per environment. The log message contains the time it was written, the PID of the current process, the message and the caller information (file and line).
Logging your own messages
Just call L<debug|Dancer2/debug>, L<info|Dancer2/info>, L<warning|Dancer2/warning> or L<error|Dancer2/error> with your message:
RESTING
Writing a REST application
With Dancer2, it's easy to write REST applications. Dancer2 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 file:
serializer: JSON
Or right in your code:
set serializer => 'JSON';
From now, all hash ref or array ref 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.
It's possible to let the client choose which serializer he want to use. For this, use the mutable serializer, and an appropriate serializer will be chosen from the Content-Type header.
It's also possible to return a custom error, using the L<send_error|Dancer2/send_error> keyword.. When you don't use a serializer, the send_error
function will take a string as first parameter (the message), and an optional HTTP code. When using a serializer, the message can be a string, an arrayref or a hashref:
The content of the error will be serialized using the appropriate serializer.
DANCER ON THE STAGE: DEPLOYMENT
Running stand-alone
At the simplest, your Dancer2 app can run standalone, operating as its own webserver using L.
Simply fire up your app:
Point your browser at it, and away you go!
This option can be useful for small personal web apps or internal apps, but if you want to make your app available to the world, it probably won't suit you.
Auto Reloading with Plack and Shotgun
To edit your files without the need to restart the webserver on each file change, simply start your Dancer2 app using L and L:
Point your browser at it. Files can now be changed in your favorite editor and the browser needs to be refreshed to see the saved changes.
Please note that this is not recommended for production for performance reasons. This is the Dancer2 replacement solution of the old Dancer experimental auto_reload
option.
On Windows, Shotgun loader is known to cause huge memory leaks in a fork-emulation layer. If you are aware of this and still want to run the loader, please use the following command:
CGI and Fast-CGI
In providing ultimate flexibility in terms of deployment, your Dancer2 app can be run as a simple cgi-script out-of-the-box. No additional web-server configuration needed. Your web server should recognize .cgi files and be able to serve Perl scripts. The Perl module L is required.
Running on Apache (CGI and FCGI)
Start by adding the following to your apache configuration (httpd.conf
or sites-available/*site*
):
ServerName www.example.com DocumentRoot /srv/www.example.com/public ServerAdmin you@example.com AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all AddHandler cgi-script .cgi RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ /dispatch.cgi$1 [QSA,L] ErrorLog /var/log/apache2/www.example.com-error.log CustomLog /var/log/apache2/www.example.com-access_log common
Note that when using fast-cgi your rewrite rule should be:
Here, the mod_rewrite magic for Pretty-URLs is directly put in Apache's configuration. But if your web server supports .htaccess files, you can drop those lines in a .htaccess file.
To check if your server supports mod_rewrite type apache2 -l
to list modules. To enable mod_rewrite (Debian), run a2enmod rewrite
. Place following code in a file called .htaccess in your application's root folder:
Now you can access your dancer application URLs as if you were using the embedded web server.
This option is a no-brainer, easy to setup, low maintenance but serves requests slower than all other options.
You can use the same technique to deploy with FastCGI, by just changing the line:
By:
Of course remember to update your rewrite rules, if you have set any:
Running under an appdir
If you want to deploy multiple applications under the same VirtualHost, using one application per directory for example, you can do the following.
This example uses the FastCGI dispatcher that comes with Dancer2, but you should be able to adapt this to use any other way of deployment described in this guide. The only purpose of this example is to show how to deploy multiple applications under the same base directory/virtualhost.
ServerName localhost DocumentRoot "/path/to/rootdir" RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all AddHandler fastcgi-script .fcgi RewriteRule /App1(.*)$ /App1/public/dispatch.fcgi$1 [QSA,L] RewriteRule /App2(.*)$ /App2/public/dispatch.fcgi$1 [QSA,L] ... RewriteRule /AppN(.*)$ /AppN/public/dispatch.fcgi$1 [QSA,L]
Of course, if your Apache configuration allows that, you can put the RewriteRules in a .htaccess file directly within the application's directory, which lets you add a new application without changing the Apache configuration.
Running on lighttpd (CGI)
To run as a CGI app on lighttpd, just create a soft link to the dispatch.cgi script (created when you run dancer -a MyApp) inside your system's cgi-bin folder. Make sure mod_cgi is enabled.
Running on lighttpd (FastCGI)
Make sure mod_fcgi is enabled. You also must have L installed.
This example configuration uses TCP/IP:
Launch your application:
This example configuration uses a socket:
Launch your application:
Plack middlewares
If you want to use Plack middlewares, you need to enable them using L as such:
The nice thing about this setup is that it will work seamlessly through Plack or through the internal web server.
You do not need to provide different files for either server.
Path-based middlewares
If you want to setup a middleware for a specific path, you can do that using L which uses L:
Running on Perl webservers with plackup
A number of Perl web servers supporting PSGI are available on cpan:
L
Starman
is a high performance web server, with support for preforking, signals, ...
L
Twiggy
is an AnyEvent
web server, it's light and fast.
L
Corona
is a Coro
based web server.
To start your application, just run plackup (see L and specific servers above for all available options):
$ plackup bin/app.pl $ plackup -E deployment -s Starman --workers=10 -p 5001 -a bin/app.pl
As you can see, the scaffolded Perl script for your app can be used as a PSGI startup file.
Enabling content compression
Content compression (gzip, deflate) can be easily enabled via a Plack middleware (see L<Plack/Plack::Middleware>): L. It's a middleware to encode the response body in gzip or deflate, based on Accept-Encoding HTTP request header.
Enable it as you would enable any Plack middleware. First you need to install L, then in the handler (usually app.psgi
) edit it to use L, as described above:
To test if content compression works, trace the HTTP request and response before and after enabling this middleware. Among other things, you should notice that the response is gzip or deflate encoded, and contains a header Content-Encoding
set to gzip
or deflate
Running multiple apps with Plack::Builder
You can use L to mount multiple Dancer2 applications on a L webserver like L.
Start by creating a simple app.psgi file:
and now use L
Currently this still demands the same appdir for both (default circumstance) but in a future version this will be easier to change while staying very simple to mount.
Running from Apache with Plack
You can run your app from Apache using PSGI (Plack), with a config like the following:
ServerName www.myapp.example.com ServerAlias myapp.example.com DocumentRoot /websites/myapp.example.com AllowOverride None Order allow,deny Allow from all SetHandler perl-script PerlResponseHandler Plack::Handler::Apache2 PerlSetVar psgi_app /websites/myapp.example.com/app.pl ErrorLog /websites/myapp.example.com/logs/error_log CustomLog /websites/myapp.example.com/logs/access_log common
To set the environment you want to use for your application (production or development), you can set it this way:
... SetEnv DANCER_ENVIRONMENT "production" ...
Creating a service
You can turn your app into proper service running in background using one of the following examples:
Using Ubic
L is an extensible perlish service manager. You can use it to start and stop any services, automatically start them on reboots or daemon failures, and implement custom status checks.
A basic PSGI service description (usually in /etc/ubic/service/application):
Run ubic start application
to start the service.
Using daemontools
daemontools is a collection of tools for managing UNIX services. You can use it to easily start/restart/stop services.
A basic script to start an application: (in /service/application/run)
Running stand-alone behind a proxy / load balancer
Another option would be to run your app stand-alone as described above, but then use a proxy or load balancer to accept incoming requests (on the standard port 80, say) and feed them to your Dancer2 app.
This could be achieved using various software; examples would include:
Using Apache's mod_proxy
You could set up a VirtualHost for your web app, and proxy all requests through to it:
ProxyPass / http://localhost:3000/ ProxyPassReverse / http://localhost:3000/
Or, if you want your webapp to share an existing VirtualHost, you could have it under a specified dir:
It is important for you to note that the Apache2 modules mod_proxy
and mod_proxy_http
must be enabled.
It is also important to set permissions for proxying for security purposes, below is an example.
Order allow,deny Allow from all
Using perlbal
It processes hundreds of millions of requests a day just for LiveJournal, Vox and TypePad and dozens of other "Web 2.0" applications.
It can also provide a management interface to let you see various information on requests handled etc.
It could easily be used to handle requests for your Dancer2 apps, too.
It can be easily installed from CPAN:
Once installed, you'll need to write a configuration file. See the examples provided with perlbal, but you'll probably want something like:
Using balance
It could be used simply to hand requests to a standalone Dancer2 app. You could even run several instances of your Dancer2 app, on the same machine or on several machines, and use a machine running balance to distribute the requests between them, for some serious heavy traffic handling!
To listen on port 80, and send requests to a Dancer2 app on port 3000:
To listen on a specified IP only on port 80, and distribute requests between multiple Dancer2 apps on multiple other machines:
Using Lighttpd
You can use Lighttp's mod_proxy:
This configuration will proxy all request to the /application path to the path / on localhost:3000.
Using Nginx
with Nginx:
You will need plackup to start a worker listening on a socket :
A good way to start this is to use daemontools
and place this line with all environments variables in the "run" file.
AUTHOR
Dancer Core Developers
COPYRIGHT AND LICENSE
This software is copyright (c) 2014 by Alexis Sukrieh.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.henq@PORTEGE-R600:~$
Last updated
Was this helpful?