您的位置:首页 > 编程语言 > Go语言

Django中管理使用静态文件

2013-02-17 17:18 656 查看

Managing static files

原文地址:https://docs.djangoproject.com/en/dev/howto/static-files/

Django developers mostly concern themselves with the dynamic parts of web applications – the views and templates that render a new 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应用还有另外一个部分:静态文件(图片,样式表,js脚本等等)在一个完整的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服务器可以找到的位置。然而,对于大型工程,尤其是含有多个app的复杂工程,处理各个应用提供的一系列的静态文件将变得麻烦。

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 asdjango-staticfiles
and was merged into Django 1.3.

如果你曾使用过第三方的django-staticfiles应用,这与django.contrib.staticfiles看起来会很相似。这是因为他们本质上都是相同的代码:django.contrib.staticfiles由django-staticfiles开发展而来,并被合并到了Django1.3版本中。

If you’re upgrading from django-staticfiles, please seeUpgrading from
django-staticfiles, below, for a few minor changes you’ll need to make.

如果你正在从django-staticfiles升级,请看Upgrading from django-staticfiles,以下你需要注意几个次要变化。

1. Using django.contrib.staticfiles

1.1 Basic usage

1.2 Deploying static files in a nutshell

2. Referring to static files in templates

2.1 With a context processor

2.2 With a template tag

3. 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程序附带一个快速和dirty(无法翻译的词,解释不通)的辅助视图,您可以在开发中使用它在本地服务器提供文件。

This view is automatically enabled and will serve your static files at STATIC_URL when you use the built-in runserver management command.

当使用内置的runserver管理命令时,这一视图会自动被使用并且以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:

为了使用这个视图(如果你使用了一些其它的服务器做本地部署)你需要在URLconf中添加几行。第一行位于配置文件的第一行,最后一行在文件低端。

from django.contrib.staticfiles.urls import staticfiles_urlpatterns

# ... the rest of your URLconf goes 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 additionally to files in app directories.

这会检查你STATIC_URL的设置并接通视图服务提供静态文件。不要忘记设置适当的设置STATICFILES_DIRS项使django.contrib.staticfiles能够知晓在app目录的什么位置去寻找要加载的文件。

Warning

This will only work if DEBUG is True.这只有在DEBUG为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_url patterns your STATIC_URL setting can’t be empty or a full URL, such as http://static.example.com/.
另外,当使用staticfiles_url时,STATIC_URL的配置不能为空或者一个整路径。

For a few more details on how the staticfiles can be used during development, seeStatic file development view.

在开发过程中,想要了解更多关于静态文件如何使用的信息,请参考Static file development view

3.1 Serving other directories 为其它目录服务

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 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).

The most likely example is user-uploaded content in 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 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<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)


Note, the snippet assumes your MEDIA_URL has a value of '/media/'. This will call the serve() view, passing in the path from the URLconf and the (required) document_root parameter.

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 static() that takes as parameters the prefix such as 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.

An example for serving MEDIA_URL ('/media/') during development:

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/).

4. Serving static files in production

The basic outline of putting static files into production is simple: run the collectstatic command when static files change, then arrange for the collected static files directory (STATIC_ROOT) to be moved to the static file server and served.

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.

4.1 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 alreadyserving your site, the basic outline gets modified to look something like:

Push your code up to the deployment server.
On the server, run
collectstatic to copy all the static filesintoSTATIC_ROOT.
Point your web server at
STATIC_ROOT. For example, here’show to do this under
Apache and mod_wsgi.
You’ll probably want to automate this process, especially if you’ve gotmultiple web servers. There’s any number of ways to do this automation, butone option that many Django developers enjoy isFabric.

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 syntaxof a fabfile is fairly straightforward but won’t be covered here; consultFabric’s
documentation, for a complete explanation of the syntax..

So, a fabfile to deploy static files to a couple of web servers might looksomething 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')

4.2 Serving static files from a dedicated server

Most larger Django apps use a separate Web server – i.e., one that’s not alsorunning Django – for serving static files. This server often runs a differenttype of web server – faster but less full-featured. Some good choices are:

lighttpd
Nginx
TUX
Cherokee
A stripped-down version of
Apache
Configuring these servers is out of scope of this document; check eachserver’s respective documentation for instructions.

Since your static file server won’t be running Django, you’ll need to modifythe deployment strategy to look something like:

When your static files change, run
collectstatic locally.
Push your local
STATIC_ROOT up to the static file serverinto the directory that’s being served.rsync is a goodchoice for this step
since it only needs to transfer thebits of static files that have changed.
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.rsync_project(
remote_dir = env.remote_static_root,
local_dir = env.local_static_root,
delete = True
)


4.3 Serving static files from a cloud service or CDN

Another common tactic is to serve static files from a cloud storage providerlike Amazon’sS3 and/or a CDN (content delivery network). This lets youignore the problems of serving static files,
and can often make forfaster-loading webpages (especially when using a CDN).

When using these services, the basic workflow would look a bit like the above,except that instead of usingrsync to transfer your static files to theserver you’d need to transfer the static files
to the storage provider or CDN.

There’s any number of ways you might do this, but if the provider has an API acustom file storage backend will make theprocess incredibly simple.
If you’ve written or are using a 3rd party customstorage backend, you can tell
collectstatic to use it by settingSTATICFILES_STORAGE
to the storage engine.

For example, if you’ve written an S3 storage backend inmyproject.storage.S3Storage you could use it with:

STATICFILES_STORAGE = 'myproject.storage.S3Storage'

Once that’s done, all you have to do is run
collectstatic and yourstatic files would be pushed through your storage package up to S3. If youlater needed to switch to a different storage provider, it could be as simpleas
changing your
STATICFILES_STORAGE setting.

For details on how you’d write one of these backends,Writing a custom storage system.

See also
The
django-storages project is a 3rd party app that provides manystorage backends for many common file storage APIs (includingS3).

5. Upgrading from django-staticfiles

6. Learn more

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: