部署静态文件
想要 的使用指南,请参考 管理静态文件(比如图片、JavaScript、CSS)。
The basic outline of putting static files into production consists of two steps: run the 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. Depending on , files may need to be moved to a new location manually or the post_process
method of the Storage
class might take care of that.
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.
如果你想在早已提供站点服务器服务器上同时提供静态文件服务,操作步骤类似这样:
- 将代码推送至部署服务器。
- 在服务器上运行 ,将所有的静态文件拷贝至
STATIC_ROOT
。
大多数大型 Django 站点使用一个独立的 Web 服务器——即,该服务器并未运行 Django,值提供静态文件服务。这种服务器一般运行一种不同的 Web 服务器——更快,更简单。常见选项如下:
- 一个 Apache 的朴素版本
如何配置这些服务器超出了本文范围;查阅这些服务器各自的文档获取介绍。
由于静态文件服务器并不运行 Django,你需要将部署策略改成这样:
- 当静态文件改变时,本地运行 。
另一种常见的策略是从类似亚马逊 S3 的云存储服务商或 CDN (content delivery network) 提供静态文件服务。这能让你忽略提供静态文件服务可能出现的问题,提供 Web 页面加载速度(尤其是在用 CDN 的时候)。
There’s any number of ways you might do this, but if the provider has an API, you can use a custom file storage backend to integrate the CDN with your Django project. If you’ve written or are using a 3rd party custom storage backend, you can tell to use it by setting STATICFILES_STORAGE
to the storage engine.
例如,若你已在 myproject.storage.S3Storage
中写了一个 S3 存储后端,可以这么用:
Once that’s done, all you have to do is run 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, you may only have to change your STATICFILES_STORAGE
setting.
关于如何编写这些后端的细节,参考 。有很多可用的第三方应用提供了针对常见文件存储 API 的存储后端。 djangopackages.org 入门 是个不错的起点。