package Dancer::Config

package Dancer::Config,第1张

概述package Dancer::Config;use strict;use warnings;use base 'Exporter';use vars '@EXPORT_OK';use Dancer::Config::Object 'hashref_to_object';use Dancer::Deprecation;use Dancer::Template;
package Dancer::Config;use strict;use warnings;use base 'Exporter';use vars '@EXPORT_OK';use Dancer::Config::Object 'hashref_to_object';use Dancer::Deprecation;use Dancer::Template;use Dancer::ModuleLoader;use Dancer::fileUtils 'path';use Carp;use Dancer::Exception qw(:all);use Encode;@EXPORT_OK = qw(setting);my $SETTINGS = {};# mergeable settingsmy %MERGEABLE = map { ($_ => 1) } qw( plugins handlers );my %_LOADED;sub settings {$SETTINGS}my $setters = {    logger => sub {        my ($setting,$value) = @_;        Dancer::Logger->init($value,settings());    },log_file => sub {        Dancer::Logger->init(setting("logger"),setting());    },session => sub {        my ($setting,$value) = @_;        Dancer::Session->init($value,template => sub {        my ($setting,$value) = @_;        Dancer::Template->init($value,route_cache => sub {        my ($setting,$value) = @_;        require Dancer::Route::Cache;        Dancer::Route::Cache->reset();    },serializer => sub {        my ($setting,$value) = @_;        require Dancer::Serializer;        Dancer::Serializer->init($value);    },import_warnings => sub {        my ($setting,$value) = @_;        $^W = $value ? 1 : 0;    },traces => sub {        my ($setting,$traces) = @_;        $Dancer::Exception::Verbose = $traces ? 1 : 0;    },};$setters->{log_path} = $setters->{log_file};my $normalizers = {    charset => sub {        my ($setting,$charset) = @_;        length($charset || '')          or return $charset;        my $enCoding = Encode::find_enCoding($charset);        defined $enCoding          or raise core_config => "Charset defined in configuration is wrong : Couldn't IDentify '$charset'";        my $name = $enCoding->name;        # Perl makes a distinction between the usual perl utf8,and the strict        # utf8 charset. But we don't want to make this distinction        $name eq 'utf-8-strict'          and $name = 'utf-8';        return $name;    },};sub normalize_setting {    my ($class,$setting,$value) = @_;    $value = $normalizers->{$setting}->($setting,$value)      if exists $normalizers->{$setting};    return $value;}# public accessor for get/setsub setting {    if (@_ == 1) {        return _get_setting(shift @_);    }    else {        # can be useful for deBUG! Use Logger,instead?        dIE "Odd number in 'set' assignment" unless scalar @_ % 2 == 0;        my $count = 0;        while (@_) {            my $setting = shift;            my $value   = shift;            _set_setting  ($setting,$value);            # At the moment,with any kind of hIErarchical setter,# there is no case where the same trigger will be run more            # than once. If/when a hIErarchical setter is implemented,# we should create a List of the hooks that should be run,# and run them at the end of this while,only (efficIEncy            # purposes).            _trigger_hooks($setting,$value);            $count++        }        return $count; # just to return anything,the number of items set.    }}sub _trigger_hooks {    my ($setting,$value) = @_;    $setters->{$setting}->(@_) if defined $setters->{$setting};}sub _set_setting {    my ($setting,$value) = @_;    return unless @_ == 2;    # normalize the value if needed    $value = Dancer::Config->normalize_setting($setting,$value);    $SETTINGS->{$setting} = $value;    return $value;}sub _get_setting {    my $setting = shift;    return $SETTINGS->{$setting};}sub conffile { path(setting('confdir') || setting('appdir'),'config.yml') }sub environment_file {    my $env = setting('environment');    # XXX for compatibility reason,we duplicate the code from `init_envdir` here    # we don't kNow how if some application don't already do some weird stuff like    # the test in `t/15_plugins/02_config.t`.    my $envdir = setting('envdir') || path(setting('appdir'),'environments');    return path($envdir,"$env.yml");}sub init_confdir {    return setting('confdir') if setting('confdir');    setting confdir => $ENV{DANCER_confdIR} || setting('appdir');}sub init_envdir {    return setting('envdir') if setting('envdir');    setting envdir => $ENV{DANCER_ENVDIR} || path(setting('appdir'),'environments');}sub load {    init_confdir();    init_envdir();    # look for the conffile    return 1 unless -f conffile;    # load YAML    my ( $result,$error ) = Dancer::ModuleLoader->load('YAML');    if ( not $result ) {        confess "Configuration file found but Could not load YAML: $error";    }    if (!$_LOADED{conffile()}) {        load_settings_from_yaml(conffile);        $_LOADED{conffile()}++;    }    my $env = environment_file;    if (-f $env && !$_LOADED{$env}) {        load_settings_from_yaml($env);        $_LOADED{$env}++;    }    foreach my $key (grep { $setters->{$_} } keys %$SETTINGS) {        $setters->{$key}->($key,$SETTINGS->{$key});    }    if ( $SETTINGS->{strict_config} ) {        $SETTINGS = hashref_to_object($SETTINGS);    }    return 1;}sub load_settings_from_yaml {    my ($file) = @_;    my $config;    eval { $config = YAML::Loadfile($file) };    if (my $err = $@ || (!$config)) {        confess "Unable to parse the configuration file: $file: $@";    }    for my $key (keys %{$config}) {        if ($MERGEABLE{$key}) {            my $setting = setting($key);            $setting->{$_} = $config->{$key}{$_} for keys %{$config->{$key}};        }        else {            _set_setting($key,$config->{$key});        }    }    return scalar(keys %$config);}sub load_default_settings {    $SETTINGS->{server}        ||= $ENV{DANCER_SERVER}        || '0.0.0.0';    $SETTINGS->{port}          ||= $ENV{DANCER_PORT}          || '3000';    $SETTINGS->{content_type}  ||= $ENV{DANCER_CONTENT_TYPE}  || 'text/HTML';    $SETTINGS->{charset}       ||= $ENV{DANCER_CHARSET}       || '';    $SETTINGS->{startup_info}  ||= $ENV{DANCER_STARTUP_INFO}  || 1;    $SETTINGS->{daemon}        ||= $ENV{DANCER_DAEMON}        || 0;    $SETTINGS->{apphandler}    ||= $ENV{DANCER_APPHANDLER}    || 'Standalone';    $SETTINGS->{warnings}      ||= $ENV{DANCER_WARNINGS}      || 0;    $SETTINGS->{auto_reload}   ||= $ENV{DANCER_auto_RELOAD}   || 0;    $SETTINGS->{traces}        ||= $ENV{DANCER_TRACES}        || 0;    $SETTINGS->{server_tokens} ||= $ENV{DANCER_SERVER_TOKENS} || 1;    $SETTINGS->{logger}        ||= $ENV{DANCER_LOGGER}        || 'file';    $SETTINGS->{environment}   ||=         $ENV{DANCER_ENVIRONMENT}      || $ENV{PLACK_ENV}      || 'development';    setting $_ => {} for keys %MERGEABLE;    setting template        => 'simple';    setting import_warnings => 1;}load_default_settings();1;__END__=pod=head1 nameDancer::Config - how to configure Dancer to suit your needs=head1 DESCRIPTIONDancer::Config handles reading and changing the configuration of your Dancerapps.  The documentation for this module aims to describe how to changesettings,and which settings are available.=head1 SETTINGSYou can change a setting with the keyword B<set>,like the following:    use Dancer;    # changing default settings    set port         => 8080;    set content_type => 'text/plain';    set startup_info => 0;A better way of defining settings exists: using YAML file. For this to bepossible,you have to install the L<YAML> module. If a file named B<config.yml>exists in the application directory,it will be loaded,as a setting group.The same is done for the environment file located in the B<environments>directory.=head1 SUPPORTED SETTINGS=head2 Run mode and Listening interface/port=head3 server (string)The IP address that the Dancer app should bind to.  Default is 0.0.0.0,i.e.bind to all available interfaces.=head3 port (int)The port Dancer will Listen to.Default value is 3000. This setting can be changed on the command-line with theB<--port> switch.=head3 daemon (boolean)If set to true,runs the standalone webserver in the background.This setting can be changed on the command-line with the B<--daemon> flag.=head3 behind_proxy (boolean)If set to true,Dancer will look to C<X-Forwarded-Protocol> andC<X-Forwarded-host> when constructing URLs (for example,when usingC<redirect>. This is useful if your application is behind a proxy.=head2 Content type / character set=head3 content_type (string)The default content type of outgoing content.Default value is 'text/HTML'.=head3 charset (string)This setting has multiple effects:=over=item *It sets the default charset of outgoing content. C<charset=> item will beadded to Content-Type response header.=item *It makes Unicode bodIEs in http responses of C<text/*> types to be encoded tothis charset.=item *It also indicates to Dancer in which charset the static files and templates areencoded.=item *If you're using L<Dancer::Plugin::Database>,UTF-8 support will automatically beenabled for your database - see L<Dancer::Plugin::Database/"autoMATIC UTF-8 SUPPORT">=backDefault value is empty which means don't do anything. http responseswithout charset will be interpreted as ISO-8859-1 by most clIEnts.You can cancel any charset processing by specifying your own charsetin Content-Type header or by ensuring that response body leaves yourhandler without Unicode flag set (by enCoding it into some 8bitcharset,for example).Also,since automatically serialized JsON responses haveC<application/Json> Content-Type,you should always encode them byhand.=head3 default_mime_type (string)Dancer's L<Dancer::MIME> module uses C<application/data> as a defaultmime type. This setting lets the user change it. For example,if youhave a lot of files being served in the B<public> folder that do nothave an extension,and are text files,set the C<default_mime_type> toC<text/plain>.=head2 file / directory locations=head3 environment (string)This is the name of the environment that should be used. StandardDancer applications have a C<environments> folder with specificconfiguration files for different environments (usually developmentand production environments). They specify different kind of errorreporting,deployment details,etc. These files are read after thegeneric C<config.yml> configuration file.The running environment can be set with:   set environment => "production";Note that this variable is also used as a default value if othervalues are not defined.=head3 appdir (directory)This is the path where your application will live.  It's where Dancerwill look by default for your config files,templates and staticcontent.It is typically set by C<use Dancer> to use the same directory as yourscript.=head3 public (directory)This is the directory,where static files are stored. Any existingfile in that directory will be served as a static file,beforematching any route.By default,it points to $appdir/public.=head3 vIEws (directory)This is the directory where your templates and layouts live.  It's the"vIEw" part of MVC (model,vIEw,controller).This defaults to $appdir/vIEws.=head2 Templating & layouts=head3 templateAllows you to configure which template engine should be used.  For instance,touse Template Toolkit,add the following to C<config.yml>:    template: template_toolkit=head3 layout (string)The name of the layout to use when rendering vIEw. Dancer will look fora matching template in the directory $vIEws/layout.Your can overrIDe the default layout using the third argument of theC<template> keyword. Check C<Dancer> manpage for details.=head2 Logging,deBUGging and error handling=head2 strict_config (boolean,default: false)If true,C<config> will return an object instead of a hash reference. SeeL<Dancer::Config::Object> for more information.=head3 import_warnings (boolean,default: enabled)If true,or not present,C<use warnings> will be in effect in scripts in whichyou import C<Dancer>.  Set to a false value to disable this.=head3 startup_info (boolean)If set to true,prints a banner at the server start with information such asversions and the environment (or "dancerfloor").Conforms to the environment variable DANCER_STARTUP_INFO.=head3 warnings (boolean)If set to true,tells Dancer to consIDer all warnings as blocking errors.=head3 traces (boolean)If set to true,Dancer will display full stack traces when a warning or a dIEoccurs. (Internally sets Carp::Verbose). Default to false.=head3 server_tokens (boolean)If set to true,Dancer will add an "X-Powered-By" header and also appendthe Dancer version to the "Server" header. Default to true.You can also use the environment variable C<DANCER_SERVER_TOKENS>.=head3 log_path (string)Folder where the ``file C<logger>'' saves logfiles.=head3 log_file (string)name of the file to create when ``file C<logger>'' is active. Itdefaults to the C<environment> setting contents.=head3 logger (enum)Select which logger to use.  For example,to write to log files in C<log_path>:    logger: fileOr to direct log messages to the console from which you started your Dancer appin standalone mode,logger: consoleVarIoUs other logger backends are available on CPAN,including L<Dancer::Logger::Syslog>,L<Dancer::Logger::Log4perl>,L<Dancer::Logger::Psgi>(which can,with the aID of Plack mIDdlewares,send log messages to a browser'sconsole window) and others.=head3 log (enum)Tells which log messages should be actually logged. Possible values areB<core>,B<deBUG>,B<warning> or B<error>.=over 4=item B<core> : all messages are logged,including some from Dancer itself=item B<deBUG> : all messages are logged=item B<info> : only info,warning and error messages are logged=item B<warning> : only warning and error messages are logged=item B<error> : only error messages are logged=backDuring development,you'll probably want to use C<deBUG> to see your own deBUGmessages,and C<core> if you need to see what Dancer is doing.  In production,you'll likely want C<error> or C<warning> only,for less-chatty logs.=head3 show_errors (boolean)If set to true,Dancer will render a detailed deBUG screen whenever an error iscaught. If set to false,Dancer will render the default error page,using$public/$error_code.HTML if it exists or the template specifIEd by theC<error_template> setting.The error screen attempts to sanitise sensitive looking information (passwords /card numbers in the request,etc) but you still should not have show_errorsenabled whilst in production,as there is still a risk of divulging details.=head3 error_template (template path)This setting lets you specify a template to be used in case of runtimeerror. At the present moment the template can use three variables:=over 4=item B<Title>The error Title.=item B<message>The error message.=item B<code>The code throwing that error.=back=head3 auto_reload (boolean)Requires L<Module::Refresh> and L<Clone>.If set to true,Dancer will reload the route handlers whenever the file wherethey are defined is changed. This is very useful in development environment butB<should not be enabled in production>. Enabling this flag in production yIEldsa major negative effect on performance because of L<Module::Refresh>.When this flag is set,you don't have to restart your webserver whenever youmake a change in a route handler.Note that L<Module::Refresh> only operates on files in C<%INC>,so if the scriptyour Dancer app is started from changes,even with auto_reload enabled,you willstill not see the changes reflected until you start your app.=head2 Session engine=head3 session (enum)This setting lets you enable a session engine for your web application. Bedefault,sessions are Disabled in Dancer,you must choose a session engine touse them.See L<Dancer::Session> for supported engines and their respective configuration.=head3 session_expiresThe session expiry time in seconds,or as e.g. "2 hours" (seeL<Dancer::cookie/expires>.  By default,there is no specific expiry time.=head3 session_nameThe name of the cookie to store the session ID in.  Defaults toC<dancer.session>.  This can be overrIDden by certain session engines.=head3 session_secureThe user's session ID is stored in a cookie.  If the C<session_secure> settingis set to a true value,the cookie will be marked as secure,meaning it shouldonly be sent over httpS connections.=head3 session_is_http_onlyThis setting defaults to 1 and instructs the session cookie to becreated with the C<httpOnly> option active,meaning that JavaScriptwill not be able to access to its value.=head2 auto_page (boolean)For simple pages where you're not doing anything dynamic,but stillwant to use the template engine to provIDe headers etc,you can usethe auto_page feature to avoID the need to create a route for eachpage.With C<auto_page> enabled,if the requested path does not match anyspecific route,Dancer will check in the vIEws directory for amatching template,and use it to satisfy the request if found.Simply enable auto_page in your config:    auto_page: 1Then,if you request C</foo/bar>,Dancer will look in the vIEws dir forC</foo/bar.tt>.Dancer will honor your C<before_template_render> code,and all defaultvariables. They will be accessible and interpolated on automaticserved pages.=head2 DANCER_confdIR and DANCER_ENVDIRIt's possible to set the configuration directory and environment directory using this twoenvironment variables. Setting `DANCER_confdIR` will have the same effect as doing    set confdir => '/path/to/confdir'and setting `DANCER_ENVDIR` will be similar to:    set envdir => '/path/to/environments'=head1 AUTHORThis module has been written by Alexis SukrIEh <sukria@cpan.org> and others,see the AUTHORS file that comes with this distribution for details.=head1 liCENSEThis module is free software and is released under the same terms as Perlitself.=head1 SEE ALSOL<Dancer>=cut
@H_404_9@ 总结

以上是内存溢出为你收集整理的package Dancer::Config全部内容,希望文章能够帮你解决package Dancer::Config所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1283440.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-09
下一篇 2022-06-09

发表评论

登录后才能评论

评论列表(0条)

保存