perlfaq-5.0150039

名前

perlfaq9 - Web, Email and Networking

perlfaq9 - Web、メール、ネットワーク

説明

This section deals with questions related to running web sites, sending and receiving email as well as general networking.

このセクションでは、web サイトの実行、メールの送受信、および一般的な ネットワークに関する質問を扱っています。

web フレームワークを使うべき?

Yes. If you are building a web site with any level of interactivity (forms / users / databases), you will want to use a framework to make handling requests and responses easier.

はい。 何らかのレベルの相互作用(フォーム、ユーザー、データベース)を持つ web サイトを 構築しているなら、リクエストとレスポンスをより簡単に扱えるような フレームワークを使いたいでしょう。

If there is no interactivity then you may still want to look at using something like Template Toolkit or Plack::Middleware::TemplateToolkit so maintenance of your HTML files (and other assets) is easier.

相互作用がなくても、HTML ファイル(およびその他の資産)の管理をより 簡単にするために Template ToolkitPlack::Middleware::TemplateToolkit のようなものを使いたいかもしれません。

どの web フレームワークを使うべき?

There is no simple answer to this question. Perl frameworks can run everything from basic file servers and small scale intranets to massive multinational multilingual websites that are the core to international businesses.

この質問への単純な答えはありません。 Perl のフレームワークには、基本的なファイルサーバとスケールの小さい イントラネット用から国際ビジネスのコアとなる巨大国際多言語 web サイトまで あらゆるものがあります。

Below is a list of a few frameworks with comments which might help you in making a decision, depending on your specific requirements. Start by reading the docs, then ask questions on the relevant mailing list or IRC channel.

以下は、特定の要求に合わせて決定を行う助けとなるであろうコメント付きの いくつかのフレームワークの一覧です。 文書を読むことから始めて、それから関連するメーリングリストや IRC チャンネルに質問してください。

Catalyst

Strongly object-oriented and fully-featured with a long development history and a large community and addon ecosystem. It is excellent for large and complex applications, where you have full control over the server.

長い開発の歴史と大きなコミュニティおよびアドオン生態系を持ち、 強力にオブジェクト指向で完全な機能があります。 サーバに対する完全な制御がある場所での大きく複雑なアプリケーションには 素晴らしいものです。

Dancer

Young and free of legacy weight, providing a lightweight and easy to learn API. Has a growing addon ecosystem. It is best used for smaller projects and very easy to learn for beginners.

新しくレガシーな重みから解放されていて、軽量で学習しやすい API を提供します。 アドオン生態系は大きくなりつつあります。 より小さいプロジェクトに最適で初心者が学習するのはとても簡単です。

Mojolicious

Fairly young with a focus on HTML5 and real-time web technologies such as WebSockets.

比較的若く、HTML5 と WebSockets のようなリアルタイム web 技術に焦点を 当てています。

Web::Simple

Currently experimental, strongly object-oriented, built for speed and intended as a toolkit for building micro web apps, custom frameworks or for tieing together existing Plack-compatible web applications with one central dispatcher.

現在の所実験的で、強力にオブジェクト指向で、速度重視で構築されており、 ごく小さい web アプリやカスタムフレームワークを構築したり、 既存の Plack 互換の web アプリケーションを一つの中央ディスパッチャと 結びつけることを意図しています。

All of these interact with or use Plack which is worth understanding the basics of when building a website in Perl (there is a lot of useful Plack::Middleware).

これら全ては Plack を使うか相互作用しており、Perl で web サイトを 構築するときは基本を理解する価値があります (多くの有用な Plack::Middleware が あります)。

Plack と PSGI って何?

PSGI is the Perl Web Server Gateway Interface Specification, it is a standard that many Perl web frameworks use, you should not need to understand it to build a web site, the part you might want to use is Plack.

PSGI は Perl Web Server Gateway Interface Specification です; これは多くの Perl web フレームワークが使う標準で、web サイトを構築するためにこれを 理解する必要はないはずです; 使いたい部分は Plack でしょう。

Plack is a set of tools for using the PSGI stack. It contains middleware components, a reference server and utilities for Web application frameworks. Plack is like Ruby's Rack or Python's Paste for WSGI.

Plack は PSGI スタックを使うためのツールの集合です。 これには Web アプリケーションフレームワークのための ミドルウェア 要素、 リファレンスサーバ、ユーティリティを含みます。 Plack は Ruby の Rack や Python の WSGI のための Paste に似ています。

You could build a web site using Plack and your own code, but for anything other than a very basic web site, using a web framework (that uses Plack) is a better option.

Plack と独自のコードを使って web サイトを構築することもできますが、 とても基本的な web サイト以外のものなら、(Plack を使った) web フレームワークを使うのがよりよい選択肢です。

ある文字列から HTML を取り除くには?

Use HTML::Strip, or HTML::FormatText which not only removes HTML but also attempts to do a little simple formatting of the resulting plain text.

HTML::Strip を使うか、HTML を取り除くだけでなく結果のプレーンテキストを 少し単純な形式にしようとする HTML::FormatText を使ってください。

URL の展開を行うには?

HTML::SimpleLinkExtor will extract URLs from HTML, it handles anchors, images, objects, frames, and many other tags that can contain a URL. If you need anything more complex, you can create your own subclass of HTML::LinkExtor or HTML::Parser. You might even use HTML::SimpleLinkExtor as an example for something specifically suited to your needs.

HTML::SimpleLinkExtor は HTML から URL を抽出します; これはアンカー、 イメージ、オブジェクト、フレームおよび URL を含んでいるその他の多くのタグを 扱います。 より複雑なものが必要なら、独自の HTML::LinkExtorHTML::Parser の サブクラスを作ることができます。 何か特別な用途に合わせるための例として HTML::SimpleLinkExtor を使うことも できます。

You can use URI::Find to extract URLs from an arbitrary text document.

任意のテキスト文書から URL を抽出するためには、URI::Find が使えます。

HTML ファイルをフェッチするには?

(contributed by brian d foy)

(brian d foy によって寄贈されました)

Use the libwww-perl distribution. The LWP::Simple module can fetch web resources and give their content back to you as a string:

libwww-perl ディストリビューションを使ってください。 LWP::Simple はウェブ上のリソースをフェッチして、その内容を文字列として 返します:

    use LWP::Simple qw(get);

    my $html = get( "http://www.example.com/index.html" );

It can also store the resource directly in a file:

リソースを直接ファイルに保存することもできます:

    use LWP::Simple qw(getstore);

    getstore( "http://www.example.com/index.html", "foo.html" );

If you need to do something more complicated, you can use LWP::UserAgent module to create your own user-agent (e.g. browser) to get the job done. If you want to simulate an interactive web browser, you can use the WWW::Mechanize module.

もっと複雑なことをする必要がある場合は、仕事を行うための独自の ユーザーエージェント(例えばブラウザ)を作るために LWP::UserAgent モジュールを使えます。 対話的なウェブブラウザをシミュレートしたい場合は、 WWW::Mechanize モジュールが使えます。

HTML フォームの処理を自動化するには?

If you are doing something complex, such as moving through many pages and forms or a web site, you can use WWW::Mechanize. See its documentation for all the details.

もし、複数のページとフォームや web サイトを移動するような、複雑なことを しようとしているなら、WWW::Mechanize が使えます。 全ての詳細についてはこれのドキュメントを参照してください。

If you're submitting values using the GET method, create a URL and encode the form using the query_form method:

GET メソッドを使って値を処理しているのであれば、URL を作って、 さらに query_form メソッドを使ってフォームをエンコードします:

    use LWP::Simple;
    use URI::URL;

    my $url = url('L<http://www.perl.com/cgi-bin/cpan_mod')>;
    $url->query_form(module => 'DB_File', readme => 1);
    $content = get($url);

If you're using the POST method, create your own user agent and encode the content appropriately.

POST メソッドを使っているのであれば、自分用のエージェントを作成して コンテンツを適切にエンコードしてやります。

    use HTTP::Request::Common qw(POST);
    use LWP::UserAgent;

    my $ua = LWP::UserAgent->new();
    my $req = POST 'L<http://www.perl.com/cgi-bin/cpan_mod'>,
                   [ module => 'DB_File', readme => 1 ];
    my $content = $ua->request($req)->as_string;

web上で %-encodings をデコードしたり生成したりするには?

Most of the time you should not need to do this as your web framework, or if you are making a request, the LWP or other module would handle it for you.

ほとんどの場合、web フレームワークでこれを行う必要はないはずです; リクエストを作ったときには、LWP やその他のモジュールが代わりにこれらを 扱います。

To encode a string yourself, use the URI::Escape module. The uri_escape function returns the escaped string:

自分で文字列をエンコードするには、URI::Escape モジュールを使ってください。 uri_escape 関数はエスケープされた文字列を返します:

    my $original = "Colon : Hash # Percent %";

    my $escaped = uri_escape( $original );

    print "$escaped\n"; # 'Colon%20%3A%20Hash%20%23%20Percent%20%25'

To decode the string, use the uri_unescape function:

文字列をデコードするには、uri_unescape 関数を使います:

    my $unescaped = uri_unescape( $escaped );

    print $unescaped; # back to original

Remember not to encode a full URI, you need to escape each component separately and then join them together.

URI 全体をエンコードするのではなく、それぞれの要素を別々にエスケープして それから互いに結合する必要があることを忘れないでください。

別のページにリダイレクトするには?

Most Perl Web Frameworks will have a mechanism for doing this, using the Catalyst framework it would be:

ほとんどの Perl Web フレームワークはこれを行う機構があります; Catalyst フレームワークを使っているなら以下のようになります:

    $c->res->redirect($url);
    $c->detach();

If you are using Plack (which most frameworks do), then Plack::Middleware::Rewrite is worth looking at if you are migrating from Apache or have URL's you want to always redirect.

(ほとんどのフレームワークが使っている) Plack を使っていて、 Apache からの移動や常にリダイレクトしたい URL があるなら、 Plack::Middleware::Rewrite は見る価値があるでしょう。

私の web ぺージでパスワードを入力するには?

See if the web framework you are using has an authentication system and if that fits your needs.

使っている web フレームワークが認証システムを持っているか、そしてそれが 目的に合致しているかを調べてください。

Alternativly look at Plack::Middleware::Auth::Basic, or one of the other Plack authentication options.

あるいは、Plack::Middleware::Auth::Basic またはその他の Plack 認証 オプションの一つを 見てください。

私の CGI スクリプトに悪影響をもたらすようなものを、ユーザーがフォームに入力できないようにするには?

(contributed by brian d foy)

(brian d foy によって寄贈されました)

You can't prevent people from sending your script bad data. Even if you add some client-side checks, people may disable them or bypass them completely. For instance, someone might use a module such as LWP to submit to your web site. If you want to prevent data that try to use SQL injection or other sorts of attacks (and you should want to), you have to not trust any data that enter your program.

人々がスクリプトに悪いデータを送るのを防ぐことは出来ません。 例えクライアント側でチェックをしたとしても、それを無効にしたり 完全に回避したりできます。 例えば、LWP のようなモジュールを使って web サイトに 投稿するかもしれません。 SQL インジェクションや同様の種類の攻撃を行うようなデータを防ぎたいのなら (そしておそらくそうしたいでしょう)、プログラムに入力される どんなデータも信用しないようにする必要があります。

The perlsec documentation has general advice about data security. If you are using the DBI module, use placeholder to fill in data. If you are running external programs with system or exec, use the list forms. There are many other precautions that you should take, too many to list here, and most of them fall under the category of not using any data that you don't intend to use. Trust no one.

perlsec 文書にはデータセキュリティに関する一般的な助言があります。 DBI モジュールを使っているなら、データを埋めるのにプレースホルダを 使ってください。 systemexec で外部プログラムを実行しているなら、リスト形式を 使ってください。 その他、ここに書ききれないほどの注意するべき多くの事前注意があり、 そのほとんどは、使おうとしていないデータは使わないという分野に当てはまります。 誰も信用しないでください。

メールのヘッダーを解析するには?

Use the Email::MIME module. It's well-tested and supports all the craziness that you'll see in the real world (comment-folding whitespace, encodings, comments, etc.).

Email::MIME モジュールを使ってください。 これはよくテストされていて、現実世界で見ることになるあらゆる狂気 (コメント畳み込み空白、エンコーディング、コメントなど)に対応しています。

  use Email::MIME;

  my $message = Email::MIME->new($rfc2822);
  my $subject = $message->header('Subject');
  my $from    = $message->header('From');

If you've already got some other kind of email object, consider passing it to Email::Abstract and then using its cast method to get an Email::MIME object:

既に何らかの他の種類のメールオブジェクトがあるなら、それを Email::Abstract に渡して、それから Email::MIME オブジェクトを 得るために cast メソッドを使うことを考慮してください:

  my $mail_message_object = read_message();
  my $abstract = Email::Abstract->new($mail_message_object);
  my $email_mime_object = $abstract->cast('Email::MIME');

メールアドレスが正しいかチェックするには?

(partly contributed by Aaron Sherman)

(一部は Aaron Sherman によって寄贈されました)

This isn't as simple a question as it sounds. There are two parts:

これは見た目ほど単純な質問ではありません。 これは二つの部分からなります:

a) How do I verify that an email address is correctly formatted?

a) メールアドレスが正しい形式かを検証するには?

b) How do I verify that an email address targets a valid recipient?

b) メールアドレスが正当な受信者を対象としているかを検証するには?

Without sending mail to the address and seeing whether there's a human on the other end to answer you, you cannot fully answer part b, but the Email::Valid module will do both part a and part b as far as you can in real-time.

そのアドレスにメールを送ってそれが届いたかどうかを確認しなければ 完全にパート b に答えられませんが、Email::ValidRFC::RFC822::Address のモジュールは、リアルタイムでできる限りの ことに対してパート a とパート b の両方を行います。

Our best advice for verifying a person's mail address is to have them enter their address twice, just as you normally do to change a password. This usually weeds out typos. If both versions match, send mail to that address with a personal message. If you get the message back and they've followed your directions, you can be reasonably assured that it's real.

私たちができる最善のアドバイスは、個人のメールアドレスをチェックするのに パスワードを変更するときと同じようにユーザーにアドレスを 二回入力させるというものです。 これによって通常は打ち間違いを防ぐことができます。 二回の入力がマッチしたなら、個人的な内容のメッセージをメールとして そのアドレスへ送ります。 もしメッセージが返ってきて、それがあなたの指示に従っているなら、 それが実際のものであると十分に仮定できます。

A related strategy that's less open to forgery is to give them a PIN (personal ID number). Record the address and PIN (best that it be a random one) for later processing. In the mail you send, include a link to your site with the PIN included. If the mail bounces, you know it's not valid. If they don't click on the link, either they forged the address or (assuming they got the message) following through wasn't important so you don't need to worry about it.

より偽造のやりにくい別のやり方に、チェックに対象者に対して PIN (Personal ID Number) を与えるというものがあります。 後の処理のためにアドレスと PIN (ランダムであることが望ましい)を 記録しておくのです。 あなたがメールを送るときに、PIN が含まれたあなたのサイトへのリンクを 含めてください。 メールがバウンスしたなら、不正であることが分かります。 リンクがクリックされなければ、アドレスが偽造されたか、(メッセージが 届いたとして) 最後まで行うことが重要ではなかったのでそれについて 気にする必要はないと言うことです。

MIME/BASE64 文字列のデコードを行うには?

The MIME::Base64 package handles this as well as the MIME/QP encoding. Decoding base 64 becomes as simple as:

MIME::Base64 パッケージはこの問題と、 MIME/QP エンコーディングを取り扱います。 BASE64 のデコードは以下のように単純です:

    use MIME::Base64;
    my $decoded = decode_base64($encoded);

The Email::MIME module can decode base 64-encoded email message parts transparently so the developer doesn't need to worry about it.

Email::MIME モジュールは BASE64 でエンコードされたメールのメッセージ部分を 透過的にデコードできるので、開発者はそれについて気にする必要はありません。

あるユーザーのメールアドレスを知るには?

Ask them for it. There are so many email providers available that it's unlikely the local system has any idea how to determine a user's email address.

その人に聞いてください。 多くのメールプロバイダが利用可能なので、ローカルシステムがユーザーの メールアドレスを決定する方法はまずありません。

The exception is for organization-specific email (e.g. foo@yourcompany.com) where policy can be codified in your program. In that case, you could look at $ENV{USER}, $ENV{LOGNAME}, and getpwuid($<) in scalar context, like so:

例外は、組織に固有のメール (例えば foo@yourcompany.com) で、ポリシーを プログラムにコード化できる場合です。 この場合、以下のように $ENV{USER}, $ENV{LOGNAME} およびスカラコンテキストで and getpwuid($<) を 見ることができます:

  my $user_name = getpwuid($<)

But you still cannot make assumptions about whether this is correct, unless your policy says it is. You really are best off asking the user.

しかし、ポリシーがそうなっていない限り、これが正しいかどうかに関して 仮定することはやはりできません。 本当に最良なのはユーザーに聞くことです。

メールを送るには?

Use the Email::MIME and Email::Sender::Simple modules, like so:

以下のように、Email::MIMEEmail::Sender::Simple モジュールを 使ってください:

  # first, create your message
  my $message = Email::MIME->create(
    header_str => [
      From    => 'you@example.com',
      To      => 'friend@example.com',
      Subject => 'Happy birthday!',
    ],
    attributes => {
      encoding => 'quoted-printable',
      charset  => 'ISO-8859-1',
    },
    body_str => "Happy birthday to you!\n",
  );

  use Email::Sender::Simple qw(sendmail);
  sendmail($message);

By default, Email::Sender::Simple will try `sendmail` first, if it exists in your $PATH. This generally isn't the case. If there's a remote mail server you use to send mail, consider investigating one of the Transport classes. At time of writing, the available transports include:

デフォルトでは、Email::Sender::Simple は、$PATH にあれば `sendmail` を 最初に試します。 これは一般的に間違いです。 メールを送るのに使うリモートのメールサーバがある場合、 Transport クラスの一つを調査することを考慮してください。 これを書いている時点では、利用可能な転送層は以下のようなものです:

Email::Sender::Transport::Sendmail

This is the default. If you can use the mail(1) or mailx(1) program to send mail from the machine where your code runs, you should be able to use this.

これはデフォルトです。 コードを実行しているマシンからメールを送るのに mail(1)mailx(1) が 使えるなら、これが使えるはずです。

Email::Sender::Transport::SMTP

This transport contacts a remote SMTP server over TCP. It optionally uses SSL and can authenticate to the server via SASL.

この転送層は TCP を使ってリモート SMTP サーバに接続します。 オプションとして SSL を使って、SASL 経由でサーバに認証できます。

Email::Sender::Transport::SMTP::TLS

This is like the SMTP transport, but uses TLS security. You can authenticate with this module as well, using any mechanisms your server supports after STARTTLS.

これは SMTP 転送と似ていますが、TLS セキュリティを使います。 このモジュールも、STARTTLS の後サーバが対応している任意の機構を使って 認証できます。

Telling Email::Sender::Simple to use your transport is straightforward.

使用する転送層を Email::Sender::Simple に教えるのは簡単です:

  sendmail(
    $message,
    {
      transport => $email_sender_transport_object,
    }
  );

メールメッセージに添付するためにどうやって MIME を使えばいいですか?

Email::MIME directly supports multipart messages. Email::MIME objects themselves are parts and can be attached to other Email::MIME objects. Consult the Email::MIME documentation for more information, including all of the supported methods and examples of their use.

Email::MIME は直接マルチパートメッセージに対応しています。 Email::MIME 自身はパートで、その他の Email::MIME オブジェクトに 添付できます。 対応している全てのメソッドとその使い方の例を含む、さらなる情報については Email::MIME 文書を参照してください。

メールを読み出すには?

Use the Email::Folder module, like so:

以下のように、Email::Folder モジュールを使ってください:

  use Email::Folder;

  my $folder = Email::Folder->new('/path/to/email/folder');
  while(my $message = $folder->next_message) {
    # next_message returns Email::Simple objects, but we want
    # Email::MIME objects as they're more robust
    my $mime = Email::MIME->new($message->as_string);
  }

There are different classes in the Email::Folder namespace for supporting various mailbox types. Note that these modules are generally rather limited and only support reading rather than writing.

様々なメールボックスの種類に対応するための異なったクラスが Email::Folder 名前空間にあります。 これらのモジュールは一般的に 読み込み にのみ対応していて書き込みには 対応していないことに注意してください。

私のホスト名/ドメイン名/IP アドレスを見つけるには?

(contributed by brian d foy)

(brian d foy によって寄贈されました)

The Net::Domain module, which is part of the Standard Library starting in Perl 5.7.3, can get you the fully qualified domain name (FQDN), the host name, or the domain name.

Perl 5.7.3 から標準ライブラリの一部である Net::Domain モジュールを使うと、 完全修飾ドメイン名 (FQDN)、ホスト名、ドメイン名が得られます。

    use Net::Domain qw(hostname hostfqdn hostdomain);

    my $host = hostfqdn();

The Sys::Hostname module, part of the Standard Library, can also get the hostname:

標準ライブラリの一部である Sys::Hostname モジュールでもホスト名を 得られます。

    use Sys::Hostname;

    $host = hostname();

The Sys::Hostname::Long module takes a different approach and tries harder to return the fully qualified hostname:

Sys::Hostname::Long モジュールは異なる手法をとり、完全修飾ホスト名を 返すためにさらに多くのことを試みます:

  use Sys::Hostname::Long 'hostname_long';

  my $hostname = hostname_long();

To get the IP address, you can use the gethostbyname built-in function to turn the name into a number. To turn that number into the dotted octet form (a.b.c.d) that most people expect, use the inet_ntoa function from the Socket module, which also comes with perl.

IP アドレスを得るには、名前から数値に変換するために gethostbyname 組み込み関数が使えます。 数値を、ほとんどの人が想定しているピリオド付きの形 (a.b.c.d) に変換するには、 標準配布されている Socket モジュールの inet_ntoa 関数を使います。

    use Socket;

    my $address = inet_ntoa(
        scalar gethostbyname( $host || 'localhost' )
    );

(S)FTP ファイルをダウンロード/アップロードするには?

Net::FTP, and Net::SFTP allow you to interact with FTP and SFTP (Secure FTP) servers.

Net::FTPNet::SFTP で FTP および SFTP (Secure FTP) サーバと 相互作用できるようになります。

Perl で RPC を行うには?

Use one of the RPC modules( https://metacpan.org/search?q=RPC ).

RFC モジュール ( https://metacpan.org/search?q=RPC ) の一つを使いましょう。

AUTHOR AND COPYRIGHT

Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and other authors as noted. All rights reserved.

This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself.

Irrespective of its distribution, all code examples in this file are hereby placed into the public domain. You are permitted and encouraged to use this code in your own programs for fun or for profit as you see fit. A simple comment in the code giving credit would be courteous but is not required.