SlideShare une entreprise Scribd logo
1  sur  19
Télécharger pour lire hors ligne
_DJANGO PROJECTS CONFIGURED
FOR MULTIPLE ENVIRONMENTS
KRYSTIAN HANEK
Backend Developer
apptension.com
_DEFAULT DJANGO
CONFIGURATION ISN’T
ENOUGH:
The default Django configuration lacks:
Multiple settings files for different environments.
Separate packages for different environments.
Flexible configuration without having to alter the code.
Solutions dedicated for production environment: admin panel path, error logging (e.g.
Sentry), cache configuration (memcache/redis), storing files uploaded to the cloud by the
users (S3), HSTS, secure cookies.
Solutions dedicated for testing environment: disabling template debugging, in-memory
caching, sending emails to the console, password hasher, storing the templates.
_DJANGO PROJECTS CONFIGURED FOR MULTIPLE ENVIRONMENTS
_A RECIPE FOR
MULTI-ENVIRONMENT
CONFIGURATION:
Let’s configure a Django project for multiple
environments (production, local and testing).
Our app will use several third-party tools including
PostgreSQL, Sentry, AWS, WhiteNoise, Gunicorn,
Redis, Anymail.
_A RECIPE FOR MULTI-ENVIRONMENT CONFIGURATION
1. Install virtualenv/virtualenvwrapper
2. Install Django: pip install Django == 1.11.5
3. Create your project: django-admin: django-admin startproject djangohotspot
(djangohotspot) ╭ ~/Workspace/
╰$ tree djangohotspot
djangohotspot
├── djangohotspot
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py
_STARTING YOUR PROJECT
(djangohotspot) ╭ ~/Workspace/
╰$ tree djangohotspot
djangohotspot
├── djangohotspot
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── manage.py
└── requirements
├── base.txt
├── local.txt
├── production.txt
└── test.txt
_CREATING SEPARATE REQUIREMENTS.TXT FILES
_REQUIREMENTS FILES
base.txt
django==1.11.5
# Configuration
django-environ==0.4.4
whitenoise==3.3.0
# Models
django-model-utils==3.0.0
# Images
Pillow==4.2.1
# Password storage
argon2-cffi==16.3.0
# Python-PostgreSQL Database Adapter
psycopg2==2.7.3.1
# Unicode slugification
awesome-slugify==1.6.5
# Time zones support
pytz==2017.2
# Redis support
django-redis==4.8.0
redis>=2.10.5
production.txt
-r base.txt
# WSGI Handler
gevent==1.2.2
gunicorn==19.7.1
# Static and Media Storage
boto3==1.4.7
django-storages==1.6.5
# Email backends for Mailgun, Postmark,
# SendGrid and more
django-anymail==0.11.1
# Raven is the Sentry client
raven==6.1.0
_REQUIREMENTS FILES
test.txt
-r base.txt
coverage==4.4.1
flake8==3.4.1
factory-boy==2.9.2
# pytest
pytest-cov==2.4.0
pytest-django==3.1.2
pytest-factoryboy==1.3.1
pytest-mock==1.6.0
pytest-sugar==0.9.0
local.txt
-r test.txt
-r production.txt
django-extensions==1.9.0
ipdb==0.10.3
Let’s not store settings.py in the catalog of your
project’s main app:
djangohotspot/djangohotspot/settings.p
y
Create a python module (in the main catalog) called
config, and an additional settings module
within it.
_SEPARATING THE SETTINGS (djangohotspot) ╭ ~/Workspace/Prezentacja
╰$ tree djangohotspot
djangohotspot
├── config
│ ├── __init__.py
│ └── settings
│ ├── base.py
│ ├── __init__.py
│ ├── local.py
│ ├── production.py
│ └── test.py
├── djangohotspot
│ ├── __init__.py
│ ├── urls.py
│ └── wsgi.py
├── manage.py
└── requirements
├── base.txt
├── local.txt
├── production.txt
└── test.txt
ROOT_DIR = environ.Path (__file__) - 3 # djangohotspot/
APPS_DIR = ROOT_DIR.path ('djangohotspot') # path for django apps
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
AUTOSLUG_SLUGIFY_FUNCTION = 'slugify.slugify' # allows you to define a function for
unicode-supported Slug
DATABASES = { 'default': env.db('DATABASE_URL', default='postgres:///djangohotspot'), }
DATABASES['default']['ATOMIC_REQUESTS'] = True # allows you to open and commit
transaction when there are no exceptions. This could affect the performance negatively
for traffic-heavy apps.
EMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND',
default='django.core.mail.backends.smtp.EmailBackend')
ADMIN_URL = env('DJANGO_ADMIN_URL', default=r'^admin/')
PASSWORD_HASHERS = ['django.contrib.auth.hashers.Argon2PasswordHasher', (...)] # add this
object at the beginning of the list
_CONFIG.SETTINGS.BASE
# import from your base settings file
from .base import *
# add toolbar debug
MIDDLEWARE += ['debug_toolbar.middleware.DebugToolbarMiddleware', ]
INSTALLED_APPS += ['debug_toolbar', ]
DEBUG_TOOLBAR_CONFIG = {
'DISABLE_PANELS': [ 'debug_toolbar.panels.redirects.RedirectsPanel', ],
'SHOW_TEMPLATE_CONTEXT': True,
}
# define:
INTERNAL_IPS = ['127.0.0.1']
# add django extension
INSTALLED_APPS += ['django_extensions', ]
_CONFIG.SETTINGS.LOCAL
# security configuration
SECURE_HSTS_SECONDS = 60
SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool( 'DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS', default=True)
SECURE_CONTENT_TYPE_NOSNIFF = env.bool( 'DJANGO_SECURE_CONTENT_TYPE_NOSNIFF', default=True)
SECURE_BROWSER_XSS_FILTER = True
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = True
SECURE_SSL_REDIRECT = env.bool('DJANGO_SECURE_SSL_REDIRECT', default=True)
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_HTTPONLY = True
X_FRAME_OPTIONS = 'DENY'
ADMIN_URL = env('DJANGO_ADMIN_URL')
Note: It’s useful to add DJANGO_ADMIN_URL to the production settings. Change it from default to avoid attack attempts on the default
URL admin panel.
_CONFIG.SETTINGS.PRODUCTION 1/3
# Add your domain to:
ALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS', default=['djangohotspot.pl', ])
# Add Gunicorn:
INSTALLED_APPS += ['gunicorn', ]
# Add django-storage pod AWS:
INSTALLED_APPS += ['storages', ]
AWS_ACCESS_KEY_ID = env('DJANGO_AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = env('DJANGO_AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = env('DJANGO_AWS_STORAGE_BUCKET_NAME')
AWS_AUTO_CREATE_BUCKET = True
AWS_QUERYSTRING_AUTH = False
AWS_EXPIRY = 60 * 60 * 24 * 7
MEDIA_URL = 'https://s3.amazonaws.com/%s/' % AWS_STORAGE_BUCKET_NAME
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
_CONFIG.SETTINGS.PRODUCTION 2/3
# Add Sentry
INSTALLED_APPS += ['raven.contrib.django.raven_compat', ]
RAVEN_MIDDLEWARE = ['raven.contrib.django.raven_compat.middleware.SentryResponseErrorIdMiddleware']
MIDDLEWARE = RAVEN_MIDDLEWARE + MIDDLEWARE
SENTRY_DSN = env('DJANGO_SENTRY_DSN')
SENTRY_CLIENT = env('DJANGO_SENTRY_CLIENT', default='raven.contrib.django.raven_compat.DjangoClient')
SENTRY_CELERY_LOGLEVEL = env.int('DJANGO_SENTRY_LOG_LEVEL', logging.INFO )
RAVEN_CONFIG = {
'CELERY_LOGLEVEL': env.int('DJANGO_SENTRY_LOG_LEVEL', logging.INFO ),
'DSN': SENTRY_DSN,
}
# Add Whitenoise
WHITENOISE_MIDDLEWARE = ['whitenoise.middleware.WhiteNoiseMiddleware', ]
MIDDLEWARE = WHITENOISE_MIDDLEWARE + MIDDLEWARE
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
_CONFIG.SETTINGS.PRODUCTION 3/3
# Disable debugging
DEBUG = False
TEMPLATES[0]['OPTIONS']['debug'] = False
# Sent emails are stored in the memory and available at django.core.mail.outbox
EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'
# Set cache
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': ''
}
}
# Set password hasher to speed up the testing
PASSWORD_HASHERS = ['django.contrib.auth.hashers.MD5PasswordHasher', ]
# Djanglo templates can be stored in the memory
TEMPLATES[0]['OPTIONS']['loaders'] = [
['django.template.loaders.cached.Loader', [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader', ]
, ]
, ]
_CONFIG.SETTINGS.TEST
1. Move uwsgi.py and urls.py in djangohotspot/djangohotspot to the config module.
2. In config.settings add the following edits:
WSGI_APPLICATION = 'config.wsgi.application'
ROOT_URLCONF = 'config.urls'
3. Add the following code to config.urls in order to debug 4xx and 5xx pages:
if settings.DEBUG:
urlpatterns += [
url(r'^400/$', default_views.bad_request, kwargs={'exception': Exception('Bad Request!')}),
url(r'^403/$', default_views.permission_denied,kwargs={'exception': Exception('Permission Denied')}),
url(r'^404/$', default_views.page_not_found,kwargs={'exception': Exception('Page not Found')}),
url(r'^500/$', default_views.server_error),
]
if 'debug_toolbar' in settings.INSTALLED_APPS:
import debug_toolbar
urlpatterns = [
url(r'^__debug__/', include(debug_toolbar.urls)),
] + urlpatterns
_UWSGI.PY & URLS.PY
import os
import sys
from django.core.wsgi import get_wsgi_application
app_path = os.path.dirname (os.path.abspath (__file__)).replace('/config', '')
sys.path.append (os.path.join (app_path, 'djangohotspot'))
if os.environ.get ('DJANGO_SETTINGS_MODULE') == 'config.settings.production':
from raven.contrib.django.raven_compat.middleware.wsgi import Sentry
os.environ.setdefault ('DJANGO_SETTINGS_MODULE', 'config.settings.production')
application = get_wsgi_application ()
if os.environ.get ('DJANGO_SETTINGS_MODULE') == 'config.settings.production':
application = Sentry(application )
_CONFIG.UWSGI
_THAT’S A WRAP!
VISIT OUR WEBSITE

Contenu connexe

Tendances

Lessons from running potentially malicious code inside containers
Lessons from running potentially malicious code inside containersLessons from running potentially malicious code inside containers
Lessons from running potentially malicious code inside containersBen Hall
 
Automating Complex Setups with Puppet
Automating Complex Setups with PuppetAutomating Complex Setups with Puppet
Automating Complex Setups with PuppetKris Buytaert
 
Vagrant for real (codemotion rome 2016)
Vagrant for real (codemotion rome 2016)Vagrant for real (codemotion rome 2016)
Vagrant for real (codemotion rome 2016)Michele Orselli
 
Running Docker in Development & Production (#ndcoslo 2015)
Running Docker in Development & Production (#ndcoslo 2015)Running Docker in Development & Production (#ndcoslo 2015)
Running Docker in Development & Production (#ndcoslo 2015)Ben Hall
 
Ansible 實戰:top down 觀點
Ansible 實戰:top down 觀點Ansible 實戰:top down 觀點
Ansible 實戰:top down 觀點William Yeh
 
MeaNstack on Docker
MeaNstack on DockerMeaNstack on Docker
MeaNstack on DockerDaniel Ku
 
Docker orchestration v4
Docker orchestration v4Docker orchestration v4
Docker orchestration v4Hojin Kim
 
Running Docker in Development & Production (DevSum 2015)
Running Docker in Development & Production (DevSum 2015)Running Docker in Development & Production (DevSum 2015)
Running Docker in Development & Production (DevSum 2015)Ben Hall
 
Docker composeで開発環境をメンバに配布せよ
Docker composeで開発環境をメンバに配布せよDocker composeで開発環境をメンバに配布せよ
Docker composeで開発環境をメンバに配布せよYusuke Kon
 
App development with quasar (pdf)
App development with quasar (pdf)App development with quasar (pdf)
App development with quasar (pdf)wonyong hwang
 
Herd your chickens: Ansible for DB2 configuration management
Herd your chickens: Ansible for DB2 configuration managementHerd your chickens: Ansible for DB2 configuration management
Herd your chickens: Ansible for DB2 configuration managementFrederik Engelen
 
Hands on Docker - Launch your own LEMP or LAMP stack - SunshinePHP
Hands on Docker - Launch your own LEMP or LAMP stack - SunshinePHPHands on Docker - Launch your own LEMP or LAMP stack - SunshinePHP
Hands on Docker - Launch your own LEMP or LAMP stack - SunshinePHPDana Luther
 
Dockerを利用したローカル環境から本番環境までの構築設計
Dockerを利用したローカル環境から本番環境までの構築設計Dockerを利用したローカル環境から本番環境までの構築設計
Dockerを利用したローカル環境から本番環境までの構築設計Koichi Nagaoka
 
Real World Experience of Running Docker in Development and Production
Real World Experience of Running Docker in Development and ProductionReal World Experience of Running Docker in Development and Production
Real World Experience of Running Docker in Development and ProductionBen Hall
 
Running High Performance and Fault Tolerant Elasticsearch Clusters on Docker
Running High Performance and Fault Tolerant Elasticsearch Clusters on DockerRunning High Performance and Fault Tolerant Elasticsearch Clusters on Docker
Running High Performance and Fault Tolerant Elasticsearch Clusters on DockerSematext Group, Inc.
 
Continuous Delivery: The Next Frontier
Continuous Delivery: The Next FrontierContinuous Delivery: The Next Frontier
Continuous Delivery: The Next FrontierCarlos Sanchez
 
Making Your Capistrano Recipe Book
Making Your Capistrano Recipe BookMaking Your Capistrano Recipe Book
Making Your Capistrano Recipe BookTim Riley
 
이미지 기반의 배포 패러다임 Immutable infrastructure
이미지 기반의 배포 패러다임 Immutable infrastructure이미지 기반의 배포 패러다임 Immutable infrastructure
이미지 기반의 배포 패러다임 Immutable infrastructureDaegwon Kim
 
Ninja Build: Simple Guide for Beginners
Ninja Build: Simple Guide for BeginnersNinja Build: Simple Guide for Beginners
Ninja Build: Simple Guide for BeginnersChang W. Doh
 

Tendances (20)

Lessons from running potentially malicious code inside containers
Lessons from running potentially malicious code inside containersLessons from running potentially malicious code inside containers
Lessons from running potentially malicious code inside containers
 
Automating Complex Setups with Puppet
Automating Complex Setups with PuppetAutomating Complex Setups with Puppet
Automating Complex Setups with Puppet
 
Vagrant for real (codemotion rome 2016)
Vagrant for real (codemotion rome 2016)Vagrant for real (codemotion rome 2016)
Vagrant for real (codemotion rome 2016)
 
Running Docker in Development & Production (#ndcoslo 2015)
Running Docker in Development & Production (#ndcoslo 2015)Running Docker in Development & Production (#ndcoslo 2015)
Running Docker in Development & Production (#ndcoslo 2015)
 
Ansible 實戰:top down 觀點
Ansible 實戰:top down 觀點Ansible 實戰:top down 觀點
Ansible 實戰:top down 觀點
 
MeaNstack on Docker
MeaNstack on DockerMeaNstack on Docker
MeaNstack on Docker
 
kubernetes practice
kubernetes practicekubernetes practice
kubernetes practice
 
Docker orchestration v4
Docker orchestration v4Docker orchestration v4
Docker orchestration v4
 
Running Docker in Development & Production (DevSum 2015)
Running Docker in Development & Production (DevSum 2015)Running Docker in Development & Production (DevSum 2015)
Running Docker in Development & Production (DevSum 2015)
 
Docker composeで開発環境をメンバに配布せよ
Docker composeで開発環境をメンバに配布せよDocker composeで開発環境をメンバに配布せよ
Docker composeで開発環境をメンバに配布せよ
 
App development with quasar (pdf)
App development with quasar (pdf)App development with quasar (pdf)
App development with quasar (pdf)
 
Herd your chickens: Ansible for DB2 configuration management
Herd your chickens: Ansible for DB2 configuration managementHerd your chickens: Ansible for DB2 configuration management
Herd your chickens: Ansible for DB2 configuration management
 
Hands on Docker - Launch your own LEMP or LAMP stack - SunshinePHP
Hands on Docker - Launch your own LEMP or LAMP stack - SunshinePHPHands on Docker - Launch your own LEMP or LAMP stack - SunshinePHP
Hands on Docker - Launch your own LEMP or LAMP stack - SunshinePHP
 
Dockerを利用したローカル環境から本番環境までの構築設計
Dockerを利用したローカル環境から本番環境までの構築設計Dockerを利用したローカル環境から本番環境までの構築設計
Dockerを利用したローカル環境から本番環境までの構築設計
 
Real World Experience of Running Docker in Development and Production
Real World Experience of Running Docker in Development and ProductionReal World Experience of Running Docker in Development and Production
Real World Experience of Running Docker in Development and Production
 
Running High Performance and Fault Tolerant Elasticsearch Clusters on Docker
Running High Performance and Fault Tolerant Elasticsearch Clusters on DockerRunning High Performance and Fault Tolerant Elasticsearch Clusters on Docker
Running High Performance and Fault Tolerant Elasticsearch Clusters on Docker
 
Continuous Delivery: The Next Frontier
Continuous Delivery: The Next FrontierContinuous Delivery: The Next Frontier
Continuous Delivery: The Next Frontier
 
Making Your Capistrano Recipe Book
Making Your Capistrano Recipe BookMaking Your Capistrano Recipe Book
Making Your Capistrano Recipe Book
 
이미지 기반의 배포 패러다임 Immutable infrastructure
이미지 기반의 배포 패러다임 Immutable infrastructure이미지 기반의 배포 패러다임 Immutable infrastructure
이미지 기반의 배포 패러다임 Immutable infrastructure
 
Ninja Build: Simple Guide for Beginners
Ninja Build: Simple Guide for BeginnersNinja Build: Simple Guide for Beginners
Ninja Build: Simple Guide for Beginners
 

Similaire à Configuring Django projects for multiple environments

Effective Python Package Management [PyCon Canada 2017]
Effective Python Package Management [PyCon Canada 2017]Effective Python Package Management [PyCon Canada 2017]
Effective Python Package Management [PyCon Canada 2017]Devon Bernard
 
PyCon AU 2010 - Getting Started With Apache/mod_wsgi.
PyCon AU 2010 - Getting Started With Apache/mod_wsgi.PyCon AU 2010 - Getting Started With Apache/mod_wsgi.
PyCon AU 2010 - Getting Started With Apache/mod_wsgi.Graham Dumpleton
 
Nko workshop - node js crud & deploy
Nko workshop - node js crud & deployNko workshop - node js crud & deploy
Nko workshop - node js crud & deploySimon Su
 
Pyramid Deployment and Maintenance
Pyramid Deployment and MaintenancePyramid Deployment and Maintenance
Pyramid Deployment and MaintenanceJazkarta, Inc.
 
Burn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesBurn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesLindsay Holmwood
 
Writing and Publishing Puppet Modules - PuppetConf 2014
Writing and Publishing Puppet Modules - PuppetConf 2014Writing and Publishing Puppet Modules - PuppetConf 2014
Writing and Publishing Puppet Modules - PuppetConf 2014Puppet
 
Deploying Django with Ansible
Deploying Django with AnsibleDeploying Django with Ansible
Deploying Django with Ansibleandrewmirskynet
 
Cloud Meetup - Automation in the Cloud
Cloud Meetup - Automation in the CloudCloud Meetup - Automation in the Cloud
Cloud Meetup - Automation in the Cloudpetriojala123
 
Zero Downtime Deployment with Ansible
Zero Downtime Deployment with AnsibleZero Downtime Deployment with Ansible
Zero Downtime Deployment with AnsibleStein Inge Morisbak
 
Practical Chef and Capistrano for Your Rails App
Practical Chef and Capistrano for Your Rails AppPractical Chef and Capistrano for Your Rails App
Practical Chef and Capistrano for Your Rails AppSmartLogic
 
X64服务器 lnmp服务器部署标准 new
X64服务器 lnmp服务器部署标准 newX64服务器 lnmp服务器部署标准 new
X64服务器 lnmp服务器部署标准 newYiwei Ma
 
Zend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_ToolZend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_ToolGordon Forsythe
 
The Best (and Worst) of Django
The Best (and Worst) of DjangoThe Best (and Worst) of Django
The Best (and Worst) of DjangoJacob Kaplan-Moss
 
Django Architecture Introduction
Django Architecture IntroductionDjango Architecture Introduction
Django Architecture IntroductionHaiqi Chen
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsAlessandro Molina
 
Running Django on Docker: a workflow and code
Running Django on Docker: a workflow and codeRunning Django on Docker: a workflow and code
Running Django on Docker: a workflow and codeDanielle Madeley
 

Similaire à Configuring Django projects for multiple environments (20)

Effective Python Package Management [PyCon Canada 2017]
Effective Python Package Management [PyCon Canada 2017]Effective Python Package Management [PyCon Canada 2017]
Effective Python Package Management [PyCon Canada 2017]
 
PyCon AU 2010 - Getting Started With Apache/mod_wsgi.
PyCon AU 2010 - Getting Started With Apache/mod_wsgi.PyCon AU 2010 - Getting Started With Apache/mod_wsgi.
PyCon AU 2010 - Getting Started With Apache/mod_wsgi.
 
Nko workshop - node js crud & deploy
Nko workshop - node js crud & deployNko workshop - node js crud & deploy
Nko workshop - node js crud & deploy
 
Pyramid Deployment and Maintenance
Pyramid Deployment and MaintenancePyramid Deployment and Maintenance
Pyramid Deployment and Maintenance
 
Burn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesBurn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websites
 
Writing and Publishing Puppet Modules - PuppetConf 2014
Writing and Publishing Puppet Modules - PuppetConf 2014Writing and Publishing Puppet Modules - PuppetConf 2014
Writing and Publishing Puppet Modules - PuppetConf 2014
 
Deploying Django with Ansible
Deploying Django with AnsibleDeploying Django with Ansible
Deploying Django with Ansible
 
Cloud Meetup - Automation in the Cloud
Cloud Meetup - Automation in the CloudCloud Meetup - Automation in the Cloud
Cloud Meetup - Automation in the Cloud
 
Zero Downtime Deployment with Ansible
Zero Downtime Deployment with AnsibleZero Downtime Deployment with Ansible
Zero Downtime Deployment with Ansible
 
Practical Chef and Capistrano for Your Rails App
Practical Chef and Capistrano for Your Rails AppPractical Chef and Capistrano for Your Rails App
Practical Chef and Capistrano for Your Rails App
 
R sharing 101
R sharing 101R sharing 101
R sharing 101
 
Django
DjangoDjango
Django
 
X64服务器 lnmp服务器部署标准 new
X64服务器 lnmp服务器部署标准 newX64服务器 lnmp服务器部署标准 new
X64服务器 lnmp服务器部署标准 new
 
Zend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_ToolZend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_Tool
 
The Best (and Worst) of Django
The Best (and Worst) of DjangoThe Best (and Worst) of Django
The Best (and Worst) of Django
 
Django Architecture Introduction
Django Architecture IntroductionDjango Architecture Introduction
Django Architecture Introduction
 
Vagrant for real
Vagrant for realVagrant for real
Vagrant for real
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable Applications
 
Running Django on Docker: a workflow and code
Running Django on Docker: a workflow and codeRunning Django on Docker: a workflow and code
Running Django on Docker: a workflow and code
 
Oracle API Gateway Installation
Oracle API Gateway InstallationOracle API Gateway Installation
Oracle API Gateway Installation
 

Plus de Apptension

Team Happiness - O szczęściu w zespole
Team Happiness - O szczęściu w zespoleTeam Happiness - O szczęściu w zespole
Team Happiness - O szczęściu w zespoleApptension
 
D3.js - A picture is worth a thousand words
D3.js - A picture is worth a thousand wordsD3.js - A picture is worth a thousand words
D3.js - A picture is worth a thousand wordsApptension
 
Universal Javascript in React
Universal Javascript in ReactUniversal Javascript in React
Universal Javascript in ReactApptension
 
Testerzy na orbicie
Testerzy na orbicieTesterzy na orbicie
Testerzy na orbicieApptension
 
An introduction to Angular2
An introduction to Angular2 An introduction to Angular2
An introduction to Angular2 Apptension
 
AngularJS - podstawy
AngularJS - podstawyAngularJS - podstawy
AngularJS - podstawyApptension
 

Plus de Apptension (7)

White Space
White SpaceWhite Space
White Space
 
Team Happiness - O szczęściu w zespole
Team Happiness - O szczęściu w zespoleTeam Happiness - O szczęściu w zespole
Team Happiness - O szczęściu w zespole
 
D3.js - A picture is worth a thousand words
D3.js - A picture is worth a thousand wordsD3.js - A picture is worth a thousand words
D3.js - A picture is worth a thousand words
 
Universal Javascript in React
Universal Javascript in ReactUniversal Javascript in React
Universal Javascript in React
 
Testerzy na orbicie
Testerzy na orbicieTesterzy na orbicie
Testerzy na orbicie
 
An introduction to Angular2
An introduction to Angular2 An introduction to Angular2
An introduction to Angular2
 
AngularJS - podstawy
AngularJS - podstawyAngularJS - podstawy
AngularJS - podstawy
 

Dernier

Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 

Dernier (20)

Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 

Configuring Django projects for multiple environments

  • 1. _DJANGO PROJECTS CONFIGURED FOR MULTIPLE ENVIRONMENTS KRYSTIAN HANEK Backend Developer apptension.com
  • 3. The default Django configuration lacks: Multiple settings files for different environments. Separate packages for different environments. Flexible configuration without having to alter the code. Solutions dedicated for production environment: admin panel path, error logging (e.g. Sentry), cache configuration (memcache/redis), storing files uploaded to the cloud by the users (S3), HSTS, secure cookies. Solutions dedicated for testing environment: disabling template debugging, in-memory caching, sending emails to the console, password hasher, storing the templates. _DJANGO PROJECTS CONFIGURED FOR MULTIPLE ENVIRONMENTS
  • 5. Let’s configure a Django project for multiple environments (production, local and testing). Our app will use several third-party tools including PostgreSQL, Sentry, AWS, WhiteNoise, Gunicorn, Redis, Anymail. _A RECIPE FOR MULTI-ENVIRONMENT CONFIGURATION
  • 6. 1. Install virtualenv/virtualenvwrapper 2. Install Django: pip install Django == 1.11.5 3. Create your project: django-admin: django-admin startproject djangohotspot (djangohotspot) ╭ ~/Workspace/ ╰$ tree djangohotspot djangohotspot ├── djangohotspot │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── manage.py _STARTING YOUR PROJECT
  • 7. (djangohotspot) ╭ ~/Workspace/ ╰$ tree djangohotspot djangohotspot ├── djangohotspot │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py └── requirements ├── base.txt ├── local.txt ├── production.txt └── test.txt _CREATING SEPARATE REQUIREMENTS.TXT FILES
  • 8. _REQUIREMENTS FILES base.txt django==1.11.5 # Configuration django-environ==0.4.4 whitenoise==3.3.0 # Models django-model-utils==3.0.0 # Images Pillow==4.2.1 # Password storage argon2-cffi==16.3.0 # Python-PostgreSQL Database Adapter psycopg2==2.7.3.1 # Unicode slugification awesome-slugify==1.6.5 # Time zones support pytz==2017.2 # Redis support django-redis==4.8.0 redis>=2.10.5 production.txt -r base.txt # WSGI Handler gevent==1.2.2 gunicorn==19.7.1 # Static and Media Storage boto3==1.4.7 django-storages==1.6.5 # Email backends for Mailgun, Postmark, # SendGrid and more django-anymail==0.11.1 # Raven is the Sentry client raven==6.1.0
  • 9. _REQUIREMENTS FILES test.txt -r base.txt coverage==4.4.1 flake8==3.4.1 factory-boy==2.9.2 # pytest pytest-cov==2.4.0 pytest-django==3.1.2 pytest-factoryboy==1.3.1 pytest-mock==1.6.0 pytest-sugar==0.9.0 local.txt -r test.txt -r production.txt django-extensions==1.9.0 ipdb==0.10.3
  • 10. Let’s not store settings.py in the catalog of your project’s main app: djangohotspot/djangohotspot/settings.p y Create a python module (in the main catalog) called config, and an additional settings module within it. _SEPARATING THE SETTINGS (djangohotspot) ╭ ~/Workspace/Prezentacja ╰$ tree djangohotspot djangohotspot ├── config │ ├── __init__.py │ └── settings │ ├── base.py │ ├── __init__.py │ ├── local.py │ ├── production.py │ └── test.py ├── djangohotspot │ ├── __init__.py │ ├── urls.py │ └── wsgi.py ├── manage.py └── requirements ├── base.txt ├── local.txt ├── production.txt └── test.txt
  • 11. ROOT_DIR = environ.Path (__file__) - 3 # djangohotspot/ APPS_DIR = ROOT_DIR.path ('djangohotspot') # path for django apps INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS AUTOSLUG_SLUGIFY_FUNCTION = 'slugify.slugify' # allows you to define a function for unicode-supported Slug DATABASES = { 'default': env.db('DATABASE_URL', default='postgres:///djangohotspot'), } DATABASES['default']['ATOMIC_REQUESTS'] = True # allows you to open and commit transaction when there are no exceptions. This could affect the performance negatively for traffic-heavy apps. EMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND', default='django.core.mail.backends.smtp.EmailBackend') ADMIN_URL = env('DJANGO_ADMIN_URL', default=r'^admin/') PASSWORD_HASHERS = ['django.contrib.auth.hashers.Argon2PasswordHasher', (...)] # add this object at the beginning of the list _CONFIG.SETTINGS.BASE
  • 12. # import from your base settings file from .base import * # add toolbar debug MIDDLEWARE += ['debug_toolbar.middleware.DebugToolbarMiddleware', ] INSTALLED_APPS += ['debug_toolbar', ] DEBUG_TOOLBAR_CONFIG = { 'DISABLE_PANELS': [ 'debug_toolbar.panels.redirects.RedirectsPanel', ], 'SHOW_TEMPLATE_CONTEXT': True, } # define: INTERNAL_IPS = ['127.0.0.1'] # add django extension INSTALLED_APPS += ['django_extensions', ] _CONFIG.SETTINGS.LOCAL
  • 13. # security configuration SECURE_HSTS_SECONDS = 60 SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool( 'DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS', default=True) SECURE_CONTENT_TYPE_NOSNIFF = env.bool( 'DJANGO_SECURE_CONTENT_TYPE_NOSNIFF', default=True) SECURE_BROWSER_XSS_FILTER = True SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True SECURE_SSL_REDIRECT = env.bool('DJANGO_SECURE_SSL_REDIRECT', default=True) CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = True X_FRAME_OPTIONS = 'DENY' ADMIN_URL = env('DJANGO_ADMIN_URL') Note: It’s useful to add DJANGO_ADMIN_URL to the production settings. Change it from default to avoid attack attempts on the default URL admin panel. _CONFIG.SETTINGS.PRODUCTION 1/3
  • 14. # Add your domain to: ALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS', default=['djangohotspot.pl', ]) # Add Gunicorn: INSTALLED_APPS += ['gunicorn', ] # Add django-storage pod AWS: INSTALLED_APPS += ['storages', ] AWS_ACCESS_KEY_ID = env('DJANGO_AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = env('DJANGO_AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = env('DJANGO_AWS_STORAGE_BUCKET_NAME') AWS_AUTO_CREATE_BUCKET = True AWS_QUERYSTRING_AUTH = False AWS_EXPIRY = 60 * 60 * 24 * 7 MEDIA_URL = 'https://s3.amazonaws.com/%s/' % AWS_STORAGE_BUCKET_NAME DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' _CONFIG.SETTINGS.PRODUCTION 2/3
  • 15. # Add Sentry INSTALLED_APPS += ['raven.contrib.django.raven_compat', ] RAVEN_MIDDLEWARE = ['raven.contrib.django.raven_compat.middleware.SentryResponseErrorIdMiddleware'] MIDDLEWARE = RAVEN_MIDDLEWARE + MIDDLEWARE SENTRY_DSN = env('DJANGO_SENTRY_DSN') SENTRY_CLIENT = env('DJANGO_SENTRY_CLIENT', default='raven.contrib.django.raven_compat.DjangoClient') SENTRY_CELERY_LOGLEVEL = env.int('DJANGO_SENTRY_LOG_LEVEL', logging.INFO ) RAVEN_CONFIG = { 'CELERY_LOGLEVEL': env.int('DJANGO_SENTRY_LOG_LEVEL', logging.INFO ), 'DSN': SENTRY_DSN, } # Add Whitenoise WHITENOISE_MIDDLEWARE = ['whitenoise.middleware.WhiteNoiseMiddleware', ] MIDDLEWARE = WHITENOISE_MIDDLEWARE + MIDDLEWARE STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' _CONFIG.SETTINGS.PRODUCTION 3/3
  • 16. # Disable debugging DEBUG = False TEMPLATES[0]['OPTIONS']['debug'] = False # Sent emails are stored in the memory and available at django.core.mail.outbox EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' # Set cache CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': '' } } # Set password hasher to speed up the testing PASSWORD_HASHERS = ['django.contrib.auth.hashers.MD5PasswordHasher', ] # Djanglo templates can be stored in the memory TEMPLATES[0]['OPTIONS']['loaders'] = [ ['django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ] , ] , ] _CONFIG.SETTINGS.TEST
  • 17. 1. Move uwsgi.py and urls.py in djangohotspot/djangohotspot to the config module. 2. In config.settings add the following edits: WSGI_APPLICATION = 'config.wsgi.application' ROOT_URLCONF = 'config.urls' 3. Add the following code to config.urls in order to debug 4xx and 5xx pages: if settings.DEBUG: urlpatterns += [ url(r'^400/$', default_views.bad_request, kwargs={'exception': Exception('Bad Request!')}), url(r'^403/$', default_views.permission_denied,kwargs={'exception': Exception('Permission Denied')}), url(r'^404/$', default_views.page_not_found,kwargs={'exception': Exception('Page not Found')}), url(r'^500/$', default_views.server_error), ] if 'debug_toolbar' in settings.INSTALLED_APPS: import debug_toolbar urlpatterns = [ url(r'^__debug__/', include(debug_toolbar.urls)), ] + urlpatterns _UWSGI.PY & URLS.PY
  • 18. import os import sys from django.core.wsgi import get_wsgi_application app_path = os.path.dirname (os.path.abspath (__file__)).replace('/config', '') sys.path.append (os.path.join (app_path, 'djangohotspot')) if os.environ.get ('DJANGO_SETTINGS_MODULE') == 'config.settings.production': from raven.contrib.django.raven_compat.middleware.wsgi import Sentry os.environ.setdefault ('DJANGO_SETTINGS_MODULE', 'config.settings.production') application = get_wsgi_application () if os.environ.get ('DJANGO_SETTINGS_MODULE') == 'config.settings.production': application = Sentry(application ) _CONFIG.UWSGI
  • 19. _THAT’S A WRAP! VISIT OUR WEBSITE