Skip to content

Commit

Permalink
support for Django 3
Browse files Browse the repository at this point in the history
  • Loading branch information
metakermit committed Dec 15, 2019
1 parent dbdfa6d commit 3059e64
Show file tree
Hide file tree
Showing 16 changed files with 948 additions and 42 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ coverage.xml

# Django stuff:
*.log
*.sqlite3

# Sphinx documentation
docs/_build/
Expand All @@ -62,3 +63,4 @@ target/
.python-version

.venv
staticfiles
25 changes: 25 additions & 0 deletions Pipfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"

[packages]
whitenoise = "*"

[dev-packages]
bumpversion = "*"
watchdog = "*"
"flake8" = "*"
tox = "*"
coverage = "*"
cryptography = "*"
pytest = "*"
twine = "*"
Sphinx = "*"
PyYAML = "*"
django = "*"
django-spa = {editable = true, path = "."}
ipdb = "*"

[requires]
python_version = "3.7"
686 changes: 686 additions & 0 deletions Pipfile.lock

Large diffs are not rendered by default.

25 changes: 17 additions & 8 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -38,28 +38,37 @@ Usage
For an example of using django-spa to serve a create-react-app frontend
that consumes a Django REST framework API, check out generator-django-rest_.

First set up WhiteNoise_, as django-spa overrides some of its functionality.
As part of setting up django-spa, you also need to set up WhiteNoise_,
which we'll summarise here.

Add django-spa to your *requirements.txt*
and ``pip install -r requirements.txt``::
First, add ``django-spa`` to your *requirements.txt*
and ``pip install -r requirements.txt`` (or ``pipenv install django-spa``).
Whitenoise is installed as a dependency, so no need to specify it extra.

django-spa

Update *settings.py* with the django-spa middleware::
Update *settings.py* with the Whitenoise & django-spa middleware::

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'spa.middleware.SPAMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'spa.middleware.SPAMiddleware',
]

Use the django-spa static file storage::
Disable runserver's static file serving by adding ``runserver_nostatic``
to the top of your INSTALLED_APPS list::

INSTALLED_APPS = [
'whitenoise.runserver_nostatic',
'django.contrib.staticfiles',
# ...
]

Set the django-spa static file storage::

STATICFILES_STORAGE = 'spa.storage.SPAStaticFilesStorage'

Expand Down
15 changes: 15 additions & 0 deletions example/manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/env python
import os
import sys

if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'spaproject.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
Empty file added example/spaproject/__init__.py
Empty file.
130 changes: 130 additions & 0 deletions example/spaproject/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
"""
Django settings for spaproject project.
Generated by 'django-admin startproject' using Django 2.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'c0^wn8&&8x=qjh=$%hpx23^570lww(^qx*s&b$@4tdywf0&nu9'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'whitenoise.runserver_nostatic',
'django.contrib.staticfiles',
]

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'spa.middleware.SPAMiddleware',
# 'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'spaproject.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

WSGI_APPLICATION = 'spaproject.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}


# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]


# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'spaproject/static'),)

STATICFILES_STORAGE = 'spa.storage.SPAStaticFilesStorage'
# STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'
Binary file added example/spaproject/static/badge.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
10 changes: 10 additions & 0 deletions example/spaproject/static/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>Django SPA</title>
</head>
<body>
<h1>Hello, Django SPA!</h1>
<img src="badge.png">
</body>
21 changes: 21 additions & 0 deletions example/spaproject/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"""spaproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path

urlpatterns = [
path('admin/', admin.site.urls),
]
16 changes: 16 additions & 0 deletions example/spaproject/wsgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
WSGI config for spaproject project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'spaproject.settings')

application = get_wsgi_application()
1 change: 0 additions & 1 deletion requirements.txt

This file was deleted.

12 changes: 0 additions & 12 deletions requirements_dev.txt

This file was deleted.

2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
history = history_file.read()

requirements = [
'whitenoise==3.2.2'
'whitenoise==5.0.1'
]

test_requirements = [
Expand Down
43 changes: 25 additions & 18 deletions spa/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import os

from django.conf import settings
from django.urls import resolve
from django.urls import is_valid_path
from django.urls.exceptions import Resolver404
from whitenoise.middleware import WhiteNoiseMiddleware

Expand All @@ -25,22 +25,28 @@ def process_request(self, request):
if static_file is not None:
return self.serve(static_file, request)
else:
# if no file was found there are two options
# if no file was found there are two options:

# 1) the file is in one of the Django urls
# (e.g. a template or the Djangoadmin)
# so we'll let Django handle this
# (just return and let the normal middleware take its course)
urlconf = getattr(request, 'urlconf', None)
if is_valid_path(request.path_info, urlconf):
return
if (settings.APPEND_SLASH and not request.path_info.endswith('/') and
is_valid_path('%s/' % request.path_info, urlconf)):
return

# 2) the url is handled by frontend routing
# redirect all unknown files to the SPA root
try:
# 1) the file is in one of the Django urls
# (e.g. a template or the Djangoadmin)
# so we'll let Django handle this (return nothing)
resolve(request.path)
except Resolver404:
# 2) the url is handled by frontend routing
# redirect all unknown files to the SPA root
try:
return self.serve(self.spa_root, request)
except AttributeError: # no SPA page stored yet
self.spa_root = self.find_file('/')
if self.spa_root:
return self.serve(self.spa_root, request)
except AttributeError: # no SPA page stored yet
self.spa_root = self.find_file('/')
if self.spa_root:
return self.serve(self.spa_root, request)
# TODO: else return a Django 404
# TODO: else return a Django 404 (maybe?)

def update_files_dictionary(self, *args):
super(SPAMiddleware, self).update_files_dictionary(*args)
Expand All @@ -61,7 +67,7 @@ def update_files_dictionary(self, *args):
self.spa_root = static_file
else:
# also serve static files on /
# e.g. serve /static/my/file.png on /my/file.png
# e.g. when /my/file.png is requested, serve /static/my/file.png
directory_indexes[url[static_prefix_length:]] = static_file
self.files.update(directory_indexes)

Expand All @@ -77,6 +83,7 @@ def find_file(self, url):
return self.spa_root
else:
# also serve static files on /
# e.g. serve /static/my/file.png on /my/file.png
url = os.path.join(settings.STATIC_URL, url[1:])
# e.g. when /my/file.png is requested, serve /static/my/file.png
if (not url.startswith(settings.STATIC_URL)):
url = os.path.join(settings.STATIC_URL, url[1:])
return super(SPAMiddleware, self).find_file(url)
2 changes: 0 additions & 2 deletions spa/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ class PatchedManifestStaticFilesStorage(ManifestStaticFilesStorage):
"""
A static file system storage backend which also saves
hashed copies of the files it saves.
Patched for https://github.com/metakermit/django-spa/issues/3
"""

def url_converter(self, *args, **kwargs):
Expand Down

0 comments on commit 3059e64

Please sign in to comment.