1. Reducing the Server response time:
As a programmer, one of the reasons of the high server response time is due to redundancy in the queries. The following the cases where we use redundancy of queries and how can we reduce them.
if Assessment.objects.filter(id=assess.assessment_id, edu_class_id=role.edu_class_id, subject_id=role.subject_id).exists():
assessments_list = assessments_list + list(Assessment.objects.filter(id=assess.assessment_id,edu_class_id=role.edu_class_id,subject_id=role.subject_id))
In the above code the query 'Assessment.objects.filter(id=assess.assessment_id, edu_class_id=role.edu_class_id, subject_id=role.subject_id)' is repeated twice. Using the same query second time is of no use. The method .exists(), is to be used in such cases where the query set result is not used anywhere else. We can rewrite the above code as below.
assessments = Assessment.objects.filter(id=assess.assessment_id, edu_class_id=role.edu_class_id, subject_id=role.subject_id)
if assessments:
assessments_list = assessments_list + list(assessments)
2. Enable compression and minifying CSS and JS:
Many of the projects which are developed in Django use a plugin called 'Django-Compressor' to compress the CSS and JS resources. For more information about Django-Compressor check http://django-compressor.readthedocs.org/en/latest/. By default, django compressor won't minify the CSS and JS files completely. To minify CSS and JS resources we have to keep the following settings in settings.py
COMPRESS_CSS_FILTERS = ['compressor.filters.css_default.CssAbsoluteFilter','compressor.filters.cssmin.CSSMinFilter']
COMPRESS_JS_FILTERS = ['compressor.filters.jsmin.JSMinFilter']
3. Minify HTML:
Django supports multiple HTML minification techniques, two of them are Django-htmlmin and Django-hmin. Both will minify the HTML data that is going to be loaded on the page. For more about Django-htmlmin check https://pypi.python.org/pypi/django-htmlmin and for django-hmin check https://pypi.python.org/pypi/django-hmin/0.3.2
4. Leverage browser caching:
Setting an expiry date or a maximum age in the HTTP headers for static resources instructs the browser to load previously downloaded resources from local disk rather than over the network. If we are landing the static files using Nginx the need the configure the expires value in the Nginx configuration file. This will look as following.
expires 365d;
If we use Django-storages we have to keep the following settings in your settings.py.
AWS_HEADERS = {
'Expires': 'Thu, 15 Apr 2010 20:00:00 GMT',
'Cache-Control': 'max-age=86400',
}
This setting sets an expiry date for the resources those are being served from AmazonS3.
By following the above techniques we can render our page more quickly, such that it will increase the page score in the google page speed insights.