Aplikasi staticfiles¶
django.contrib.staticfiles menyimpan berkas-berkas tetap dari setiap dari aplikasi anda (dan setiap tempat lain anda tentukan) kedalam tempat tunggal yang dapat dengan mudah dilayani di produksi.
lihat juga
Untuk sebuah perkenalaln pada aplikasi berkas-berkas tetap dan beberapa penggunaan contoh, lihat Mengelola berkas statis (sebagai contoh gambar, JavaScript, CSS). Untuk panduan dalam menyebarkan berkas-berkas tetap, lihat menyebarkan berkas tetap.
Pengaturan¶
Lihat staticfiles settings untuk rincian pada pengaturan berikut:
Pengelolaan perintah¶
django.contrib.staticfiles membuka tiga perintah pengelolaan.
collectstatic¶
-
django-admin collectstatic¶
Kumpulkan berkas-berkas tetap kedalam STATIC_ROOT.
Duplicate file names are by default resolved in a similar way to how template
resolution works: the file that is first found in one of the specified
locations will be used. If you're confused, the findstatic command
can help show you which files are found.
On subsequent collectstatic runs (if STATIC_ROOT isn't empty), files
are copied only if they have a modified timestamp greater than the timestamp of
the file in STATIC_ROOT. Therefore if you remove an application from
INSTALLED_APPS, it's a good idea to use the collectstatic
--clear option in order to remove stale static files.
Files are searched by using the enabled finders. The default is to look in all locations defined in
STATICFILES_DIRS and in the 'static' directory of apps
specified by the INSTALLED_APPS setting.
Perintah pengelolaan collectstatic memanggil metode post_process() dari STATICFILES_STORAGE setiap berjalan dan melewatkan daftar jalur yang telah ditemukan oleh perintah pengelolaan. Itu juga menerima semua pilihan baris perintah dari collectstatic. Ini digunakan oleh CachedStaticFilesStorage secara awalan.
By default, collected files receive permissions from
FILE_UPLOAD_PERMISSIONS and collected directories receive permissions
from FILE_UPLOAD_DIRECTORY_PERMISSIONS. If you would like different
permissions for these files and/or directories, you can subclass either of the
static files storage classes and specify the
file_permissions_mode and/or directory_permissions_mode parameters,
respectively. For example:
from django.contrib.staticfiles import storage
class MyStaticFilesStorage(storage.StaticFilesStorage):
def __init__(self, *args, **kwargs):
kwargs['file_permissions_mode'] = 0o640
kwargs['directory_permissions_mode'] = 0o760
super(MyStaticFilesStorage, self).__init__(*args, **kwargs)
Kemudian setel pengaturan STATICFILES_STORAGE menjadi 'path.to.MyStaticFilesStorage'.
Beberapa pilihan umum digunakan adalah:
-
--noinput,--no-input¶ Do NOT prompt the user for input of any kind.
-
--ignorePATTERN,-iPATTERN¶ Abaikan berkas-berkas atau direktori cocok dengan pola gaya-global ini. Gunakan beberapa kali untuk mengabaikan lebih.
-
--dry-run,-n¶ Lakukan apapun kecuali merubah sistem berkas.
-
--clear,-c¶ Bersihkan berkas-berkas yang ada sebelum mencoba menyalin atau menaut berkas asli.
-
--link,-l¶ Buat sebuah tautan simbolus pada setiap berkas daripada menyalin.
-
--no-post-process¶ Jangan memanggil metode
post_process()dari backend penyimpananSTATICFILES_STORAGEyang sudah dikonfigurasi.
-
--no-default-ignore¶ Jangan abaikan pola-gaya-blobal pribadi umum
'CVS','.*'dan'*~'.
Untuk daftar penuh dari pilihan, mengacu pada perintah bantuan sendiri dengan menjalankan:
$ python manage.py collectstatic --help
Menyesuaikan daftar pola diabaikan¶
The default ignored pattern list, ['CVS', '.*', '*~'], can be customized in
a more persistent way than providing the --ignore command option at each
collectstatic invocation. Provide a custom AppConfig
class, override the ignore_patterns attribute of this class and replace
'django.contrib.staticfiles' with that class path in your
INSTALLED_APPS setting:
from django.contrib.staticfiles.apps import StaticFilesConfig
class MyStaticFilesConfig(StaticFilesConfig):
ignore_patterns = [...] # your custom ignore list
findstatic¶
-
django-admin findstatic staticfile [staticfile ...]¶
Mencari untuk satu atau lebih jalur relatif dengan diadakan penemu.
Sebagai contoh:
$ python manage.py findstatic css/base.css admin/js/core.js
Found 'css/base.css' here:
/home/special.polls.com/core/static/css/base.css
/home/polls.com/core/static/css/base.css
Found 'admin/js/core.js' here:
/home/polls.com/src/django/contrib/admin/media/js/core.js
-
findstatic--first¶
By default, all matching locations are found. To only return the first match
for each relative path, use the --first option:
$ python manage.py findstatic css/base.css --first
Found 'css/base.css' here:
/home/special.polls.com/core/static/css/base.css
This is a debugging aid; it'll show you exactly which static file will be collected for a given path.
Dengan mengatur bendera --verbosity menjadi 0, anda dapat menekan keluaran tambahan dan hanya mendapatkan nama-nama jalur:
$ python manage.py findstatic css/base.css --verbosity 0
/home/special.polls.com/core/static/css/base.css
/home/polls.com/core/static/css/base.css
Di pihak lain, dengan mengatur bendera --verbosity menjadi 2, anda dapat mendapatkan semua direktori yang telah dicari:
$ python manage.py findstatic css/base.css --verbosity 2
Found 'css/base.css' here:
/home/special.polls.com/core/static/css/base.css
/home/polls.com/core/static/css/base.css
Looking in the following locations:
/home/special.polls.com/core/static
/home/polls.com/core/static
/some/other/path/static
runserver¶
-
django-admin runserver [addrport]¶
Overrides the core runserver command if the staticfiles app
is installed and adds automatic serving of static
files. File serving doesn't run through MIDDLEWARE.
The command adds these options:
-
--nostatic¶
Use the --nostatic option to disable serving of static files with the
staticfiles app entirely. This option is
only available if the staticfiles app is
in your project's INSTALLED_APPS setting.
Contoh penggunaan:
django-admin runserver --nostatic
-
--insecure¶
Use the --insecure option to force serving of static files with the
staticfiles app even if the DEBUG
setting is False. By using this you acknowledge the fact that it's
grossly inefficient and probably insecure. This is only intended for
local development, should never be used in production and is only
available if the staticfiles app is
in your project's INSTALLED_APPS setting. runserver
--insecure doesn't work with
CachedStaticFilesStorage.
Contoh penggunaan:
django-admin runserver --insecure
Penyimpanan¶
StaticFilesStorage¶
-
class
storage.StaticFilesStorage¶
A subclass of the FileSystemStorage
storage backend that uses the STATIC_ROOT setting as the base
file system location and the STATIC_URL setting respectively
as the base URL.
-
storage.StaticFilesStorage.post_process(paths, **options)¶
This method is called by the collectstatic management command
after each run and gets passed the local storages and paths of found
files as a dictionary, as well as the command line options.
The CachedStaticFilesStorage
uses this behind the scenes to replace the paths with their hashed
counterparts and update the cache appropriately.
ManifestStaticFilesStorage¶
-
class
storage.ManifestStaticFilesStorage¶
A subclass of the StaticFilesStorage
storage backend which stores the file names it handles by appending the MD5
hash of the file's content to the filename. For example, the file
css/styles.css would also be saved as css/styles.55e7cbb9ba48.css.
The purpose of this storage is to keep serving the old files in case some pages still refer to those files, e.g. because they are cached by you or a 3rd party proxy server. Additionally, it's very helpful if you want to apply far future Expires headers to the deployed files to speed up the load time for subsequent page visits.
The storage backend automatically replaces the paths found in the saved
files matching other saved files with the path of the cached copy (using
the post_process()
method). The regular expressions used to find those paths
(django.contrib.staticfiles.storage.HashedFilesMixin.patterns)
by default covers the @import rule and url() statement of Cascading
Style Sheets. For example, the 'css/styles.css' file with the
content
@import url("../admin/css/base.css");
would be replaced by calling the url()
method of the ManifestStaticFilesStorage storage backend, ultimately
saving a 'css/styles.55e7cbb9ba48.css' file with the following
content:
@import url("../admin/css/base.27e20196a850.css");
-
storage.ManifestStaticFilesStorage.max_post_process_passes¶
Since static files might reference other static files that need to have their
paths replaced, multiple passes of replacing paths may be needed until the file
hashes converge. To prevent an infinite loop due to hashes not converging (for
example, if 'foo.css' references 'bar.css' which references
'foo.css') there is a maximum number of passes before post-processing is
abandoned. In cases with a large number of references, a higher number of
passes might be needed. Increase the maximum number of passes by subclassing
ManifestStaticFilesStorage and setting the max_post_process_passes
attribute. It defaults to 5.
Previous versions didn't make multiple passes to ensure file hashes
converged, so often times file hashes weren't correct. The
max_post_process_passes attribute was added.
To enable the ManifestStaticFilesStorage you have to make sure the
following requirements are met:
- the
STATICFILES_STORAGEsetting is set to'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' - Pengaturan
DEBUGdisetel keFalse - Anda telah mengumpulkan semua berkas tetap dengan menggunakan perintah pengelolaan
collectstatic
In older versions, you also had to use
{% load static from staticfiles %} in your template. The
static template tag ({% load static %}) now uses
django.contrib.staticfiles if it's installed.
Since creating the MD5 hash can be a performance burden to your website
during runtime, staticfiles will automatically store the mapping with
hashed names for all processed files in a file called staticfiles.json.
This happens once when you run the collectstatic management
command.
-
storage.ManifestStaticFilesStorage.manifest_strict¶
If a file isn't found in the staticfiles.json manifest at runtime, a
ValueError is raised. This behavior can be disabled by subclassing
ManifestStaticFilesStorage and setting the manifest_strict attribute to
False -- nonexistent paths will remain unchanged.
The manifest_strict attribute was added. In older versions, the
behavior is the same as manifest_strict=False.
Due to the requirement of running collectstatic, this storage
typically shouldn't be used when running tests as collectstatic isn't run
as part of the normal test setup. During testing, ensure that the
STATICFILES_STORAGE setting is set to something else like
'django.contrib.staticfiles.storage.StaticFilesStorage' (the default).
-
storage.ManifestStaticFilesStorage.file_hash(name, content=None)¶
The method that is used when creating the hashed name of a file. Needs to return a hash for the given file name and content. By default it calculates a MD5 hash from the content's chunks as mentioned above. Feel free to override this method to use your own hashing algorithm.
CachedStaticFilesStorage¶
-
class
storage.CachedStaticFilesStorage¶
CachedStaticFilesStorage is a similar class like the
ManifestStaticFilesStorage class
but uses Django's caching framework for storing the
hashed names of processed files instead of a static manifest file called
staticfiles.json. This is mostly useful for situations in which you don't
have access to the file system.
If you want to override certain options of the cache backend the storage uses,
simply specify a custom entry in the CACHES setting named
'staticfiles'. It falls back to using the 'default' cache backend.
Peringatan
CachedStaticFilesStorage isn't recommended -- in almost all cases
ManifestStaticFilesStorage is a better choice. There are several
performance penalties when using CachedStaticFilesStorage since a cache
miss requires hashing files at runtime. Remote file storage require several
round-trips to hash a file on a cache miss, as several file accesses are
required to ensure that the file hash is correct in the case of nested file
paths.
Finders Module¶
staticfiles finders has a searched_locations attribute which is a list
of directory paths in which the finders searched. Example usage:
from django.contrib.staticfiles import finders
result = finders.find('css/base.css')
searched_locations = finders.searched_locations
Other Helpers¶
There are a few other helpers outside of the
staticfiles app to work with static
files:
- The
django.template.context_processors.static()context processor which addsSTATIC_URLto every template context rendered withRequestContextcontexts. - The builtin template tag
staticwhich takes a path and urljoins it with the static prefixSTATIC_URL. Ifdjango.contrib.staticfilesis installed, the tag uses theurl()method of theSTATICFILES_STORAGEinstead. - The builtin template tag
get_static_prefixwhich populates a template variable with the static prefixSTATIC_URLto be used as a variable or directly. - The similar template tag
get_media_prefixwhich works likeget_static_prefixbut usesMEDIA_URL.
Static file development view¶
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.
-
views.serve(request, path)¶
This view function serves static files in development.
Peringatan
This view will only work if 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.
Catatan
Untuk menebak jenis isi berkas dilayani, tampilan ini bergantung pada modul mimetypes dari pustaka standar Python, yang itu sendiri bergantung pada pokok berkas peta serambi. Jika anda menemukan bahwa tampilan ini tidak mengembalikanjenis isi yang sesuai untuk berkas-berkas tertent, itu kebanyakan sepertinya bahwa berkas-berkas peta serambi butuh diperbaharui. Ini dapat dicapai, sebagai contoh, dengan memasang atau memperbaharui paket mailcap pada penyaluran Red Hat, atau mime-support pada penyaluran Debian.
This view is automatically enabled by runserver (with a
DEBUG setting set to True). To use the view with a different
local development server, add the following snippet to the end of your
primary URL configuration:
from django.conf import settings
from django.contrib.staticfiles import views
if settings.DEBUG:
urlpatterns += [
url(r'^static/(?P<path>.*)$', views.serve),
]
Note, the beginning of the pattern (r'^static/') should be your
STATIC_URL setting.
Since this is a bit finicky, there's also a helper function that'll do this for you:
-
urls.staticfiles_urlpatterns()¶
This will return the proper URL pattern for serving static files to your already defined pattern list. Use it like this:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf here ...
urlpatterns += staticfiles_urlpatterns()
This will inspect your STATIC_URL setting and wire up the view
to serve static files accordingly. Don't forget to set the
STATICFILES_DIRS setting appropriately to let
django.contrib.staticfiles know where to look for files in addition to
files in app directories.
Peringatan
This helper function will only work if DEBUG is True
and your STATIC_URL setting is neither empty nor a full
URL such as http://static.example.com/.
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.
Specialized test case to support 'live testing'¶
-
class
testing.StaticLiveServerTestCase¶
This unittest TestCase subclass extends django.test.LiveServerTestCase.
Just like its parent, you can use it to write tests that involve running the code under test and consuming it with testing tools through HTTP (e.g. Selenium, PhantomJS, etc.), because of which it's needed that the static assets are also published.
But given the fact that it makes use of the
django.contrib.staticfiles.views.serve() view described above, it can
transparently overlay at test execution-time the assets provided by the
staticfiles finders. This means you don't need to run
collectstatic before or as a part of your tests setup.