Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use whitenoise for static file serving. #368

Merged
merged 7 commits into from
Jul 22, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion MANIFEST.in
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
include README.md
include LICENSE.txt
include pykeg/setup.cfg
recursive-include pykeg *.html *.css *.js *.png
recursive-include pykeg *.html *.css *.js *.png *.gif *.eot *.svg *.ttf *.woff *.ico
recursive-include deploy *
recursive-include pykeg/testdata *
4 changes: 4 additions & 0 deletions circle.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,7 @@ machine:
services:
- mysql
- redis

test:
pre:
- kegbot collectstatic -v 0 --noinput
17 changes: 10 additions & 7 deletions pykeg/contrib/demomode/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,22 +23,25 @@
from django.shortcuts import redirect


class DemoModeMiddleware:
class DemoModeMiddleware(object):
"""Denies non-GET requests when in demo mode.."""

WHITELISTED_PATHS = (
'/accounts/login/',
'/accounts/logout/',
'/demo/',
)

def process_request(self, request):
if not getattr(settings, 'DEMO_MODE', False):
return
if request.method == 'GET':
return
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
if not getattr(settings, 'DEMO_MODE', False) or request.method == 'GET':
return self.get_response(request)

for path in self.WHITELISTED_PATHS:
if request.path.startswith(path):
return
return self.get_response(request)

messages.error(request, 'Site is in demo mode; changes were not saved.')
path_or_url = urlparse.urlparse(request.META.get('HTTP_REFERER', '')).path
Expand Down
18 changes: 0 additions & 18 deletions pykeg/core/optional_modules.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,12 @@

import imp

try:
imp.find_module('debug_toolbar')
HAVE_DEBUG_TOOLBAR = True
except ImportError:
HAVE_DEBUG_TOOLBAR = False

try:
imp.find_module('raven.contrib.django')
HAVE_RAVEN = True
except ImportError:
HAVE_RAVEN = False

try:
imp.find_module('django_statsd')
HAVE_STATSD = True
except ImportError:
HAVE_STATSD = False

try:
imp.find_module('storages')
HAVE_STORAGES = True
Expand All @@ -38,12 +26,6 @@
except ImportError:
HAVE_PYLIBMC = False

try:
imp.find_module('debug_toolbar_memcache')
HAVE_MEMCACHE_TOOLBAR = True
except ImportError:
HAVE_MEMCACHE_TOOLBAR = False

try:
imp.find_module('djcelery_email')
HAVE_CELERY_EMAIL = True
Expand Down
97 changes: 16 additions & 81 deletions pykeg/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,13 @@
# Grab flags for optional modules.
from pykeg.core.optional_modules import *

import os
import logging
from pykeg.logging.logger import RedisLogger
logging.setLoggerClass(RedisLogger)

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

INSTALLED_APPS = (
'pykeg.core',
'pykeg.web',
Expand Down Expand Up @@ -52,6 +55,8 @@
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

# Default session serialization.
# Note: Twitter plugin requires Pickle (not JSON serializable).

Expand Down Expand Up @@ -84,7 +89,7 @@
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
Expand All @@ -98,28 +103,22 @@
# Disable Django's built in host checker.
ALLOWED_HOSTS = ['*']

MIDDLEWARE_CLASSES = (
# CurrentRequest and KegbotSite middlewares added first

'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.gzip.GZipMiddleware',
'django.middleware.common.CommonMiddleware',
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'pykeg.web.middleware.CurrentRequestMiddleware',
'pykeg.web.middleware.KegbotSiteMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',

'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'pykeg.contrib.demomode.middleware.DemoModeMiddleware',
'pykeg.web.api.middleware.ApiRequestMiddleware',
'pykeg.web.middleware.PrivacyMiddleware',

# Cache middleware should be last, except for ApiResponseMiddleWare,
# which needs to be after it (in request order) so that it can
# update the Cache-Control header before it (in reponse order).
'django.middleware.cache.FetchFromCacheMiddleware',

# ApiResponseMiddleware added last.
)
]

AUTHENTICATION_BACKENDS = (
'pykeg.web.auth.local.LocalAuthBackend',
Expand Down Expand Up @@ -362,67 +361,3 @@
CELERY_EMAIL_BACKEND = EMAIL_BACKEND
INSTALLED_APPS += ('djcelery_email',)
EMAIL_BACKEND = 'djcelery_email.backends.CeleryEmailBackend'

# debug_toolbar

if DEBUG:
if HAVE_DEBUG_TOOLBAR:
INSTALLED_APPS += (
'debug_toolbar',
)
MIDDLEWARE_CLASSES += (
'debug_toolbar.middleware.DebugToolbarMiddleware',
)
DEBUG_TOOLBAR_PANELS = (
'debug_toolbar.panels.version.VersionDebugPanel',
'debug_toolbar.panels.timer.TimerDebugPanel',
'debug_toolbar.panels.settings.SettingsPanel',
'debug_toolbar.panels.headers.HeaderDebugPanel',
'debug_toolbar.panels.request_vars.RequestVarsDebugPanel',
'debug_toolbar.panels.template.TemplateDebugPanel',
'debug_toolbar.panels.sql.SQLDebugPanel',
'debug_toolbar.panels.signals.SignalDebugPanel',
'debug_toolbar.panels.logging.LoggingPanel',
#'debug_toolbar.panels.profiling.ProfilingDebugPanel',
)
if HAVE_MEMCACHE_TOOLBAR:
INSTALLED_APPS += ('debug_toolbar_memcache',)
if HAVE_MEMCACHE:
DEBUG_TOOLBAR_PANELS += ('debug_toolbar_memcache.panels.memcache.MemcachePanel',)
elif HAVE_PYLIBMC:
DEBUG_TOOLBAR_PANELS += ('debug_toolbar_memcache.panels.pylibmc.PylibmcPanel',)

# Statsd

# Needs SECRET_KEY so must be imported after local settings.

STATSD_PATCHES = [
'django_statsd.patches.db',
'django_statsd.patches.cache',
]

if HAVE_STATSD:
MIDDLEWARE_CLASSES = (
'django_statsd.middleware.GraphiteRequestTimingMiddleware',
'django_statsd.middleware.GraphiteMiddleware',
) + MIDDLEWARE_CLASSES

INSTALLED_APPS += ('django_statsd',)

if DEBUG and HAVE_DEBUG_TOOLBAR and KEGBOT_STATSD_TO_TOOLBAR:
MIDDLEWARE_CLASSES = (
'debug_toolbar.middleware.DebugToolbarMiddleware',
) + MIDDLEWARE_CLASSES
DEBUG_TOOLBAR_PANELS = (
'django_statsd.panel.StatsdPanel',
) + DEBUG_TOOLBAR_PANELS
STATSD_CLIENT = 'django_statsd.clients.toolbar'

# First/last middlewares.

MIDDLEWARE_CLASSES = (
'pykeg.web.middleware.CurrentRequestMiddleware',
'pykeg.web.middleware.KegbotSiteMiddleware',
) + MIDDLEWARE_CLASSES

MIDDLEWARE_CLASSES += ('pykeg.web.api.middleware.ApiResponseMiddleware',)
36 changes: 19 additions & 17 deletions pykeg/web/api/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,25 @@
WHITELISTED_API_PATHS += getattr(settings, 'KEGBOT_EXTRA_WHITELISTED_API_PATHS', ())


class ApiRequestMiddleware:
class ApiRequestMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
response = self.get_response(request)

if util.is_api_request(request):
if not isinstance(response, HttpResponse):
data = util.prepare_data(response)
data['meta'] = {
'result': 'ok'
}
response = util.build_response(request, data, 200)

add_never_cache_headers(response)

return response

def process_view(self, request, view_func, view_args, view_kwargs):
request.is_kb_api_request = util.is_api_request(request)
if not request.is_kb_api_request:
Expand Down Expand Up @@ -76,28 +94,12 @@ def process_view(self, request, view_func, view_args, view_kwargs):
except Exception as e:
return util.wrap_exception(request, e)


class ApiResponseMiddleware:
def process_exception(self, request, exception):
"""Wraps exceptions for API requests."""
if util.is_api_request(request):
return util.wrap_exception(request, exception)
return None

def process_response(self, request, response):
if not util.is_api_request(request):
return response

if not isinstance(response, HttpResponse):
data = util.prepare_data(response)
data['meta'] = {
'result': 'ok'
}
response = util.build_response(request, data, 200)

add_never_cache_headers(response)
return response


def cache_key(request):
return 'api:%s' % request.get_full_path()
18 changes: 9 additions & 9 deletions pykeg/web/kegweb/templates/kegweb/fullscreen.html
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
{% extends "skel.html" %}
{% load kegweblib %}
{% load static kegweblib %}

{% block title %}{{ kbsite.title }} (Fullscreen Mode){% endblock %}

{% block kb-extracss %}
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}lib/slick/slick.css" media="screen" />
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/bootstrap-cyborg.css" media="screen" />
<link rel="stylesheet" type="text/css" href={% static "lib/slick/slick.css" %} media="screen" />
<link rel="stylesheet" type="text/css" href={% static "css/bootstrap-cyborg.css" %} media="screen" />

<style>

body {
background-color: #000;
background-image: url('{{ STATIC_URL }}images/chalkboard-bg.jpg') center center no-repeat;
background-image: url({% static "images/chalkboard-bg.jpg" %}) center center no-repeat;
background-size: cover;
color: #eee;
}
Expand Down Expand Up @@ -61,7 +61,7 @@
<div class="row-fluid">
<div class="span12">
<center>
<img src="{{ STATIC_URL }}images/whats-on-tap.png">
<img src={% static "images/whats-on-tap.png" %}>
</center>
</div>
</div>
Expand All @@ -75,7 +75,7 @@
{% with keg.type as beverage %}

<div class="row-fluid">

<div class="span2">
<img src="{{ keg.get_illustration }}" style="padding-bottom: 20px;">
</div>
Expand All @@ -85,7 +85,7 @@
{% if keg.type.picture %}
<img class="tap-snapshot-image" src="{{ keg.type.picture.resized.url }}">
{% else %}
<img class="tap-snapshot-image" src="{{ STATIC_URL }}images/kegbot-unknown-square.png">
<img class="tap-snapshot-image" src={% static "images/kegbot-unknown-square.png" %}>
{% endif %}
<span class="label label-info">{% volume keg.remaining_volume_ml %} remaining</span>
</center>
Expand All @@ -106,7 +106,7 @@ <h2>
{% endwith %}
{% endwith %}
{% endfor %} <!-- /tap in row -->

</div> <!-- /page -->

{% endfor %}
Expand All @@ -120,7 +120,7 @@ <h2>
{% endblock %}

{% block kb-extrajs %}
<script type="text/javascript" src="{{ STATIC_URL }}lib/slick/slick.min.js"></script>
<script type="text/javascript" src={% static "lib/slick/slick.min.js" %}></script>

<script type="text/javascript">

Expand Down
4 changes: 2 additions & 2 deletions pykeg/web/kegweb/templates/kegweb/keg-snapshot.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{% load kegweblib %}
{% load static kegweblib %}
{% with keg.current_tap as tap %}
{% url "kb-keg" keg.id as keg_url %}
<div class="kb-tapbox clickable" id="keg-snapshot-{{keg.id}}"
Expand All @@ -9,7 +9,7 @@
{% if keg.type.picture %}
<img class="tap-snapshot-image" src="{{ keg.type.picture.resized.url }}">
{% else %}
<img class="tap-snapshot-image" src="{{ STATIC_URL }}images/kegbot-unknown-square.png">
<img class="tap-snapshot-image" src={% static "images/kegbot-unknown-square.png" %}>
{% endif %}
</a>
</div>
Expand Down
3 changes: 2 additions & 1 deletion pykeg/web/kegweb/templates/kegweb/mugshot_box.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{% load static %}
{% spaceless %}
<div>

Expand All @@ -14,7 +15,7 @@
{% if user and user.mugshot %}
src="{{ user.mugshot.resized.url }}"
{% else %}
src="{{ STATIC_URL }}images/unknown-drinker.png"
src={% static "images/unknown-drinker.png" %}
{% endif %}
/>
</a>
Expand Down
Loading