Commit 33b025d1 by Timothée Peignier

update docs to sphinx

parent 2df0ec93
...@@ -6,3 +6,4 @@ ...@@ -6,3 +6,4 @@
build build
dist dist
MANIFEST MANIFEST
docs/_build/
h1. Backwards Incompatible Changes
_A list of backwards incompatible changes_
h3. Revision 53
http://code.google.com/p/django-compress/source/detail?r=53
Changed the default media type for CSS to "all" instead of "media,projection". You can still specify media type with `extra_context`.
h3. Revision 56
http://code.google.com/p/django-compress/source/detail?r=56
*bump_filename completely changed*
bump_filename was broken because a lot of caches does not properly cache files with querystrings. Therefore it is completely rewritten without any thoughts on backwards compatibility, since it was not possible anyways. This changeset also introduces a couple of other changes that could potentially break old code.
* The `bump_filename` option was removed from the group settings. There is no need specifying it for ALL groups, if you actually use it, you most likely want to use it on all your compressed files.
* The bump_filename options is replaced by the setting COMPRESS_VERSION, and is completely ignored.
* The querystring is no longer used to determine a files version, since it was use
* If COMPRESS_VERSION is used, you specify the version part of the `output_filename` file with '?'. This placeholder can be changed with COMPRESS_VERSION_PLACEHOLDER.
E.g.:
<pre>
<pre><code>
'screen': {
'source_filenames': ('css/screen/style.css', 'css/screen/paginator.css', 'css/screen/agenda.css', 'css/screen/weather.css', 'css/screen/gallery.css', ),
'output_filename': 'c/screen.r?.css',
},
</code></pre>
</pre>
* COMPRESS_VERSION requires COMPRESS_AUTO to be enabled. COMPRESS_AUTO is enabled by default, but if you explicitly set it to `False` an ImproperlyConfiguredError exception will be thrown.
COMPRESS_AUTO changes
* The CSS/Javascript files are not checked during Django's initialization anymore. It was not really useful and did not make sense. The automatic part is now handled by the templatetags (i.e. what used to be COMPRESS_TEMPLATE_AUTO).
* COMPRESS_AUTO is replaced by COMPRESS_AUTO_TEMPLATE, and the old behavior of COMPRESS_AUTO is removed. This might be really confusing, the Configuration should make it clear.
\ No newline at end of file
h1. Customization
_Describes how to customize and add your own functionality to django-compress_
django-compress can be customized an a couple of ways.
If you need to change the output of the HTML-tags generated from the templatetags, this can be done by overriding the templates <tt>compress/css.html</tt> and <tt>compress/js.html</tt>.
You can also write your own filter-class, if you for example want to implement other types of compressors. All you need to do is to define a filter_css and/or a filter_js functions in a class that inherits from <tt>compress.filter_base.FilterBase</tt>, and specify it in the tuple of filters (<tt>COMPRESS_CSS_FILTERS</tt>/<tt>COMPRESS_JS_FILTERS</tt>) (see [Configuration] for more information) in the settings.
For now, see the files under [http://django-compress.googlecode.com/svn/trunk/filters/ filters/] for more details. CSSTidyFilter uses and external program, and JSMinCompressor just calls a Python-function, so it will probably be able to point you in the right direction when writing custom filters.
\ No newline at end of file
h1. Far Future Expires
_Details about the "Far Future Expires" technique, and how to implement it with help from django-compress_
h3. General details and considerations about the "Far Future Expires" technique
(you can skip this if you already know what it is)
If you really want to make sure that your CSS and JavaScript files get cached by the browser (and possibly by proxies), you should use "Far Future Expires". This means that you send the Expires HTTP-header with a date that is far in the future, resulting in the file being cached at the client (almost) forever
If you do not specify an Expires header, the files will be requested again, and the server will respond "304 Not Modified" - which means that the file that the client got in its cache is still up-to-date. *However, a HTTP request will still be made anyway.* The actual data does not get sent, but there will still be unnecessary HTTP requests, which can be avoided.
Most modern browser implement "Heuristic expiration", so it will actually not be "304 Not Modified" for your static files on every request, however, the [http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html HTTP specification does not specify] (see section 13.2.2) how "Heuristic expiration" should be handled by the browsers. Therefore it is recommended to explicitly set the Expires header, to make sure all browsers cache the files in the preferred way.
This technique obviously has a drawback, when you want to change your files, you need to change their names, since their URLs will be cached... that's right: forever! The solution to that is pretty obvious too: change the URLs.
h3. django-compress with COMPRESS_VERSION
If you specify <tt>COMPRESS_VERSION</tt> in your configuration, you can add a placeholder to the filenames to output the version number of the different files. See [Configuration]) for more information. The filename itself will be changed when any of the source files are updated.
h3. Configuration of web server (that serves MEDIA_URL)
h4. Apache
Expires-control in Apache is handled by mod_expires:
See documentation for more information:
* [http://httpd.apache.org/docs/2.2/mod/mod_expires.html mod_expires in Apache documentation]
h4. Example
<pre><code>
<Directory /your/media/root/css>
ExpiresActive on
ExpiresDefault "access plus 10 years"
</Directory>
</code></pre>
Apache also allows the specify files by their mime-type:
<pre><code>
ExpiresActive On
ExpiresByType text/css "access plus 10 years"
ExpiresByType application/x-javascript "access plus 10 years"
</code></pre>
h4. lighttpd
lighttpd handles Expires similar to Apache, with a module called mod_expire.
* [http://trac.lighttpd.net/trac/wiki/Docs%3AModExpire mod_expire in lighttpd documentation]
h4. Example
Set far future headers on all files under /media/css/ and /media/js/.
<pre><code>
$HTTP["url"] =~ "^/media/css/" {
expire.url = ( "" => "access 10 years" )
}
$HTTP["url"] =~ "^/media/js/" {
expire.url = ( "" => "access 10 years" )
}
</code></pre>
h4. nginx
nginx's <tt>ngx_http_headers_module</tt> provides the <tt>expires</tt> option, which control the <tt>Expires</tt> and <tt>Cache-Control</tt> HTTP headers.
* [http://wiki.codemongers.com/NginxHttpHeadersModule ngx_http_headers_module in nginx documentation]
h4. Example
This will set expiration to the maximum expiration:
<pre><code>
location /media/js {
expires max;
}
location /media/css {
expires max;
}
</code></pre>
\ No newline at end of file
h1. django-compress features
This is a application that will provide an easy and automated way to output compressed/minified CSS and JavaScript. It adheres to the DRY principle, you set up your CSS-files and JavaScript-files in your project settings, and you are done. There is no need to enter the names in your template again (a couple of template tags takes care of that).
* Group/concatenate your CSS/JavaScript source files to single files, and run the code through specified filters
* Provides sane defaults for CSS (CSSTidy required) and JavaScript minification.
* A filter for YUI Compressor is included.
* It’s easy and straightforward to write custom compressors/filters to generate the output. Filters for jsmin and CSSTidy is included by default.
* A last-modifcation/version part can automatically be appended to the filename of the outputted files to make use of “far future Expires HTTP header), and provide an automated way of updating the content without delays.
* You setup and group your CSS and JavaScript-files in the settings, and set up whetter or not you want your files to be compressed.
* Templatetags to output CSS (<link...>) or JavaScript (<script...>) tags with the compressed files if COMPRESS = True, or otherwise the source files.
* The compressed files will be updated (if neeeded) when you are accessing them from the templatetags. This only applies when COMPRESS_AUTO is enabled. You can manually update them with “./manage.py synccompress”.
\ No newline at end of file
h1. Installation
Installation is pretty straight-forward and follows the same installation procedure as many other Django applications. django-compress does not create any models, so you do not need to configure a database.
h3. Recommendations
By default django-compress uses CSSTidy to compress CSS. CSSTidy is an excellent stand-alone application for dealing with CSS-files. CSSTidy can be downloaded from: http://csstidy.sourceforge.net/. If you do not install CSSTidy, make sure to disable the filter in your settings (by setting COMPRESS_CSS_FILTERS = None).
h3. Install instructions
# Get the code from svn: svn co http://django-compress.googlecode.com/svn/trunk/ django-compress
** Use the setup.py script to install: python setup.py install
** OR manually put the compress-directory somewhere on your PYTHONPATH
# Add 'compress' to your INSTALLED_APPS
h3. Using git?
The main source repository is now available at github: http://github.com/pelme/django-compress/tree/master
The Subversion repository at Google Code will still be updated, though.
If you want to grab django-compress via git, use: git clone git://github.com/pelme/django-compress.git
\ No newline at end of file
h1. Introduction
_Short introduction to performance tweaks and what django-compress does_
JavaScript and CSS minification/compression can decrease load times of sites a lot.
It is important to reduce the number of requests that are made. Fewer files means better performance. However, when you develop CSS, and particularly if you are building a big site, it can be nice to separate different parts of the site’s CSS into different files. You also want to keep the CSS and JavaScript in different files while you develop, to make debugging easier.
It is also nice to comment CSS and JavaScript, but you do not want the overhead of sending the comments and whitespaces to the clients.
You also want to make sure that as much of the static content is cached as much as possible at the client. The ideal is to even avoid “304 Not Modified” which are returned when a client requested something that has already been cached, and does not need to be updated. This can be accomplished by setting the HTTP Expire header to a date far in the future. That will force the browser not to ask for updates for that URL. However, when you need to update your files, you will need to give them a new URL, to push the updated files to the clients.
These techniques has been described more in depth at Yahoo:
* http://developer.yahoo.com/performance/rules.html#num_http
* http://developer.yahoo.com/performance/rules.html#minify
* http://developer.yahoo.com/performance/rules.html#expires
django-compress tries to address those issues with as little manual intervention as possible, whilst still being configurable enough to not get in your way. Read more about the [Features].
There are numerous of other techniques that could be used to improve performance, Yahoo has an excellent page that lists the most common:
* http://developer.yahoo.com/performance/rules.html
\ No newline at end of file
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/django-compress.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/django-compress.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/django-compress"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/django-compress"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
make -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
h1. Usage
_Describes how to use django-compress when it is installed and configured_
h3. Automated generation
If <tt>COMPRESS</tt> and <tt>COMPRESS_AUTO</tt> is enabled (<tt>True</tt>), the source files will be automatically updated, and re-generated IF NEEDED when invoked from the templatetags. The last modified time of the files will be compared, and if any of the source-files is newer than the output-file, the file will be re-generated.
h3. Management command
You can update and force updates of the compressed file(s) with the management command “synccompress”. This makes it possible to keep the files updated manually.
The command is
<pre><code>
./manage.py synccompress
</code></pre>
(assuming you are in you project-folder that contains <tt>manage.py</tt>). To force all files to be re-generated, use the argument <tt>--force</tt> (e.g. <tt>./manage.py synccompress --force</tt>)
h3. Templatetags
django-compress includes two template tags: <tt>compressed_css</tt> and <tt>compressed_js</tt>, in a template library called <tt>compressed</tt>
They are used to output the <link> and <script>-tags for the specified CSS/JavaScript-groups (as specified in the settings). The first argument must be the name of the CSS/JavaScript group.
The templatetags will either output the source filenames or the compressed filenames, depending on the <tt>COMPRESS</tt> setting, if you do not specify the <tt>COMPRESS</tt> setting, the source files will be used in DEBUG-mode, and compressed files in non-DEBUG-mode.
h4. Example
If you have specified the CSS-groups “my_screen_css” and “my_print_css” and a JavaScript-group with the name “my_scripts”, you would use the following code to output them all:
<pre><code>
{% load compressed %}
{% compressed_css 'my_screen_css' %}
{% compressed_css 'my_print_css' %}
{% compressed_js 'my_scripts' %}
</code></pre>
h3. Far future Expires
Far future Expires can be used with the bump_filename-option, see the FarFutureExpires page for more information.
\ No newline at end of file
h1. Versioning
There are several ways for generating version strings. Basically, two types are available. These are: mtime version strings and hash version strings.
h3. mtime version strings (default)
This is the default method for generating version strings. In short, when invoked, it checks whether any of the source files system timestamps (mtime) is newer than the version string of the corresponding compressed file. If that is the case, the compressed output file version string will be the mtime of the most recent source file.
h3. hash version strings
Hash-based versioning works by generating a hash string based on the contents of the source files. Available hash-based versioning methods are MD5 and SHA-1.
h4. MD5 version strings
To generate MD5 version strings, put this in your settings.py:
<pre><code>
COMPRESS_VERSIONING = 'compress.versioning.hash.MD5Versioning'
</code></pre>
h4. SHA-1 version string
To generate SHA-1 version strings, put this in your settings.py:
<pre><code>
COMPRESS_VERSIONING = 'compress.versioning.hash.SHA1Versioning'
</code></pre>
h3. Git version strings
Versions formed on git revisions in codebase. Provides a fast way to check if any of your files changed that
will be consistent across multiple web servers so that they all generate the same version numbers for each
set of source files, assuming their git repositories are all in sync.
Assumes deployment is git repositiory. Requires GitPython 0.2.0.
GitPython 0.3.0 uses an async library that does not currently play well with Django. To install using Git just do
pip install GitPython==0.2.0-beta1.
h4. Git revision version strings.
To generate versions based on revision of every file in your source file list, put this in your settings.py:
<pre><code>
COMPRESS_VERSIONING = 'compress.versioning.git.GitVersioningBase'
</code></pre>
h4.Git HEAD last revision version strings.
To generate versions based on the latest revision of HEAD in your git repository (which assumes all of your source files are in the
same repository), put this in your settings.py:
<pre><code>
COMPRESS_VERSIONING = 'compress.versioning.git.GitHeadRevVersioning'
</code></pre>
h3. Write your own versioning class
To write your own versioning class, you can subclass one of the available versioning classes.
h4. Example
For example, you want a short version string based on the SHA-1 version string. You can do this by subclassing the SHA1Versioning class and overriding its get_version() method, like this:
<pre><code>
from compress.versioning.hash import SHA1Versioning
class ShortSHA1Versioning(SHA1Versioning):
"""Custom SHA1Versioning class"""
def get_version(self, source_files):
"""Return the first 10 characters of the SHA-1 version string"""
version = super(ShortSHA1Versioning, self).get_version(source_files)
return version[:10]
</code></pre>
In your settings.py add:
<pre><code>
COMPRESS_VERSIONING = 'app.module.ShortSHA1Versioning'
</code></pre>
N.B. replace _app_ and _module_ by the app and module that contains your versioning class
h3. Production environment
You probably do not want the source files to be evaluated and (if needed) regenerated on every request in a production environment. Especially when calculating a hash on every request could be expensive.
To avoid this, make sure your source files are compressed before deployment, and put the following settings in your production environment's settings.py:
<pre><code>
COMPRESS_AUTO = False
COMPRESS_VERSION = True
</code></pre>
This way, the names of the compressed files will be looked up in the file system, instead of being evaluated and (if needed) regenerated on every request.
\ No newline at end of file
.. _ref-backwardsincompatiblechanges:
==============================
Backwards Incompatible Changes
==============================
A list of backwards incompatible changes
Version 1.2
===========
* CSSTidy isn't the default anymore, YUI Compressor is now the default.
* Filters are now called compressors.
Revision 53
===========
http://code.google.com/p/django-compress/source/detail?r=53
Changed the default media type for CSS to "all" instead of "media,projection".
You can still specify media type with `extra_context`.
Revision 56
===========
http://code.google.com/p/django-compress/source/detail?r=56
*bump_filename completely changed*
bump_filename was broken because a lot of caches does not properly cache files with querystrings.
Therefore it is completely rewritten without any thoughts on backwards compatibility, since it was not possible anyways.
This changeset also introduces a couple of other changes that could potentially break old code.
* The `bump_filename` option was removed from the group settings. There is no need specifying it for ALL groups, if you actually use it, you most likely want to use it on all your compressed files.
* The bump_filename options is replaced by the setting COMPRESS_VERSION, and is completely ignored.
* The querystring is no longer used to determine a files version, since it was use
* If ``COMPRESS_VERSION`` is used, you specify the version part of the `output_filename` file with '?'. This placeholder can be changed with COMPRESS_VERSION_PLACEHOLDER.
E.g.::
'screen': {
'source_filenames': ('css/screen/style.css', 'css/screen/paginator.css', 'css/screen/agenda.css', 'css/screen/weather.css', 'css/screen/gallery.css', ),
'output_filename': 'c/screen.r?.css',
},
* ``COMPRESS_VERSION`` requires ``COMPRESS_AUTO`` to be enabled.
``COMPRESS_AUTO`` is enabled by default, but if you explicitly set it to ``False`` an ``ImproperlyConfiguredError`` exception will be thrown.
``COMPRESS_AUTO`` changes
* The CSS/Javascript files are not checked during Django's initialization anymore.
It was not really useful and did not make sense.
The automatic part is now handled by the templatetags (i.e. what used to be ``COMPRESS_TEMPLATE_AUTO``).
* ``COMPRESS_AUTO`` is replaced by ``COMPRESS_AUTO_TEMPLATE``, and the old behavior
of ``COMPRESS_AUTO`` is removed. This might be really confusing, the :doc:`configuration` should make it clear.
\ No newline at end of file
# -*- coding: utf-8 -*-
#
# django-compress documentation build configuration file, created by
# sphinx-quickstart on Sat Apr 30 17:47:55 2011.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = []
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'django-compress'
copyright = u'2011, Andreas Pelme'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '1.2'
# The full version, including alpha/beta/rc tags.
release = '1.2'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'nature'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'django-compressdoc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'django-compress.tex', u'django-compress Documentation',
u'Andreas Pelme', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'django-compress', u'django-compress Documentation',
[u'Andreas Pelme'], 1)
]
.. _ref-configuration:
=============
Configuration
=============
Configuration and list of available settings for django-compress
.. note::
Don't forget to read :doc:`backwardsincompatiblechanges`
Specifying files
================
You specify groups of files to be compressed in your settings.
The basic syntax for specifying CSS/JavaScript groups files is ::
COMPRESS_CSS = {
'group_one': {
'source_filenames': ('css/style.css', 'css/foo.css', 'css/bar.css'),
'output_filename': 'css/one_compressed.css',
'extra_context': {
'media': 'screen,projection',
},
},
# other CSS groups goes here
}
COMPRESS_JS = {
'all': {
'source_filenames': ('js/jquery-1.2.3.js', 'js/jquery-preload.js', 'js/jquery.pngFix.js',
'js/my_script.js', 'js/my_other_script.js'),
'output_filename': 'js/all_compressed.js',
}
}
Group options
-------------
* ``source_filenames`` is a tuple with the source files to be compressed.
The files are concatenated in the order it is specified in the tuple. This option is required.
* ``output_filename`` is the filename of the (to be) compressed file. This option is required.
* ``extra_context`` is a dictionary of values to add to the template context,
when generating the HTML for the HTML-tags with the templatetags.
This option is not required and can be left out.
For CSS, if you do not specify ``extra_context``/``media``, the default media in
the ``<link>`` output will be ``media="all"``.
Note that all filenames are specified relative to ``COMPRESS_ROOT``, and thus the source
files needs to be in your ``COMPRESS_ROOT``.
Other settings
--------------
* ``COMPRESS``: When ``COMPRESS`` is ``True``, CSS and JavaScripts will be concatenated and filtered.
When ``False``, the source-files will be used instead.
Defaults to ``not DEBUG`` (compressed files will only be used in non-DEBUG-mode (production))
* ``COMPRESS_AUTO``: Auto-generate CSS and JavaScript files whenever needed,
when the template tags are invoked.
This setting will make sure that the outputted files always are up to date
(assuming that you are using the provided templatetags to output the links to
your files).
If you disable this, you can use the management command to keep your files
manually updated. Defaults to ``True``.
* ``COMPRESS_VERSION``: Regulates whether or not to add a "version number" to the outputted files filename with for use with “far future Expires”. For more information, see [FarFutureExpires]. When you specify ``COMPRESS_VERSION`` you will also need to add a placeholder (which by default is '?') for the version number in the ``output_filename`` setting.
* ``COMPRESS_VERSION_REMOVE_OLD``: When ``True``, old compressed files will be removed when new versions are generated. All files with a matching name e.g. ``output_filename`` where ? can be replaced by digits will be removed. If you for some reason have files named in the same way, you should consider moving them or putting the compressed files in their own directory. Defaults to ``True``.
``COMPRESS_VERSION`` example::
COMPRESS = True
COMPRESS_VERSION = True
COMPRESS_CSS = {
'screen': {
'source_filenames': (
'css/screen/style.css', 'css/screen/paginator.css',
'css/screen/agenda.css', 'css/screen/weather.css',
'css/screen/gallery.css',
),
'output_filename': 'c/screen.r?.css',
},
}
This will output a file like ``/media/c/screen.r1213947531.css``, which will be re-generated and updated when you change your source files.
* ``COMPRESS_CSS_COMPRESSORS``: A tuple of filters to be applied to CSS files.
Defaults to ``('compress.compressors.yui.YUICompressor', )``.
* ``COMPRESS_JS_COMPRESSORS``: A tuple of filters to be applied to JavaScript files.
Defaults to ``('compress.compressors.yui.YUICompressor',)``
.. note::
Please note that in order to use YUI Compressor, you need to install YUI Compressor (see :doc:`ìnstallation` for more details).
``COMPRESS_*_COMPRESSORS`` can be set to an empty tuple or None to not use any filters.
The files will however still be concatenated to one file.
Prefix - An Alternative to MEDIA_URL
------------------------------------
In cases where you want to deploy your compiled script and styles to somewhere
other than your MEDIA_URL, say a Content Delivery Network,
you can use the optional ``prefix`` parameter::
COMPRESS_CSS = {
'group_one': {
'source_filenames': ('css/style.css', 'css/foo.css', 'css/bar.css'),
'output_filename': 'css/one_compressed.css',
'extra_context': {
'media': 'screen,projection',
'prefix': 'http://cdn.example.com/'
},
},
# other CSS groups goes here
}
In this example, the template tags will render ``http://cdn.example.com/css/one_compressed.css`` in the link tag.
You will need to manually put there after you build as part of your deployment process.
CSS URL not starting with slash
-------------------------------
If source CSS contain a relative URL not starting with slash (i.e. relative to current file),
those URL will be converted to full relative path using ``COMPRESS_URL``.
This conversion is performed before any filters applied ::
media/js/fancybox/
fancybox.png
fancybox-x.png
fancybox-y.png
jquery.fancybox-1.3.4.css
jquery.fancybox-1.3.4.js
jquery.fancybox-1.3.4.css contains ::
background-image: url('fancybox.png');
background-image: url('fancybox-x.png');
background-image: url('fancybox-y.png');
In resulting CSS it will be rewritten to ::
background-image:url(/js/fancybox/fancybox.png);
background-image:url(/js/fancybox/fancybox-x.png);
background-image:url(/js/fancybox/fancybox-y.png);
(Assuming ``COMPRESS_URL`` is '' or '/', with non-empty ``COMPRESS_URL`` result will be another).
External urls
-------------
While django-compress does a great job of minimizing the amount of http requests
on your site (hence increasing performance) there are sometimes cases when you
want to include external files as well. Let's take an example::
COMPRESS_JS = {
'jquery': {
'external_urls': (
'http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js',
'http://ajax.googleapis.com/ajax/libs/jqueryui/1.5.2/jquery-ui.min.js'
),
},
'all': {
'source_filenames': ('js/blog.js', 'js/comments.js'),
'output_filename': 'js/all.js',
},
}
In template::
{% load compressed %}
{% compressed_js 'jquery' %}
{% compressed_js 'all' %}
Output in when ``settings.COMPRESS = False``::
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" charset="utf-8"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.5.2/jquery-ui.min.js" charset="utf-8"></script>
<script type="text/javascript" src="/media/js/blog.js" charset="utf-8"></script><script type="text/javascript" src="/media/js/comments.js" charset="utf-8"></script>
Output in when ``settings.COMPRESS = True``::
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" charset="utf-8"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.5.2/jquery-ui.min.js" charset="utf-8"></script>
<script type="text/javascript" src="/media/js/all.js" charset="utf-8"></script>
Now why is this good you ask? The more script sources the more impact on performance
according to http://developer.yahoo.com/performance/rules.html#num_http
which is true but if you are low bandwidth or superbig you may want to offload
some horsepower to google which leads us as hinted in the example above to the next topic.
.. note::
external urls is currently only available for javascript. There's currently no
reason to have external css files (Yes there are css frameworks as well on the net
but they are often very small or generated to fit your needs)
Google AJAX Libraries API
-------------------------
So the reason for adding external urls support to django-compress is google ajax
libraries api support (example above) but you may want to use it however you want.
The advantages for offloading huge javascript libraries to google cdn is of course
that your site will need a lot less bandwidth, even if you use far futures expires headers.
But the superior reason is of course that the more sites that uses it, the bigger
the chance is that your favorite js framework is already cached in your visitors browser.
Google also uses far future expires headers so don't worry about that.
Don't worry about latency outside the US either. Here in sweden I measured a latency of 39ms.
To sum somethings up, it's up to you and your situation to decide if merging all js
files or offloading js libraries to google gives your site the best performance.
Both ways are great to achieve great performance.
For a complete list of javascript libraries supported go to http://code.google.com/apis/ajaxlibs/
YUI Compressor settings
=======================
* ``COMPRESS_YUI_BINARY``: command line to execute for the YUI program.
Defaults to ``'java -jar yuicompressor.jar'``. You will most likely change this to the location of yuicompressor on your system.
* ``COMPRESS_YUI_CSS_ARGUMENTS``: Additional arguments to use when compressing CSS.
Defaults to ``''``.
* ``COMPRESS_YUI_JS_ARGUMENTS``: Additional arguments to use when compressing JavaScript.
Defaults to ``''``.
.. _ref-customization:
=============
Customization
=============
.. note::
Describes how to customize and add your own functionality to django-compress
django-compress can be customized an a couple of ways.
If you need to change the output of the HTML-tags generated from the templatetags,
this can be done by overriding the templates ``compress/css.html`` and ``compress/js.html``.
You can also write your own compressor-class, if you for example want to implement
other types of compressors.
All you need to do is to define a compress_css and/or a compress_js functions in a
class that inherits from ``compress.compressors.CompressorBase``,
and specify it in the tuple of filters (``COMPRESS_CSS_COMPRESSORS``/``COMPRESS_JS_COMPRESSORS``)
(see :doc:`configuration` for more information) in the settings.
For now, see the files under `compressors/` for more details.
\ No newline at end of file
.. _ref-farfuturexpires:
==================
Far Future Expires
==================
Details about the "Far Future Expires" technique, and how to implement it with help from django-compress
General details and considerations about the "Far Future Expires" technique
===========================================================================
If you really want to make sure that your CSS and JavaScript files get cached by
the browser (and possibly by proxies), you should use "Far Future Expires".
This means that you send the Expires HTTP-header with a date that is far in the future,
resulting in the file being cached at the client (almost) forever
If you do not specify an Expires header, the files will be requested again,
and the server will respond "304 Not Modified" - which means that the file that
the client got in its cache is still up-to-date. *However, a HTTP request will still be made anyway.*
The actual data does not get sent, but there will still be unnecessary HTTP requests, which can be avoided.
Most modern browser implement "Heuristic expiration", so it will actually not be
"304 Not Modified" for your static files on every request, however, the
`HTTP specification does not specify <http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html>`_ (see section 13.2.2)
how "Heuristic expiration" should be handled by the browsers.
Therefore it is recommended to explicitly set the Expires header, to make sure all
browsers cache the files in the preferred way.
This technique obviously has a drawback, when you want to change your files,
you need to change their names, since their URLs will be cached... that's right: forever!
The solution to that is pretty obvious too: change the URLs.
django-compress with COMPRESS_VERSION
=====================================
If you specify ``COMPRESS_VERSION`` in your configuration, you can add a placeholder
to the filenames to output the version number of the different files.
See :doc:`configuration` for more information.
The filename itself will be changed when any of the source files are updated.
Configuration of web server (that serves MEDIA_URL)
===================================================
Apache
------
Expires-control in Apache is handled by mod_expires:
See documentation for more information:
* `mod_expires <http://httpd.apache.org/docs/2.2/mod/mod_expires.html>`_
For example ::
<Directory /your/media/root/css>
ExpiresActive on
ExpiresDefault "access plus 10 years"
</Directory>
Apache also allows the specify files by their mime-type:
<pre><code>
ExpiresActive On
ExpiresByType text/css "access plus 10 years"
ExpiresByType application/x-javascript "access plus 10 years"
</code></pre>
lighttpd
--------
lighttpd handles Expires similar to Apache, with a module called mod_expire.
* `mod_expire <http://trac.lighttpd.net/trac/wiki/Docs%3AModExpire>`_
For example, set far future headers on all files under ``/media/css/`` and ``/media/js/`` ::
$HTTP["url"] =~ "^/media/css/" {
expire.url = ( "" => "access 10 years" )
}
$HTTP["url"] =~ "^/media/js/" {
expire.url = ( "" => "access 10 years" )
}
nginx
-----
nginx's ``ngx_http_headers_module`` provides the ``expires`` option, which control
the ``Expires`` and ``Cache-Control`` HTTP headers.
* `ngx_http_headers_module <http://wiki.codemongers.com/NginxHttpHeadersModule>`_
For example, this will set expiration to the maximum expiration ::
location /media/js {
expires max;
}
location /media/css {
expires max;
}
.. _ref-features:
========
Features
========
This is a application that will provide an easy and automated way to output
compressed/minified CSS and JavaScript.
It adheres to the DRY principle, you set up your CSS-files and JavaScript-files
in your project settings, and you are done.
There is no need to enter the names in your template again (a couple of template tags takes care of that).
* Group/concatenate your CSS/JavaScript source files to single files,
and run the code through specified compressors
* Provides sane defaults for CSS and JavaScript minification (YUI compressor required).
* A compressor for YUI Compressor, Google Closure Compiler, UglifyJS is included.
* It’s easy and straightforward to write custom compressors to generate the output.
* A last-modifcation/version part can automatically be appended to the filename
of the outputted files to make use of “far future Expires HTTP header),
and provide an automated way of updating the content without delays.
* You setup and group your CSS and JavaScript-files in the settings,
and set up whetter or not you want your files to be compressed.
* Templatetags to output CSS (<link...>) or JavaScript (<script...>) tags
with the compressed files if ``COMPRESS = True``, or otherwise the source files.
* The compressed files will be updated (if needed) when you are accessing them
from the templatetags. This only applies when ``COMPRESS_AUTO`` is enabled.
You can manually update them with ``./manage.py synccompress``.
.. django-compress documentation master file, created by
sphinx-quickstart on Sat Apr 30 17:47:55 2011.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Introduction
============
JavaScript and CSS minification/compression can decrease load times of sites a lot.
It is important to reduce the number of requests that are made.
Fewer files means better performance. However, when you develop CSS, and particularly
if you are building a big site, it can be nice to separate different parts of the site’s CSS into different files.
You also want to keep the CSS and JavaScript in different files while you develop, to make debugging easier.
It is also nice to comment CSS and JavaScript, but you do not want the overhead
of sending the comments and whitespaces to the clients.
You also want to make sure that as much of the static content is cached as much
as possible at the client.
The ideal is to even avoid “304 Not Modified” which are returned when a client
requested something that has already been cached, and does not need to be updated.
This can be accomplished by setting the HTTP Expire header to a date far in the future.
That will force the browser not to ask for updates for that URL.
However, when you need to update your files, you will need to give them a new URL,
to push the updated files to the clients.
These techniques has been described more in depth at Yahoo:
* http://developer.yahoo.com/performance/rules.html#num_http
* http://developer.yahoo.com/performance/rules.html#minify
* http://developer.yahoo.com/performance/rules.html#expires
django-compress tries to address those issues with as little manual intervention
as possible, whilst still being configurable enough to not get in your way.
Read more about the :doc:`features`.
There are numerous of other techniques that could be used to improve performance,
Yahoo has an excellent page that lists the most common: http://developer.yahoo.com/performance/rules.html
Table Of Contents
=================
.. toctree::
:maxdepth: 2
features
installation
usage
configuration
versioning
customization
farfuturexpires
backwardsincompatiblechanges
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
.. _ref-installation:
============
Installation
============
Installation is pretty straight-forward and follows the same installation
procedure as many other Django applications.
django-compress does not create any models, so you do not need to configure a database.
Recommendations
===============
By default django-compress uses YUI Compressor to compress CSS and JS.
YUI Compressor is an excellent stand-alone application for dealing with JS and CSS-files.
YUI Compressor can be downloaded from: http://developer.yahoo.com/yui/compressor/.
If you do not install YUI COMPRESSOR, make sure to disable the compressor in your settings.
Install instructions
====================
1. Either check out django-compress from GitHub_ or to pull a release off PyPI_.
Doing ``pip install django-compress`` or ``easy_install django-compress`` is all that should be required.
2. Add 'compress' to your INSTALLED_APPS
.. _GitHub: http://github.com/pelme/django-compress
.. _PyPI: http://pypi.python.org/
@ECHO OFF
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set BUILDDIR=_build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^<target^>` where ^<target^> is one of
echo. html to make standalone HTML files
echo. dirhtml to make HTML files named index.html in directories
echo. singlehtml to make a single large HTML file
echo. pickle to make pickle files
echo. json to make JSON files
echo. htmlhelp to make HTML files and a HTML help project
echo. qthelp to make HTML files and a qthelp project
echo. devhelp to make HTML files and a Devhelp project
echo. epub to make an epub
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
echo. text to make text files
echo. man to make manual pages
echo. changes to make an overview over all changed/added/deprecated items
echo. linkcheck to check all external links for integrity
echo. doctest to run all doctests embedded in the documentation if enabled
goto end
)
if "%1" == "clean" (
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
del /q /s %BUILDDIR%\*
goto end
)
if "%1" == "html" (
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
goto end
)
if "%1" == "dirhtml" (
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
goto end
)
if "%1" == "singlehtml" (
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
goto end
)
if "%1" == "pickle" (
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the pickle files.
goto end
)
if "%1" == "json" (
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the JSON files.
goto end
)
if "%1" == "htmlhelp" (
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run HTML Help Workshop with the ^
.hhp project file in %BUILDDIR%/htmlhelp.
goto end
)
if "%1" == "qthelp" (
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run "qcollectiongenerator" with the ^
.qhcp project file in %BUILDDIR%/qthelp, like this:
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\django-compress.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\django-compress.ghc
goto end
)
if "%1" == "devhelp" (
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished.
goto end
)
if "%1" == "epub" (
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The epub file is in %BUILDDIR%/epub.
goto end
)
if "%1" == "latex" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
if errorlevel 1 exit /b 1
echo.
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "text" (
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The text files are in %BUILDDIR%/text.
goto end
)
if "%1" == "man" (
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The manual pages are in %BUILDDIR%/man.
goto end
)
if "%1" == "changes" (
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
if errorlevel 1 exit /b 1
echo.
echo.The overview file is in %BUILDDIR%/changes.
goto end
)
if "%1" == "linkcheck" (
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
if errorlevel 1 exit /b 1
echo.
echo.Link check complete; look for any errors in the above output ^
or in %BUILDDIR%/linkcheck/output.txt.
goto end
)
if "%1" == "doctest" (
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
if errorlevel 1 exit /b 1
echo.
echo.Testing of doctests in the sources finished, look at the ^
results in %BUILDDIR%/doctest/output.txt.
goto end
)
:end
.. _ref-usage:
=====
Usage
=====
Describes how to use django-compress when it is installed and configured.
Automated generation
====================
If ``COMPRESS`` and ``COMPRESS_AUTO`` is enabled (``True``), the source files
will be automatically updated, and re-generated if needed when invoked from the
templatetags.
The last modified time of the files will be compared, and if any of the
source-files is newer than the output-file, the file will be re-generated.
Management command
==================
You can update and force updates of the compressed file(s) with the management command “synccompress”.
This makes it possible to keep the files updated manually.
The command is ::
manage.py synccompress
(assuming you are in you project-folder that contains ``manage.py``).
To force all files to be re-generated, use the argument ``--force`` (e.g. ``./manage.py synccompress --force``)
Templatetags
============
django-compress includes two template tags: ``compressed_css`` and ``compressed_js``,
in a template library called ``compressed``.
They are used to output the ``<link>`` and ``<script>``-tags for the
specified CSS/JavaScript-groups (as specified in the settings).
The first argument must be the name of the CSS/JavaScript group.
The templatetags will either output the source filenames or the compressed filenames,
depending on the ``COMPRESS`` setting, if you do not specify the ``COMPRESS`` setting,
the source files will be used in DEBUG-mode, and compressed files in non-DEBUG-mode.
Example
=======
If you have specified the CSS-groups “screen” and “print” and a JavaScript-group
with the name “scripts”, you would use the following code to output them all ::
{% load compressed %}
{% compressed_css 'screen' %}
{% compressed_css 'print' %}
{% compressed_js 'scripts' %}
Far future Expires
==================
Far future Expires can be used with the bump_filename-option, see the :doc:`farfuturexpires` page for more information.
.. _ref-versioning:
==========
Versioning
==========
There are several ways for generating version strings. Basically, two types are available.
These are: mtime version strings and hash version strings.
mtime version strings (default)
===============================
This is the default method for generating version strings. In short, when invoked, it checks whether any of the source files system timestamps (mtime) is newer than the version string of the corresponding compressed file. If that is the case, the compressed output file version string will be the mtime of the most recent source file.
hash version strings
====================
Hash-based versioning works by generating a hash string based on the contents of the source files. Available hash-based versioning methods are MD5 and SHA-1.
MD5 version strings
-------------------
To generate MD5 version strings, put this in your `settings.py` ::
COMPRESS_VERSIONING = 'compress.versioning.hash.MD5Versioning'
SHA-1 version string
--------------------
To generate SHA-1 version strings, put this in your `settings.py`::
COMPRESS_VERSIONING = 'compress.versioning.hash.SHA1Versioning'
Git version strings
===================
Versions formed on git revisions in codebase. Provides a fast way to check if any of your files changed that
will be consistent across multiple web servers so that they all generate the same version numbers for each
set of source files, assuming their git repositories are all in sync.
Assumes deployment is git repositiory. Requires GitPython 0.2.0.
GitPython 0.3.0 uses an async library that does not currently play well with Django. To install using Git just do
pip install GitPython==0.2.0-beta1.
Git revision version strings
----------------------------
To generate versions based on revision of every file in your source file list, put this in your `settings.py`::
COMPRESS_VERSIONING = 'compress.versioning.git.GitVersioningBase'
Git HEAD last revision version strings
--------------------------------------
To generate versions based on the latest revision of HEAD in your git repository (which assumes all of your source files are in the
same repository), put this in your `settings.py`::
COMPRESS_VERSIONING = 'compress.versioning.git.GitHeadRevVersioning'
Write your own versioning class
===============================
To write your own versioning class, you can subclass one of the available versioning classes.
Example
-------
For example, you want a short version string based on the SHA-1 version string.
You can do this by subclassing the SHA1Versioning class and overriding its get_version() method, like this::
from compress.versioning.hash import SHA1Versioning
class ShortSHA1Versioning(SHA1Versioning):
"""Custom SHA1Versioning class"""
def get_version(self, source_files):
"""Return the first 10 characters of the SHA-1 version string"""
version = super(ShortSHA1Versioning, self).get_version(source_files)
return version[:10]
In your ``settings.py`` add::
COMPRESS_VERSIONING = 'app.module.ShortSHA1Versioning'
.. note::
Replace ``app`` and ``module`` by the app and module that contains your versioning class
Production environment
======================
You probably do not want the source files to be evaluated and (if needed)
regenerated on every request in a production environment.
Especially when calculating a hash on every request could be expensive.
To avoid this, make sure your source files are compressed before deployment,
and put the following settings in your production environment's ``settings.py``::
COMPRESS_AUTO = False
COMPRESS_VERSION = True
This way, the names of the compressed files will be looked up in the file system, instead of being evaluated and (if needed) regenerated on every request.
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment