Программирование Perl CGI: создание динамических веб-страниц

Modern Perl Web Frameworks

While the old wave of web development may have made the CGI.pm module
central, modern Perl web programming follows a stricter separation of business
logic, URL and request routing, and output. The days of slinging a string here,
an array there, a Perl hash yonder, declaring every variable at the top of the
program, and maybe making a subroutine are gone. The Perl world has seen the
value of abstraction and ways to mechanize away boilerplate. Perl has dozens
of frameworks and toolkits designed to make web development and deployment
simpler.

Any of a dozen of these frameworks will help you do great things, but three
in particular stand out. You can build web sites and web applications of
tremendous value with all three. These are neither the only good possibilities
(think of POE or Jifty or Continuity or…) nor the only mechanisms for web
programming with Perl (see Mechanize or LWP or Mojo::UserAgent for more). Yet
if you want three good options to choose between, start here.

Catalyst

The Catalyst framework is a
flexible and powerful system for building small to large web apps. It
uses the Moose object system to provide
great APIs for extension and further development. It’s the most mature of the
modern top Perl web frameworks, yet it retains its flexibility and vibrancy.
In particular, its plugin and extension ecosystem allows it to evolve to
provide new and essential features.

Catalyst has embraced the Plack/PSGI standard for Perl web deployment and
recent versions are exploring high-scalability, event-based request handling
models.

Dancer

The Dancer framework is deliberately
minimal in syntax and scope, but it also has a vibrant plugin ecosystem. Dancer
particularly excels for smaller sites and applications, though good programmers
can build larger things with it.

The first version of Dancer was easy to use. Dancer 2 continues that ease
while improving the internals and robustness of applications.

Mojolicious

The Mojolicious (Mojo) framework has a
real-time design based on high performance event handling. Its focus is solving
new and interesting problems in simple and effective ways, and the project has
produced a lot of new code that does old things in better ways.

In particular, Mojolicious goes to great lengths to support new web
standards, such as CSS 3, web sockets, and HTTP 2.

Where Catalyst embraces the CPAN fully, Mojolicious by design provides most
of what an average app might need in a single download. It’s still fully
compatible with the CPAN, but the intention is to provide good working defaults
in a package that’s easy to start with. Mojo’s fans are quick to praise it as
fun to develop.

A modern Perl web developer should be familiar with at least one of these
frameworks.

Обработка данных в Perl скрипте

Perl является мощным языком программирования для обработки данных. В Perl скрипте можно использовать множество инструментов для обработки и манипулирования данными различных форматов.

Для обработки текстовых данных Perl предоставляет множество функций работы со строками. Среди наиболее часто используемых можно выделить функции для поиска и замены текста, сортировки строк, вывода текста с различной форматированием и многое другое.

Для обработки данных, представленных в форматах XML и JSON, существует множество модулей Perl. Например, модуль XML::Simple позволяет легко считывать и записывать XML-файлы, а модуль JSON позволяет манипулировать данными в JSON-формате.

Для работы с базами данных в Perl существует множество модулей, позволяющих работать с различными типами баз данных (MySQL, PostgreSQL, Oracle и др.). С помощью этих модулей можно выполнять различные операции с данными, такие как добавление, удаление, редактирование и выборка.

В целом, благодаря мощным инструментам для обработки данных, Perl является чрезвычайно удобным языком для работы с данными различных форматов.

Разбор параметров запроса

Для обработки запросов на сервере, переданных пользователем через URL, необходимо разобрать параметры запроса. Каждый параметр состоит из имени и значения, разделенных знаком равенства (=).

Для этого можно использовать метод CGI.pm — param (), который возвращает значение параметра по его имени. Например, чтобы получить значение параметра «id», необходимо выполнить следующий код:

use CGI;

my $q = CGI->new();

my $id = $q->param(‘id’);

Параметры запроса могут передаваться в URL в двух форматах: GET и POST. В GET-запросе параметры передаются в URL после знака вопроса (?), а в POST-запросе — в теле запроса.

Чтобы получить все параметры запроса, можно использовать методы CGI.pm — param_names () и param (). Метод param_names () возвращает список имен параметров, а метод param () — данные параметров в виде ассоциативного массива. Например:

my @param_names = $q->param_names();

foreach my $param_name (@param_names) {

my $param_value = $q->param($param_name);

print «$param_name = $param_valuen»;

}

Также для работы с параметрами запроса можно использовать модуль URI::Escape, который позволяет кодировать и декодировать строку в формате URL. Например, чтобы передать значение параметра, содержащего специальные символы, необходимо его закодировать, используя функцию uri_escape ().

В итоге, для обработки параметров запроса на Perl необходимо использовать модуль CGI.pm, методы param (), param_names (), URI::Escape и знать особенности передачи параметров в GET- и POST-запросах.

Обработка полученных данных

Получение данных

Перед обработкой данных они должны быть получены. Для получения данных из формы в HTML используется тег <form>. Данные могут быть переданы методами GET или POST. Для обработки данных в Perl используется какой-то из модулей CGI, например, CGI.pm. Этот модуль позволяет получать данные из формы в Perl.

Фильтрация данных

Обработка данных

После проверки данных на безопасность, они готовы для обработки. Для обработки данных можно использовать функции Perl. Например, для строковой обработки можно использовать функции index, substr, split. Для числовой обработки можно использовать функции int, sqrt, log.

Вывод данных

После обработки данных они должны быть выведены пользователю. Для вывода данных на HTML страницу можно использовать тег <pre> для форматированного вывода или использовать функции HTML модуля CGI.pm, такие как header, start_html, end_html и т.д. Кроме того, можно использовать шаблоны для создания динамических HTML страниц.

Use the POST method to pass data

Using the POST method to pass data to the server is more secure and reliable, as sensitive information such as user passwords requires the use of POST to transfer data.

The following is also a test .cgi, which can also handle POST form data submitted by the browser:

#!/usr/bin/perl

local ($buffer, @pairs, $pair, $name, $value, %FORM);
# 读取文本信息
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "POST")
{
   read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}else {
   $buffer = $ENV{'QUERY_STRING'};
}
# 读取 name/value 对信息
@pairs = split(/&/, $buffer);
foreach $pair (@pairs)
{
   ($name, $value) = split(/=/, $pair);
   $value =~ tr/+/ /;
   $value =~ s/%(..)/pack("C", hex($1))/eg;
   $FORM{$name} = $value;
}
$name = $FORM{name};
$url  = $FORM{url};

print "Content-type:text/html\r\n\r\n";
print "<html>";
print "<head>";
print '<meta charset="utf-8">';
print '<title>W3Cschool教程(w3cschool.cn)</title>';
print "</head>";
print "<body>";
print "<h2>$name网址:$url</h2>";
print "</body>";
print "</html>";

1;

The following is a form that uses THEML to send two datas to the server using the GET method, and the submitted server script is also a test.cgi file, the test .html code is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>W3Cschool教程(w3cschool.cn)</title>
</head>
<body>
<form action="/cgi-bin/test.cgi" method="post">
站点名称: <input type="text" name="name">  <br />

站点 URL: <input type="text" name="url" />
<input type="submit" value="提交" />
</form>
</body>
</html>

The initial setup[edit | edit source]

CGI scripts begin like any other Perl program, with a «shebang», something like:

#!/usr/bin/perl

(see Perl Programming/First Programs for details)

Next load the CGI module:

useCGI;

The CGI module makes our work easy because it has pre-programmed functions in it for Internet use. Then we must create a handle to CGI — something that allows us to access the functions. We do this with:

my$query=CGI->new();

This means that the variable $query is loading the CGI standard functions.

Now that our program is setup using the CGI module, it should look something like this:

#!/usr/bin/perl

useCGI;
my$query=CGI->new();

So we have a program, it just doesn’t do anything yet, and will actually cause a server error because the server has no output or any idea of what kind of output to display even if it had some.

Coding the Scraper

For this example, we’re going to retrieve the song lyrics for “Six Days” by the American songwriter DJ Shadow.

The first step is operationalizing the LWP and TreeBuilder libraries to respectively make an HTTP request (and effectively pull the lyrics data from Genius) and prime the scraper to parse the resultant HTML:

The next step is parsing the markup returned by servers hosting the Genius app. Parsing, in this case, means encoding the markup as a traversable tree structure. To preempt any Perl encoding errors in the event of request success, you should supply—to the parser’s parse method—a UTF-8 decoded version of the markup returned from the request.

Upon completing the parsing, you will invoke the method defined in the TreeBuilder API to traverse the resultant markup and extract the lyrics. The lyrics posted on the Genius platform reside in a div element identified as the . To proceed, you will have to encode the said stipulation to produce something that looks like the snippet to follow.

Though very useful in debugging tree traversals, TreeBuilder’s dumping methods (inherited from the HTMLBuilder module) do not offer the best UI for markup formatting. The primitives in the FormatText module, on the other hand, are most useful to tidily display the markup that results from the HTTP response.

To print the resulting HTML subtree as a neat string output, you simply need to instantiate and invoke its method with data as the only argument.

You can now run the scraper by typing the following in a console:

The output—in the console—should appear as shown in the snippet below:

At this point, the scraper is crawling the page to retrieve the lyrics for “Six Days.”

To add some polish and increase its parsing capacity to accommodate any song hosted on the Genius platform, you can parameterize each invocation of the script with a single command-line argument—relevant song input.

A consequent change in the URL should follow to complete the parser:

Now that you have done most of the hard work, you can invoke the Genius scraper and extract the lyrics to the song “Six Days” by typing the following:

The code for the scraper is available in a GitHub Gist. Feel free to customize it however you see fit.

Что такое CGI и PERL

Важно понимать, что CGI – не язык программирования, а протокол передачи данных веб-серверу через stdin и их прием из stdout. В качестве обработчика команд используется любая программа с поддержкой функций потокового ввода-вывода

Например, написанная на языке Perl. Главное, что от скрипта требуется «умение» заполнять таблицы в базе данных и получать данные из них путем подачи запроса, чего никогда не сделать средствами HTML.

Особенности применения языка Perl:

  1. Подходит для парсинга текстовых данных в справочных системах.
  2. Он удобен при обработке массивов непонятных данных в БД веб-ресурсов.
  3. Требуется вывод информации на экран, в файл или график на сайте.

В качестве альтернативы Perl все чаще применяется язык программирования Python, но администраторы «старой закалки» продолжают придерживаться классики создания CGI-скриптов, так как поддержка Perl «по умолчанию» имеется в большинстве дистрибутивов Linux. Поэтому программы на нем начинают работать без предварительной подготовки сервера. Формально же скрипты можно писать на чем угодно – хоть на C/C++, Pascal, Java или Visual Basic.

Комьюнити теперь в Телеграм

Подпишитесь и будьте в курсе последних IT-новостей

Подписаться

Отправка данных из Perl скрипта на HTML страницу

Одной из самых важных задач при работе с Perl скриптами на HTML странице является отправка данных. Это может быть результат выполнения каких-то вычислений или просто текстовая информация. Для этого в Perl есть несколько способов отправки данных на страницу.

Один из самых простых способов отправки данных — использование функции print. Для этого необходимо вызвать функцию print, передав ей необходимую информацию. Например, если нужно отправить на страницу строку «Hello, World!», то можно использовать такой код:

Также можно отправлять данные, используя специальный объект CGI. Для этого нужно создать объект CGI и вызывать его методы, передавая нужную информацию в качестве параметра. Например, чтобы отправить на страницу строку «Hello, World!» c использованием объекта CGI, можно использовать такой код:

my $cgi = new CGI;

print $cgi->header();

print $cgi->start_html();

print «Hello, World!»;

print $cgi->end_html();

В этом примере мы создаем объект CGI, вызываем его метод header(), который отправляет заголовок страницы, а затем методы start_html() и end_html(), которые добавляют открывающие и закрывающие теги html.

Таким образом, отправка данных из Perl скрипта на HTML страницу довольно простая задача, которую можно выполнить, используя простую функцию print или объект CGI. Главное — знать, какие данные нужно отправлять и как их обработать в Perl.

Использование метода print

Print – это метод, который используется в Perl для вывода текста. Он работает аналогично команде echo в PHP или console.log() в JavaScript.

В Perl можно использовать метод print для вывода любых данных, включая переменные, строки и числа.

Простой пример:

Этот код выведет текст «Привет, мир!» без кавычек.

Можно также использовать переменные:

Вывод будет таким:

Используя метод print, можно выводить информацию в таблице. Для этого используется следующий синтаксис:

Этот код выведет таблицу с заголовками «Заголовок 1» и «Заголовок 2», а также ячейками «Ячейка 1» и «Ячейка 2».

Использование метода print очень простое. Он может быть использован во многих различных ситуациях и в сочетании с множеством других методов.

Форматирование вывода

Перед выводом любых данных с помощью скрипта Perl, необходимо обеспечить форматирование вывода. Это поможет представить информацию более понятно и удобно для пользователя.

Одним из способов форматирования является использование тегов em и strong

Тег em можно использовать для выделения слов или фраз, а strong для выделения основной и самой важной информации

Для представления списка элементов в HTML можно использовать теги ul, ol и li. Тег ul отображает элементы в виде ненумерованного списка, а ol — в виде нумерованного списка. Каждый элемент списка обозначается тегом li.

Однако, если нужно отобразить большой объем информации, удобнее использовать тег table. С помощью него можно создавать таблицы с заголовками и строками, что поможет улучшить визуальную читабельность информации.

Web server support and configuration

Before you program CGI, make sure that your Web server supports CGI and that CGI handlers are configured.

Apache supports CGI configurations:

Set up the CGI directory:

ScriptAlias /cgi-bin/ /var/www/cgi-bin/


All HTTP server execution CGI programs are stored in a pre-configured directory.


This directory is called the CGI directory, and by convention it is named /var/www/cgi-bin directory.

The extension of the CGI file .cgi, and Perl can also use .pl extension.

By default, the Linux server configuration runs in the cgi-bin directory for /var/www.

If you want to specify other directories that run CGI scripts, you can modify the httpd.conf profile as follows:

<Directory "/var/www/cgi-bin">
   AllowOverride None
   Options +ExecCGI
   Order allow,deny
   Allow from all
</Directory>

Add the suffix .pl AddHandler so that we can access the perl script file .pl end of the file:

AddHandler cgi-script .cgi .pl .py

The first CGI program

Let’s create a test .cgi file, as follows:

#!/usr/bin/perl

print "Content-type:text/html\r\n\r\n";
print '<html>';
print '<head>';
print '<meta charset="utf-8">';
print '<title>W3Cschool教程(w3cschool.cn)</title>';
print '</head>';
print '<body>';
print '<h2>Hello Word! </h2>';
print '<p>来自W3Cschool教程第一个 CGI 程序。</p>';
print '</body>';
print '</html>';

1;

Then open the browser and http://localhost/cgi-bin/test.cgi, and the output is as follows:

The output of the first line of the script, «Content-type:text/html\n\n», is sent to the browser and the browser is informed that the type of content displayed is «text/html».

How To Raise a «File Download» Dialog Box ?

Sometime it is desired that you want to give option where a use will click a link and it will pop up a «File Download» dialogue box to the user in stead of displaying actual content. This is very easy and will be achived through HTTP header.

This HTTP header will be different from the header mentioned in previous section.

For example,if you want make a FileName file downloadable from a given link then its syntax will be as follows.

#!/usr/bin/perl

# HTTP Header
print "Content-Type:application/octet-stream; name=\"FileName\"\r\n";
print "Content-Disposition: attachment; filename=\"FileName\"\r\n\n";

# Actual File Content will go hear.
open( FILE, "<FileName" );
while(read(FILE, $buffer, 100) ) {
   print("$buffer");
}

Starting Apache

If Apache was installed as part of your standard Linux installation then it will almost certainly also be configured to start automatically when Linux starts up. You can see if it’s running by typing

Shell

$ ps -e | grep httpd

1 $ps–e|grephttpd

at your command line. If Apache is running you’ll see a number of httpd processes running. If it isn’t running you’ll need to start it yourself. There’s a program called apachectl in the bin directory. Simply run

Shell

$ apachectl start

1 $apachectl start

and you should see a message saying that the server has started. You can also run

Shell

$ apachectl stop

1 $apachectl stop

to stop the server and

Shell

$ apachectl restart

1 $apachectl restart

to stop and immediately restart the server. This last option is useful when you’ve changed the server configuration.

Having started your Apache server we can check that it’s working properly. Simply start up your favourite browser and type

http://localhost

1 http//localhost

in the location box. You should see the Apache web server default page. If not, you’ll need to investigate a bit further to find out what the problem is.

This is what you’ll see if Apache is running correctly

Assuming that Apache is working correctly, the next step is to check that it is configured to run CGI programs correctly. We’ll try to run one of the Apache sample CGI scripts. The URL is

http://localhost/cgi-bin/printenv

1 http//localhost/cgi-bin/printenv

If your server is configured correctly you’ll see a list of environment variables displayed in your browser. If not, it’s time to start looking at the Apache configuration file. The file is called http.conf and it’s in the conf directory under the main Apache directory. Search this file for a line like

Apache

ScriptAlias /cgi-bin/ “/usr/local/apache/cgi-bin/”

1 ScriptAliascgi-bin“/usr/local/apache/cgi-bin/”

CGI Environment Variables

All CGI programs have received the following environment variables, which played an important role in the CGI program:

variable name description
CONTENT_TYPE This value indicates that the environment variable to the MIME type of information transfer. At present, the environment variables are generally CONTENT_TYPE: application / x-www-form-urlencoded, he said that the data from the HTML form.
CONTENT_LENGTH If the transfer mode server and CGI program information is POST, even if the environment variable STDIN input the number of bytes that can be read valid data from the standard. This environment variable when reading the input data must be used.
HTTP_COOKIE COOKIE content within the client.
HTTP_USER_AGENT Providing information includes the version number of the client browser or other proprietary data.
PATH_INFO The value of this environment variable indicates the name of the CGI program immediately after the additional path information. It often appears as an argument CGI program.
QUERY_STRING If the transfer mode server and CGI program information is information GET, the value of this environment variable even if passed. This information is followed by the name of the CGI program, both in the middle with a question mark ‘?’ Separator.
REMOTE_ADDR The value of this environment variable is the IP address of the client sends a request, for example, the above 192.168.1.67. This value is always present. And it is the need to provide the Web client to the Web server’s unique identifier can be used in CGI programs to distinguish between different Web client.
REMOTE_HOST The value of this environment variable contains the host name of the requesting client of CGI. If it does not you want to check, you do not need to define this environment variable.
REQUEST_METHOD It provides a method called script. For HTTP / 1.0 protocol script only GET and POST meaningful.
SCRIPT_FILENAME The full path to CGI scripts
SCRIPT_NAME The name of the CGI script
SERVER_NAME This is the host name, alias, or IP address of your WEB server.
SERVER_SOFTWARE The value of this environment variable contains the call CGI program name and version number of the HTTP server. For example, the above value of Apache / 2.2.14 (Unix)

Here is a simple CGI script output CGI environment variables:

#!/usr/bin/perl

print "Content-type: text/html\n\n";
print '<meta charset="utf-8">';
print "<font size=+1>环境变量:</font>\n";
foreach (sort keys %ENV)
{
  print "<b>$_</b>: $ENV{$_}<br>\n";
}

1;

Adding the CGI module to the basic program

The CGI module you can find on CPAN can help with a lot of the CGI processing. Here we introduce it rather simply to take care of the mime-type output, the <HTML>, <BODY> tags, the title and the tags to end the HTML.

Our simple program becomes:

#!/usr/bin/perl -w
use DBI;
use CGI;

my $cgi = new CGI;

# output the content-type so the web server knows

print $cgi->header;

# output the start HTML sequence with a title

print $cgi->start_html(-title=>'Basic CGI');

#
# you should change the connect method call to use the DBD you are
# using. The following examples all use DBD::ODBC and hence the
# first argument to the connect method is 'dbi:ODBC:DSN'.
#

my $dbh = DBI->connect('dbi:ODBC:test', 'dbuser', 'dbauth');
my $sql = q/select productcode, product from TEST/;
my $sth = $dbh->prepare($sql);
$sth->execute;
print $cgi->table({border=1});

# table headings are SQL column names

print "<tr><th>$sth->{NAME}-></th><th>$sth->{NAME}-></th></tr>";
while (my @row = $sth->fetchrow_array) {
    print "<tr><td>$row</td><td>$row</td></tr>\n";
}
print $cgi->end_table;
print $cgi->end_html;

Here we have used the CGI as follows :

  • $cgi->header — this outputs the mime-type (content-type: text/html)
  • $cgi->start_html(-title=>’Basic CGI’) — outputs the <html><title=»Basic CGI»><title><body>»
  • $cgi->table({border=1}) — outputs the «<table border=»1″>»
  • $cgi->end_table — outputs the «</table>»
  • $cgi->end_html — outputs the «</body></html>»

In fact the CGI module is a lot more powerful than this and you could output all the table in one go with a combination of the CGI Tr method and DBI’s fetchrow_xxx method but the next section shows a totally different method which allows you to separate your HTML entirely from the data you extracted from the database.

Понравилась статья? Поделиться с друзьями: