.. ===================== Managing static files ==================== ====================== 静的ファイルの公開方法 ====================== :revision-up-to: 17812 (1.4) .. versionadded:: 1.3 .. Django developers mostly concern themselves with the dynamic parts of web applications -- the views and templates that render anew for each request. But web applications have other parts: the static files (images, CSS, Javascript, etc.) that are needed to render a complete web page. Django の開発者は、ビューや、リクエストごとに新しくレンダリングされるテンプ レートといった、 Web アプリケーションの動的な部分にもっぱら関心を持っていま す。しかし、 Web アプリケーションには静的なファイル ( 画像、CSS、JavaScriptな ど ) も含まれています。完全な Web ページをレンダリングするためにはこういった ファイルが必要です。 .. For small projects, this isn't a big deal, because you can just keep the static files somewhere your web server can find it. However, in bigger projects -- especially those comprised of multiple apps -- dealing with the multiple sets of static files provided by each application starts to get tricky. 小さなプロジェクトではこのことは大きな問題になりません。 Web サーバが見つけら れる場所で静的ファイルを単に管理することができるからです。しかし、もっと大きな プロジェクトで、特に複数のアプリケーションからなる場合は、各アプリケーションが 持っている静的ファイルの集まりを複数扱うことになり、ややこしくなってきます。 .. That's what ``django.contrib.staticfiles`` is for: it collects static files from each of your applications (and any other places you specify) into a single location that can easily be served in production. ``django.contrib.staticfiles`` はまさにそのためにあります。これは静的なファイ ルを各アプリケーションから (さらに指定した別の場所からも) 一つの場所に集め、運 用環境で公開しやすくするものです。 .. .. note:: If you've used the `django-staticfiles`_ third-party app before, then ``django.contrib.staticfiles`` will look very familiar. That's because they're essentially the same code: ``django.contrib.staticfiles`` started its life as `django-staticfiles`_ and was merged into Django 1.3. .. note:: もし `django-staticfiles`_ アプリケーションを使ったことがあるなら、 ``django.contrib.staticfiles`` はよく似たものに見えるでしょう。それはこの 2 つが本質的に同じコードだからです。 ``django.contrib.staticfiles`` は `django-staticfiles`_ として生まれ、 Django 1.3 に取り込まれました。 .. If you're upgrading from ``django-staticfiles``, please see `Upgrading from django-staticfiles`_, below, for a few minor changes you'll need to make. ``django-staticfiles`` からアップグレードする場合は下に述べる `django-staticfiles からのアップデート`_ を参照してください。しなければな らないいくつかの小さな変更について説明しています。 .. _django-staticfiles: http://pypi.python.org/pypi/django-staticfiles/ .. Using ``django.contrib.staticfiles`` ==================================== ``django.contrib.staticfiles`` を使う ===================================== .. Basic usage ----------- 基本的な使い方 -------------- .. 1. Put your static files somewhere that ``staticfiles`` will find them. By default, this means within ``static/`` subdirectories of apps in your :setting:`INSTALLED_APPS`. Your project will probably also have static assets that aren't tied to a particular app. The :setting:`STATICFILES_DIRS` setting is a tuple of filesystem directories to check when loading static files. It's a search path that is by default empty. See the :setting:`STATICFILES_DIRS` docs how to extend this list of additional paths. Additionally, see the documentation for the :setting:`STATICFILES_FINDERS` setting for details on how ``staticfiles`` finds your files. .. 2. Make sure that ``django.contrib.staticfiles`` is included in your :setting:`INSTALLED_APPS`. For :ref:`local development`, if you are using :ref:`runserver` or adding :ref:`staticfiles_urlpatterns` to your URLconf, you're done with the setup -- your static files will automatically be served at the default (for :djadmin:`newly created` projects) :setting:`STATIC_URL` of ``/static/``. .. 3. You'll probably need to refer to these files in your templates. The easiest method is to use the included context processor which allows template code like: .. code-block:: html+django See :ref:`staticfiles-in-templates` for more details, **including** an alternate method using a template tag. 1. ``staticfiles`` が見つけられる場所に静的ファイルを置いてください。 デフォルトでは、 :setting:`INSTALLED_APPS` に入っているアプリケーションの ``static/`` サブディレクトリです。 おそらく、あなたのプロジェクトには特定のアプリケーションに結びついていない 静的なファイルもあるでしょう。 :setting:`STATICFILES_DIRS` には、静的ファイ ルをロードする時にチェックすべきファイルシステム上のディレクトリを、タプル で記述します。 ``staticfiles`` がファイルを探す方法の詳細について知るには :setting:`STATICFILES_FINDERS` 設定のドキュメントを参照してください。 2. :setting:`INSTALLED_APPS` に ``django.contrib.staticfiles`` が入っているこ とを確認してください。 :ref:`ローカル環境での開発` で :ref:`runserver` を使っているか、 :ref:`staticfiles_urlpatterns` を URLconf に追加し てあるなら、これでセットアップは終わりです。 自動的に :setting:`STATIC_URL` で静的ファイルが公開されます。 ( :djadmin:`newly created` プロジェクトでは ) デフォルト設定が ``/static/`` です。 3. きっとこれらのファイルをテンプレートで使いたいでしょう。一番簡単な方法は コンテキストプロセッサを使うことです。次のようなテンプレートを書けます: .. code-block:: html+django もっと詳しいことは :ref:`staticfiles-in-templates` に書いてあります。テンプ レートタグを使う別の方法も **書かれています** 。 .. Deploying static files in a nutshell ------------------------------------ ごく簡単に、静的ファイルのデプロイについて ------------------------------------------ .. When you're ready to move out of local development and deploy your project: 1. Set the :setting:`STATIC_URL` setting to the public URL for your static files (in most cases, the default value of ``/static/`` is just fine). 2. Set the :setting:`STATIC_ROOT` setting to point to the filesystem path you'd like your static files collected to when you use the :djadmin:`collectstatic` management command. For example:: STATIC_ROOT = "/home/jacob/projects/mysite.com/sitestatic" 3. Run the :djadmin:`collectstatic` management command:: ./manage.py collectstatic This'll churn through your static file storage and copy them into the directory given by :setting:`STATIC_ROOT`. 4. Deploy those files by configuring your webserver of choice to serve the files in :setting:`STATIC_ROOT` at :setting:`STATIC_URL`. :ref:`staticfiles-production` covers some common deployment strategies for static files. ローカル環境での開発が終わり、プロジェクトをデプロイする準備ができたら: 1. :setting:`STATIC_URL` を静的なファイルを指すパブリックな URL に設定してくだ さい。 ( ほとんどの場合、デフォルト値である ``/static/`` でうまく行きます ) 2. :setting:`STATIC_ROOT` に、 :djadmin:`collectstatic` コマンドを使って静的な ファイルを集めたいファイルシステム上のパスを設定してください。例えば:: STATIC_ROOT = "/home/jacob/projects/mysite.com/sitestatic" 3. :djadmin:`collectstatic` コマンドを実行してください:: ./manage.py collectstatic このコマンドは静的ファイルのストレージを漁って、見つけたファイルを :setting:`STATIC_ROOT` で与えられたディレクトリにコピーします。 4. :setting:`STATIC_ROOT` に含まれるファイルが :setting:`STATIC_URL` の場所で 公開されるように Web サーバを設定しデプロイしてください。 :ref:`staticfiles-production` はいくつかのよくある静的ファイルのデプロイ手 法に言及しています。 .. Those are the **basics**. For more details on common configuration options, read on; for a detailed reference of the settings, commands, and other bits included with the framework see :doc:`the staticfiles reference `. これらは **基本** です。設定オプションについてもっと深く知るには、さらに読むべ きものがあります。設定やコマンド、またフレームワークに含まれる他のちょっとした ことを知るために、 :doc:`staticfiles リファレンス ` を参照してください。 .. .. note:: In previous versions of Django, it was common to place static assets in :setting:`MEDIA_ROOT` along with user-uploaded files, and serve them both at :setting:`MEDIA_URL`. Part of the purpose of introducing the ``staticfiles`` app is to make it easier to keep static files separate from user-uploaded files. For this reason, you need to make your :setting:`MEDIA_ROOT` and :setting:`MEDIA_URL` different from your :setting:`STATIC_ROOT` and :setting:`STATIC_URL`. You will need to arrange for serving of files in :setting:`MEDIA_ROOT` yourself; ``staticfiles`` does not deal with user-uploaded files at all. You can, however, use :func:`django.views.static.serve` view for serving :setting:`MEDIA_ROOT` in development; see :ref:`staticfiles-other-directories`. .. note:: Django の以前のバージョンでは、ユーザがアップロードしたファイルを置くための :setting:`MEDIA_ROOT` に静的なファイルも一緒に置かれ、どちらも :setting:`MEDIA_URL` で公開されていました。 ``staticfiles`` アプリケーショ ンを使う目的の 1 つは、静的ファイルとユーザがアップロードしたファイルとを分 けて管理することを簡単にするためです。 この理由から、 :setting:`MEDIA_ROOT` および :setting:`MEDIA_URL` は :setting:`STATIC_ROOT` および :setting:`STATIC_URL` とは別の値にしなければ なりません。 :setting:`MEDIA_ROOT` に含まれるファイルを公開するには、自分で 整理する必要があります。 ``staticfiles`` はユーザがアップロードしたファイル を全く扱わないのです。ただし、 :setting:`MEDIA_ROOT` のファイルを公開するた めに :func:`django.views.static.serve` ビューを使うことはできます。 :ref:`staticfiles-other-directories` を参照してください。 .. _staticfiles-in-templates: .. Referring to static files in templates ====================================== テンプレートから静的なファイルを参照する ======================================== .. At some point, you'll probably need to link to static files in your templates. You could, of course, simply hardcode the path to you assets in the templates: テンプレートではいくつかの箇所で静的なファイルをリンクする必要があるでしょう。 もちろん、テンプレートで静的ファイルを単にハードコードすることは可能です: .. code-block:: html .. Of course, there are some serious problems with this: it doesn't work well in development, and it makes it *very* hard to change where you've deployed your static files. If, for example, you wanted to switch to using a content delivery network (CDN), then you'd need to change more or less every single template. 当然ながら、これでは深刻な問題がいくつかあります。開発環境ではうごきませんし、 静的ファイルを公開する場所を変更するのが *非常に* 困難です。例えばもし、 コン テンツデリバリーネットワーク (CDN) を使うように切り替えたい場合、テンプレート 全てを一つ一つ変更することになってしまいます。 .. A far better way is to use the value of the :setting:`STATIC_URL` setting directly in your templates. This means that a switch of static files servers only requires changing that single value. Much better! もっと良い方法は :setting:`STATIC_URL` の値を直接テンプレートで使うことです。 こうすると、一つの値を変更するだけで静的ファイルのサーバを切り替えることができ ます。ずっと良いですね! .. Django includes multiple built-in ways of using this setting in your templates: a context processor and a template tag. Django にはこの設定値をテンプレートで使うための複数の方法があります。コンテキ ストプロセッサとテンプレートタグです。 .. With a context processor ------------------------ コンテキストプロセッサを使う ---------------------------- .. The included context processor is the easy way. Simply make sure ``'django.core.context_processors.static'`` is in your :setting:`TEMPLATE_CONTEXT_PROCESSORS`. It's there by default, and if you're editing that setting by hand it should look something like:: 組み込みのコンテキストプロセッサは簡単に使えます。 :setting:`TEMPLATE_CONTEXT_PROCESSORS` 設定に ``'django.core.context_processors.static'`` が含まれていれば良いだけです。そし てデフォルトではそのようになっています。自ら設定を編集する場合は、こんな風にな るでしょう:: TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.static', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ) .. Once that's done, you can refer to :setting:`STATIC_URL` in your templates: これができれば :setting:`STATIC_URL` をテンプレートで参照できます: .. code-block:: html+django .. If ``{{ STATIC_URL }}`` isn't working in your template, you're probably not using :class:`~django.template.RequestContext` when rendering the template. ``{{ STATIC_URL }}`` がテンプレートが使えなければ、おそらくテンプレートのレン ダリングに :class:`~django.template.RequestContext` を使っていないためです。 .. As a brief refresher, context processors add variables into the contexts of every template. However, context processors require that you use :class:`~django.template.RequestContext` when rendering templates. This happens automatically if you're using a :doc:`generic view `, but in views written by hand you'll need to explicitly use ``RequestContext`` To see how that works, and to read more details, check out :ref:`subclassing-context-requestcontext`. 手短に復習すると、コンテキストプロセッサは全てのテンプレートのコンテキストに変 数を追加します。しかし、コンテキストプロセッサはテンプレートのレンダリングに :class:`~django.template.RequestContext` を使うことを要求します。 :doc:`generic view ` を使えば自動的にそうなりますが、 自作のビューでは明示的に ``RequestContext`` を使わなければなりません。 これがどのように動くか知りたければ、 :ref:`subclassing-context-requestcontext` をチェックしてください。 .. Another option is the :ttag:`get_static_prefix` template tag that is part of Django's core. 別の方法は Django 本体に含まれる :ttag:`get_static_prefix` テンプレートタグを 使うことです。 .. With a template tag ------------------- テンプレートタグを使う ---------------------- .. The more powerful tool is the :ttag:`static` template tag. It builds the URL for the given relative path by using the configured :setting:`STATICFILES_STORAGE` storage. よりパワフルなツールが :ttag:`static` テンプレートタグで す。このタグは与えられた相対パスに対して、 :setting:`STATICFILES_STORAGE` スト レージの設定を使って URL を組み立てます。 .. code-block:: html+django {% load staticfiles %} .. It is also able to consume standard context variables, e.g. assuming a ``user_stylesheet`` variable is passed to the template: 通常のコンテキスト変数を受け取ることもできます。例えば ``user_stylesheet`` 変 数がテンプレートに渡されたとすると: .. code-block:: html+django {% load staticfiles %} .. .. note:: There is also a template tag named :ttag:`static` in Django's core set of :ref:`built in template tags` which has the same argument signature but only uses `urlparse.urljoin()`_ with the :setting:`STATIC_URL` setting and the given path. This has the disadvantage of not being able to easily switch the storage backend without changing the templates, so in doubt use the ``staticfiles`` :ttag:`static` template tag. .. note:: Django コアセットの :ref:`ビルトインテンプレートタグ` に含まれる :ttag:`static` テンプレートタグもあります。これは同じ引数を持ちますが、 :setting:`STATIC_URL` 設定と与えられたパスを単に `urlparse.urljoin()`_ に 渡します。これはテンプレートを変更することなく簡単にストレージバックエンド を切り替えることができないという不利な点があります。ですので注意して ``staticfiles`` の :ttag:`static` テンプレートタグを使 いましょう。 .. _`urlparse.urljoin()`: http://docs.python.org/library/urlparse.html#urlparse.urljoin .. _staticfiles-development: .. Serving static files in development =================================== 開発中の静的ファイルの扱い方 ============================ .. The static files tools are mostly designed to help with getting static files successfully deployed into production. This usually means a separate, dedicated static file server, which is a lot of overhead to mess with when developing locally. Thus, the ``staticfiles`` app ships with a **quick and dirty helper view** that you can use to serve files locally in development. このツールは基本的に、運用環境にうまく静的ファイルをデプロイするのを補助するた めに設計されています。これは普通、別途専用で用意された静的ファイルサーバのこと ですが、ローカルでの開発時に使うには大きなオーバーヘッドがかかります。そこで ``staticfiles`` アプリは **手軽でダーティなヘルパービュー** を導入します。これ によって開発中にローカルのファイルを使えるようになります。 .. This view is automatically enabled and will serve your static files at :setting:`STATIC_URL` when you use the built-in :ref:`runserver` management command. ヘルパービューは自動で有効になっています。 :ref:`runserver` コマンドを使った時に :setting:`STATIC_URL` で静的ファイルを公開できます。 .. To enable this view if you are using some other server for local development, you'll add a couple of lines to your URLconf. The first line goes at the top of the file, and the last line at the bottom:: from django.contrib.staticfiles.urls import staticfiles_urlpatterns # ... the rest of your URLconf goes here ... urlpatterns += staticfiles_urlpatterns() ローカル開発で他のサーバを使っている場合、このビューを有効にするには URLconf に 2 行追加する必要があります。 1 つめの行はファイルの先頭に、 2 つめ の行は末尾に書きます:: from django.contrib.staticfiles.urls import staticfiles_urlpatterns # ... URLconf の他の行がここに入ります urlpatterns += staticfiles_urlpatterns() .. This will inspect your :setting:`STATIC_URL` setting and wire up the view to serve static files accordingly. Don't forget to set the :setting:`STATICFILES_DIRS` setting appropriately to let ``django.contrib.staticfiles`` know where to look for files additionally to files in app directories. この関数は :setting:`STATIC_URL` 設定を調べ、静的ファイルを適切に公開できるよ うにビューを設定します。アプリケーションディレクトリの中でどこを探せばいいかを ``django.contrib.staticfiles`` に教えるために、 :setting:`STATICFILES_DIRS` を 設定するのを忘れないでください。 .. .. warning:: This will only work if :setting:`DEBUG` is ``True``. That's because this view is **grossly inefficient** and probably **insecure**. This is only intended for local development, and should **never be used in production**. Additionally, when using ``staticfiles_urlpatterns`` your :setting:`STATIC_URL` setting can't be empty or a full URL, such as ``http://static.example.com/``. .. warning:: ローカル環境でのファイル公開は :setting:`DEBUG` が ``True`` の時にだけ動作 します。 それはこのビューが **ひどく非効率** で、おそらく **セキュアでない** ためで す。このビューはローカル環境での開発だけを意図しており、 **決して運用環境 で使うべきではありません** 。 加えて、 ``staticfiles_urlpatterns`` を使うと、 :setting:`STATIC_URL` 設定は空であったり ``http://static.example.com/`` 完 全な URL であったりできなくなります。 .. For a few more details on how the ``staticfiles`` can be used during development, see :ref:`staticfiles-development-view`. 開発中の ``staticfiles`` の使い方についてもっと詳しく知るには :ref:`staticfiles-development-view` を参照してください。 .. _staticfiles-other-directories: .. Serving other directories ------------------------- 他のディレクトリを公開する -------------------------- .. currentmodule:: django.views.static .. function:: serve(request, path, document_root, show_indexes=False) .. There may be files other than your project's static assets that, for convenience, you'd like to have Django serve for you in local development. The :func:`~django.views.static.serve` view can be used to serve any directory you give it. (Again, this view is **not** hardened for production use, and should be used only as a development aid; you should serve these files in production using a real front-end webserver). プロジェクト内に含まれているものとは別のファイルもあるかもしれません。利便性の ため、ローカル環境での開発で Django に公開させたいのではないでしょうか。 :func:`~django.views.static.serve` ビューは指定したどんなディレクトリも公開で きます。 (繰り返しますが、このビューは運用には耐えません。開発の補助としてだけ 使ってください。運用環境ではこれらのファイルは実際のフロントエンドサーバで公開 すべきです) .. The most likely example is user-uploaded content in :setting:`MEDIA_ROOT`. ``staticfiles`` is intended for static assets and has no built-in handling for user-uploaded files, but you can have Django serve your :setting:`MEDIA_ROOT` by appending something like this to your URLconf:: from django.conf import settings # ... the rest of your URLconf goes here ... if settings.DEBUG: urlpatterns += patterns('', url(r'^media/(?P.*)$', 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, }), ) よくある例は :setting:`MEDIA_ROOT` にユーザがアップロードしたコンテンツです。 ``staticfiles`` は静的アセットを意図していて、ユーザがアップロードしたファイル のハンドリングは含まれていませんが、 URLconf に以下のような記述を追加すること で :setting:`MEDIA_ROOT` を Django に公開させることができます:: from django.conf import settings # ... URLconf の他の部分がここに入ります ... if settings.DEBUG: urlpatterns += patterns('', url(r'^media/(?P.*)$', 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, }), ) .. Note, the snippet assumes your :setting:`MEDIA_URL` has a value of ``'/media/'``. This will call the :func:`~django.views.static.serve` view, passing in the path from the URLconf and the (required) ``document_root`` parameter. このスニペットは :setting:`MEDIA_URL` が ``'/media/'`` という値になっているこ とを仮定しています。 :func:`~django.views.static.serve` を呼び出し、 URLconf と ( 必須の ) ``document_root`` パラメータをパスに渡します。 .. currentmodule:: django.conf.urls.static .. function:: static(prefix, view='django.views.static.serve', **kwargs) .. Since it can become a bit cumbersome to define this URL pattern, Django ships with a small URL helper function :func:`~django.conf.urls.static.static` that takes as parameters the prefix such as :setting:`MEDIA_URL` and a dotted path to a view, such as ``'django.views.static.serve'``. Any other function parameter will be transparently passed to the view. この URL パターンを定義するのはいささか大変になってくるので、 Django は小さな URL ヘルパー関数 :func:`~django.conf.urls.static.static` を持っています。 これは :setting:`MEDIA_URL` のようなプレフィックスと、 ``'django.views.static.serve'`` のようなドット区切りのビューへのパスをパラメー タにとります。他の関数パラメータは透過的にビューに渡されます。 .. An example for serving :setting:`MEDIA_URL` (``'/media/'``) during development:: 開発中に :setting:`MEDIA_URL` (``'/media/'``) を公開する例です:: from django.conf import settings from django.conf.urls.static import static urlpatterns = patterns('', # ... the rest of your URLconf goes here ... ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) .. .. note:: This helper function will only be operational in debug mode and if the given prefix is local (e.g. ``/static/``) and not a URL (e.g. ``http://static.example.com/``). .. note:: このヘルパー関数は、デバッグモードの中で、与えられたプレフィックスが ( 例 ``/static/``) ローカルであって URL ( 例 ``http://static.example.com/``) ではない時にだけ操作できます。 .. _staticfiles-production: .. Serving static files in production ================================== 運用環境での静的ファイル公開 ============================ .. The basic outline of putting static files into production is simple: run the :djadmin:`collectstatic` command when static files change, then arrange for the collected static files directory (:setting:`STATIC_ROOT`) to be moved to the static file server and served. 運用環境に静的ファイルを置くための基本原則はシンプルです。静的ファイルが変 更された時には :djadmin:`collectstatic` コマンドを実行し、集められた静的ファイ ルのディレクトリ (:setting:`STATIC_ROOT`) を静的ファイルサーバに移動し、公開す るために整理します。 .. Of course, as with all deployment tasks, the devil's in the details. Every production setup will be a bit different, so you'll need to adapt the basic outline to fit your needs. Below are a few common patterns that might help. もちろん、あらゆるデプロイタスクと同様、細部には悪魔がいます。運用環境ごとに セットアップには小さな違いがあり、基本原則を必要に合うように変えなければならな いでしょう。以下はその助けになるかもしれないいくつかの共通パターンです。 .. Serving the app and your static files from the same server ---------------------------------------------------------- 一つのサーバでアプリケーションと静的ファイルを扱う -------------------------------------------------- .. If you want to serve your static files from the same server that's already serving your site, the basic outline gets modified to look something like: * Push your code up to the deployment server. * On the server, run :djadmin:`collectstatic` to copy all the static files into :setting:`STATIC_ROOT`. * Point your web server at :setting:`STATIC_ROOT`. For example, here's :ref:`how to do this under Apache and mod_wsgi `. 既にサイトを公開しているのと同じサーバで静的ファイルを公開したい場合、基本原則 は以下のように変更されます: * デプロイサーバにコードを展開します。 * そのサーバ上で :djadmin:`collectstatic` を実行し、全ての静的ファイルを :setting:`STATIC_ROOT` 内にコピーします。 * Web サーバに :setting:`STATIC_ROOT` を教えます。例えば :ref:`Apache と mod_wsgi での方法` があります。 .. You'll probably want to automate this process, especially if you've got multiple web servers. There's any number of ways to do this automation, but one option that many Django developers enjoy is `Fabric`__. このプロセスはきっと自動化したくなるでしょう。特に複数の Web サーバを管理して いる時はそうです。この自動化を行う方法には色々ありますが、 Django を使う開発者 には嬉しいであろう一つの方法が `Fabric`__ です。 __ http://fabfile.org/ .. Below, and in the following sections, we'll show off a few example fabfiles (i.e. Fabric scripts) that automate these file deployment options. The syntax of a fabfile is fairly straightforward but won't be covered here; consult `Fabric's documentation`__, for a complete explanation of the syntax.. 以下とそれに続くセクションでは、いくつかの fabfiles (Fabric scripts のこと ) を示します。それらはファイルのデプロイ方法を自動化してくれます。 fabfile の文 法はかなり直感的ですが、ここで網羅することはできません。 `Fabric ドキュメント`__ を読めば、文法の完全な説明が得られます。 __ http://docs.fabfile.org/ .. So, a fabfile to deploy static files to a couple of web servers might look something like:: from fabric.api import * # Hosts to deploy onto env.hosts = ['www1.example.com', 'www2.example.com'] # Where your project code lives on the server env.project_root = '/home/www/myproject' def deploy_static(): with cd(env.project_root): run('./manage.py collectstatic -v0 --noinput') 静的ファイルを 2 つの Web サーバにデプロイする fabfile はこのようになるでしょ う:: from fabric.api import * # デプロイ先のホスト env.hosts = ['www1.example.com', 'www2.example.com'] # プロジェクトコードが格納される場所 env.project_root = '/home/www/myproject' def deploy_static(): with cd(env.project_root): run('./manage.py collectstatic -v0 --noinput') .. Serving static files from a dedicated server -------------------------------------------- 専用のサーバで静的ファイルを公開する ------------------------------------ .. Most larger Django apps use a separate Web server -- i.e., one that's not also running Django -- for serving static files. This server often runs a different type of web server -- faster but less full-featured. Some good choices are: 大きな Django アプリケーションはたいてい別の Web サーバを静的ファイルの公開に 使っているでしょう。そのサーバでは Django は動いていません。 このサーバは別の種類の Web サーバ、速いがフル機能ではないものを使っていること が多いです。いくつか良い選択肢を挙げると: * lighttpd_ * Nginx_ * TUX_ * Cherokee_ * A stripped-down version of Apache_ .. _lighttpd: http://www.lighttpd.net/ .. _Nginx: http://wiki.nginx.org/Main .. _TUX: http://en.wikipedia.org/wiki/TUX_web_server .. _Apache: http://httpd.apache.org/ .. _Cherokee: http://www.cherokee-project.com/ .. Configuring these servers is out of scope of this document; check each server's respective documentation for instructions. これらのサーバの設定方法はこのドキュメントの範囲を超えますので、説明はそれぞれ のサーバの相当するドキュメントを調べてください。 .. Since your static file server won't be running Django, you'll need to modify the deployment strategy to look something like: * When your static files change, run :djadmin:`collectstatic` locally. * Push your local :setting:`STATIC_ROOT` up to the static file server into the directory that's being served. ``rsync`` is a good choice for this step since it only needs to transfer the bits of static files that have changed. 静的ファイルサーバでは Django を動かせないでしょうから、デプロイ戦略を次のよう に変更する必要があります: * 静的ファイルが変更された時、 :djadmin:`collectstatic` をローカルで実行しま す。 * ローカルの :setting:`STATIC_ROOT` を静的ファイルサーバの公開ディレクトリに アップロードします。 ``rsync`` は変更されたファイルのビットだけを転送するだ けで済むので、この手順の良い選択肢です。 .. Here's how this might look in a fabfile:: from fabric.api import * from fabric.contrib import project # Where the static files get collected locally env.local_static_root = '/tmp/static' # Where the static files should go remotely env.remote_static_root = '/home/www/static.example.com' @roles('static') def deploy_static(): local('./manage.py collectstatic') project.rysnc_project( remote_dir = env.remote_static_root, local_dir = env.local_static_root, delete = True ) fabfile はこのようになるでしょう:: from fabric.api import * from fabric.contrib import project # 静的ファイルがローカル環境で集められる場所 env.local_static_root = '/tmp/static' # 静的ファイルがリモートで置かれる場所 env.remote_static_root = '/home/www/static.example.com' @roles('static') def deploy_static(): local('./manage.py collectstatic') project.rysnc_project( remote_dir = env.remote_static_root, local_dir = env.local_static_root, delete = True ) .. _staticfiles-from-cdn: .. Serving static files from a cloud service or CDN ------------------------------------------------ クラウドサービスや CDN での静的ファイル公開 ------------------------------------------- .. Another common tactic is to serve static files from a cloud storage provider like Amazon's S3__ and/or a CDN (content delivery network). This lets you ignore the problems of serving static files, and can often make for faster-loading webpages (especially when using a CDN). もう一つの一般的な手法は、静的ファイルを Amazon S3__ のようなクラウドストレー ジプロバイダや、 CDN (content delivery network) で公開することです。これにより 静的ファイル公開の問題を気にせずにすみ、またしばしば (CDN を使う場合は特に ) Web ページを高速にロードさせることができます。 .. When using these services, the basic workflow would look a bit like the above, except that instead of using ``rsync`` to transfer your static files to the server you'd need to transfer the static files to the storage provider or CDN. これらのサービスを使う場合、基本的なワークフローは上の話と少し似ていますが、 ``rsync`` を使ってファイルをサーバに転送する代わりに、ストレージプロバイダや CDN に送らなければならないところが違います。 .. There's any number of ways you might do this, but if the provider has an API a :doc:`custom file storage backend ` will make the process incredibly simple. If you've written or are using a 3rd party custom storage backend, you can tell :djadmin:`collectstatic` to use it by setting :setting:`STATICFILES_STORAGE` to the storage engine. これを行う方法は様々ですが、プロバイダに API がある場合、 :doc:`カスタムファイルストレージバックエンド ` を 使えば、手順が信じられないほどシンプルになります。 :setting:`STATICFILES_STORAGE` に、自分が書いた、あるいはサードパーティ製のカ スタムストレージバックエンドを設定することにより、 :djadmin:`collectstatic` に そのバックエンドを使うように教えることができます。 .. For example, if you've written an S3 storage backend in ``myproject.storage.S3Storage`` you could use it with:: 例えば、 S3 ストレージバックエンドを ``myproject.storage.S3Storage`` に書いた とすると、このように使うことができます:: STATICFILES_STORAGE = 'myproject.storage.S3Storage' .. Once that's done, all you have to do is run :djadmin:`collectstatic` and your static files would be pushed through your storage package up to S3. If you later needed to switch to a different storage provider, it could be as simple as changing your :setting:`STATICFILES_STORAGE` setting. こうすれば、 :djadmin:`collectstatic` をするだけで、静的ファイルはあなたのスト レージパッケージを経て S3 にアップロードされます。もし後で別のストレージプロバ イダに変更しなければならなくなっても、単に :setting:`STATICFILES_STORAGE` 設定 を変更するだけで済みます。 .. For details on how you'd write one of these backends, :doc:`/howto/custom-file-storage`. カスタムファイルストレージバックエンドを書く方法の詳細は :doc:`/howto/custom-file-storage` にあります。 .. .. seealso:: The `django-storages`__ project is a 3rd party app that provides many storage backends for many common file storage APIs (including `S3`__). .. seealso:: `django-storages`__ はサードパーティーアプリケーションで、 `S3`__ を含む多 くな一般的なストレージ API のために、数多くのストレージバックエンドを提供 しています。 __ http://s3.amazonaws.com/ __ http://code.larlet.fr/django-storages/ __ http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html .. Upgrading from ``django-staticfiles`` ===================================== ``django-staticfiles`` からアップグレードする ============================================= .. ``django.contrib.staticfiles`` began its life as `django-staticfiles`_. If you're upgrading from `django-staticfiles`_ older than 1.0 (e.g. 0.3.4) to ``django.contrib.staticfiles``, you'll need to make a few changes: ``django.contrib.staticfiles`` は元々 `django-staticfiles`_ として生まれまし た。もし `django-staticfiles`_ 1.0 以前 (0.3.4 など) から ``django.contrib.staticfiles`` にアップグレードしようとすると、いくつかの変更 をしなければなりません: .. * Application files should now live in a ``static`` directory in each app (`django-staticfiles`_ used the name ``media``, which was slightly confusing). * The management commands ``build_static`` and ``resolve_static`` are now called :djadmin:`collectstatic` and :djadmin:`findstatic`. * The settings ``STATICFILES_PREPEND_LABEL_APPS``, ``STATICFILES_MEDIA_DIRNAMES`` and ``STATICFILES_EXCLUDED_APPS`` were removed. * The setting ``STATICFILES_RESOLVERS`` was removed, and replaced by the new :setting:`STATICFILES_FINDERS`. * The default for :setting:`STATICFILES_STORAGE` was renamed from ``staticfiles.storage.StaticFileStorage`` to ``staticfiles.storage.StaticFilesStorage`` * If using :ref:`runserver` for local development (and the :setting:`DEBUG` setting is ``True``), you no longer need to add anything to your URLconf for serving static files in development. * アプリケーションの静的ファイルはそれぞれのアプリケーションの ``static`` ディ レクトリになければなりません。 (`django-staticfiles`_ は ``media`` という 少々混乱させる名前を使っていました) * コマンド ``build_static`` と ``resolve_static`` は今では :djadmin:`collectstatic` と :djadmin:`findstatic` という名前になっています。 * 設定 ``STATICFILES_PREPEND_LABEL_APPS``, ``STATICFILES_MEDIA_DIRNAMES``, ``STATICFILES_EXCLUDED_APPS`` は削除されまし た。 * 設定 ``STATICFILES_RESOLVERS`` は削除され、新しい :setting:`STATICFILES_FINDERS` に置き換えられました。 * :setting:`STATICFILES_STORAGE` のデフォルトは ``staticfiles.storage.StaticFileStorage`` から ``staticfiles.storage.StaticFilesStorage`` にリネームされました。 * ローカル環境で :ref:`runserver` を使う時 (:setting:`DEBUG` 設定が ``True`` の時) 、開発中の静的ファイル公開のために URLconf に何も追加する必要がなくなりました。 .. Learn more ========== さらに学ぶためには ================== .. This document has covered the basics and some common usage patterns. For complete details on all the settings, commands, template tags, and other pieces include in ``django.contrib.staticfiles``, see :doc:`the staticfiles reference `. このドキュメントでは基本といくつかのよくある使用パターンについて説明しました。 ``django.contrib.staticfiles`` に含まれる全ての設定、コマンド、テンプレートタ グ、その他について、完全な詳細を知るには :doc:`staticfiles リファレンス ` を参照してください。