Skip to content

Instantly share code, notes, and snippets.

@makmac213
Last active November 6, 2015 07:31
Show Gist options
  • Save makmac213/76c67370d3f0563dd6e4 to your computer and use it in GitHub Desktop.
Save makmac213/76c67370d3f0563dd6e4 to your computer and use it in GitHub Desktop.
Some useful notes that I use most of the time
Django Compressor + Amazon S3
=============================
http://django-compressor.readthedocs.org/en/latest/
https://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html
$ pip install django_compressor
$ pip install django-storages boto
# settings.py
INSTALLED_APPS = (
"compressor",
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# other finders..
'compressor.finders.CompressorFinder',
)
# usage on template
{% load compress %}
{% compress <js/css> [<file/inline> [block_name]] %}
<html of inline or linked JS/CSS>
{% endcompress %}
# using with S3
# s3utils.py
from django.core.files.storage import get_storage_class
from storages.backends.s3boto import S3BotoStorage
StaticS3BotoStorage = lambda: S3BotoStorage(location='static')
MediaS3BotoStorage = lambda: S3BotoStorage(location='media')
class CachedS3BotoStorage(S3BotoStorage):
"""
http://django-compressor.readthedocs.org/en/latest/remote-storages/
S3 storage backend that saves the files locally, too.
"""
def __init__(self, *args, **kwargs):
super(CachedS3BotoStorage, self).__init__(*args, **kwargs)
self.local_storage = get_storage_class(
"compressor.storage.CompressorFileStorage")()
def save(self, name, content):
name = super(CachedS3BotoStorage, self).save(name, content)
self.local_storage._save(name, content)
return name
# localsettings
DEFAULT_FILE_STORAGE = 's3utils.MediaS3BotoStorage'
STATICFILES_STORAGE = 's3utils.StaticS3BotoStorage'
AWS_ACCESS_KEY_ID = 'aws_key_id'
AWS_SECRET_ACCESS_KEY = 'aws_secret_key'
AWS_STORAGE_BUCKET_NAME = 'bucket_name'
# optional
AWS_HEADERS = {'Cache-Control': str('public, max-age=15552000')}
AWS_QUERYSTRING_AUTH = False
S3_URL = 'http://%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME
STATIC_DIRECTORY = 'static/'
MEDIA_DIRECTORY = 'media/'
STATIC_URL = S3_URL + STATIC_DIRECTORY
MEDIA_URL = S3_URL + MEDIA_DIRECTORY
# django compress
COMPRESS_STORAGE = 'ofw_guru.s3utils.CachedS3BotoStorage'
COMPRESS_URL = STATIC_URL
COMPRESS_OFFLINE = True
Django Redis Cache
==================
https://github.com/sebleier/django-redis-cache
http://django-redis-cache.readthedocs.org/en/latest/
$ pip install django-redis-cache
# REDIS CACHE
CACHES = {
'default': {
'BACKEND': 'redis_cache.RedisCache',
'LOCATION': [
'redis://127.0.0.1:6379',
],
},
}
Robots
======
http://fredericiana.com/2010/06/09/three-ways-to-add-a-robots-txt-to-your-django-project/
# option 1:
from django.http import HttpResponse
urlpatterns = patterns('',
(r'^robots.txt$',
lambda r: HttpResponse("User-agent: *\nDisallow: /", mimetype="text/plain"))
)
# option 2:
from django.views.generic.simple import direct_to_template
urlpatterns = patterns('',
(r'^robots\.txt$', direct_to_template,
{'template': 'robots.txt', 'mimetype': 'text/plain'}),
)
Django: Sending email with Amazon SES
# install django-smtp-ssl
# https://github.com/bancek/django-smtp-ssl
$ pip install django-smtp-ssl
# add to settings
EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend'
EMAIL_PORT = 465
EMAIL_HOST = 'email-smtp.us-west-2.amazonaws.com'
EMAIL_HOST_USER = 'ses_username'
EMAIL_HOST_PASSWORD = 'ses_password'
Sitemaps
========
https://docs.djangoproject.com/en/1.8/ref/contrib/sitemaps/
1. Add 'django.contrib.sitemaps' to INSTALLED_APPS
INSTALLED_APPS = (
'django.contrib.sites',
'django.contrib.sitemaps',
)
2. Create sitemaps.py
# FlatPageSitemap will generate flatpages entry to the sitemap
from django.contrib.flatpages.sitemaps import FlatPageSitemap
from django.contrib.sitemaps import GenericSitemap
# e.g. you have News and Post models
from news.models import News
from blogs.models import Post
# we use all in the example but
# you can create your query
news_dict = {
'queryset': News.objects.all(),
'date_field': 'created',
}
# below example shows custom query
post_dict = {
'queryset': Post.objects.filter(status=Post.STATUS_PUBLISHED),
'date_field': 'modified',
}
PROJECT_SITEMAPS = {
'flatpages': FlatPageSitemap,
'news': GenericSitemap(news_dict, priority=1, changefreq='daily'),
'posts': GenericSitemap(post_dict, priority=0.9, changefreq='daily'),
}
3. Add to urls.py
from sitemaps import PROJECT_SITEMAPS
urlpatterns += patterns('',
# sitemaps
url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap',
{'sitemaps': PROJECT_SITEMAPS}),
)
Others
======
django-longer-username
https://github.com/skoczen/django-longer-username
- if you need to override the default django User username field
# Nginx
# https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-django-with-postgres-nginx-and-gunicorn
Apache - Module Expires
=======================
$ sudo a2enmod expires
# on virtual host conf
<VirtualHost *:80>
ServerName www.example.com
<Directory /home/ubuntu/public_html/example/example/>
Require all granted
</Directory>
WSGIScriptAlias / /home/ubuntu/public_html/example/example/example/wsgi.py
Alias /static/ /home/ubuntu/public_html/example/example/assets/
Alias /media/ /home/ubuntu/public_html/example/example/media/
ExpiresActive on
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 week"
ExpiresByType application/x-font-ttf "access plus 1 month"
ExpiresByType font/opentype "access plus 1 month"
ExpiresByType application/x-font-woff "access plus 1 month"
ExpiresByType image/svg+xml "access plus 1 month"
ExpiresByType application/vnd.ms-fontobject "access plus 1 month"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
</VirtualHost>
# WSGIApplicationGroup %{GLOBAL}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment