Code source de settings

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Django settings for Django_Client project.

import socket
import platform
import os.path
from django.utils.translation import ugettext_lazy as _

#: Est-on sur la note de dev ?
DEV = (socket.gethostname() in ["bde-test", "bde-test-virt"])
#: Est-on sur la note de prod ?
PROD = (socket.gethostname() in ["bde2", "bde2-virt",])

# Sur quel système la note tourne-t-elle ?
SYSTEM, NODE_NAME, KERNEL, KERNEL_VERSION, __, __ = platform.uname()

if SYSTEM == 'Linux':
    DISTRIBUTION, DIST_VERSION, __ = platform.linux_distribution()
else:
    DISTRIBUTION, DIST_VERSION = None, None

#: Charset par défaut
DEFAULT_CHARSET = "utf-8"
#: Mode de debug
DEBUG = not PROD


#: Adresse mail à qui envoyer des problèmes durant l'exécution
REPORT_BUGS_EMAIL = 'notekfet2015@crans.org'

#: Liste des administrateurs et de leur mails
ADMINS = [('Report bugs to', REPORT_BUGS_EMAIL)]

#: Hôtes pour lesquelles la note a le droit de répondre
ALLOWED_HOSTS = [
    '.crans.org',
]

#: Url racine
NOTE_ROOT_URL = r'/note/'
#: Url de la page de login
NOTE_LOGIN_URL = NOTE_ROOT_URL

#: Chemin absolu du répertoire racine du client django
#: (Le os.path.join est là pour assurer la présence du trailing slash)
ROOT_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "")

PROJECT_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))

#: From des messages d'erreur
SERVER_EMAIL = "notekfet2015@crans.org"
#: A tuple in the same format as ADMINS that specifies who should get broken link notifications when BrokenLinkEmailsMiddleware is enabled.
MANAGERS = ADMINS

#: Base de données pour stocker les data django.
#: Dans le cas de la NoteKfet2015, elle n'est utilisé que pour stocker les sessions
#: puisque tout est fait dans le backend.
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'django_client',                      # Or path to database file if using sqlite3.
        'USER': 'note',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

#: Local time zone for this installation. Choices can be found here:
#: http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
#: although not all choices may be available on all operating systems.
#: On Unix systems, a value of None will cause Django to use the same
#: timezone as the operating system.
#: If running in a Windows environment this must be set to the same as your
#: system time zone.
TIME_ZONE = 'Europe/Paris'

#: Language code for this installation. All choices can be found here:
#: http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'fr-FR'

#: The ID, as an integer, of the current site in the django_site database table.
#: This is used so that application data can hook into specific sites
#: and a single database can manage content for multiple sites.
SITE_ID = 1

#: If you set this to False, Django will make some optimizations so as not
#: to load the internationalization machinery.
USE_I18N = True

LANGUAGES = [
    ('fr', _(u"Français")),
    ('en', _(u"Anglais")),
]

DEFAULT_LANGUAGE = 1

LOCALE_PATHS = [
    os.path.join(ROOT_PATH, 'locale/'),
    os.path.join(PROJECT_PATH, '../static/js/custom/locale/'),
]

#: If you set this to False, Django will not format dates, numbers and
#: calendars according to the current locale.
USE_L10N = True

#: If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

#: Absolute filesystem path to the directory that will hold user-uploaded files.
#: Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media/')

#: URL that handles the media served from MEDIA_ROOT. Make sure to use a
#: trailing slash.
#: Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = os.path.join(NOTE_ROOT_URL, 'media/')

#: Absolute path to the directory static files should be collected to.
#: 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 = ROOT_PATH + 'static/'

#: URL prefix for static files.
#: Example: "http://media.lawrence.com/static/"
STATIC_URL = r'/static/'

#: Additional locations of static files
STATICFILES_DIRS = (
    os.path.join(PROJECT_PATH, '../static/'),
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

#: List of finder classes that know how to find static files in
#: various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

from secrets import SECRET_KEY

#: List of callables that know how to import templates from various sources.

TEMPLATES = [{
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],
        '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',
             ],
                                    },
             }]

#: A tuple of middleware classes to use. See `Middleware <https://docs.djangoproject.com/en/dev/topics/http/middleware/>`_.
MIDDLEWARE = [
#    'note.middleware.WhoAmiMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

#: A string representing the full Python import path to your root URLconf.
#: For example: "mydjangoapps.urls".
#: Can be overridden on a per-request basis by setting the attribute
#: urlconf on the incoming HttpRequest object.
ROOT_URLCONF = 'urls'

#: Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'note.wsgi.application'



#: A tuple of strings designating all applications that are enabled in this Django installation.
#: Each string should be a full Python path to a Python package that contains a Django application,
#: as created by ``django-admin.py startapp``.
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'note',
)

#: A sample logging configuration. The only tangible logging
#: performed by this configuration is to send an email to
#: the site admins on every HTTP 500 error when DEBUG=False.
#: See http://docs.djangoproject.com/en/dev/topics/logging for
#: more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

#: ttl des cookies Django en secondes
SESSION_COOKIE_AGE = 60*100 # 100 minutes

### Photos
#: Taille max autorisée pour les photos
MAX_PHOTO_SIZE = 870000 # en bytes (850KB)
#: Dossier où sont stockées les photos temporairement
PHOTOS_PATH = MEDIA_ROOT + "photos/"
#: URL par laquelle on accède aux photos
PHOTOS_URL = MEDIA_URL + "photos/"
#: Temps avant de supprimer un fichier de photo temporaire
#: Pendant cet intervalle de temps,
#: la photo pourra être affichée sans être redemandée au serveur NK2015
TIME_BEFORE_PHOTO_DELETE=60*5 # secondes

### Network
#: IP où joindre le serveur NK2015
NK2015_IP = "127.0.0.1"
#: Port d'écoute du serveur NK2015
NK2015_PORT = 4242

### Paramètres d'affichage
## Dates
#: Format avec lequel les dates arrivent du serveur NK2015
DATETIME_INPUT_FORMAT = u"%Y-%m-%d %H:%M:%S"
#: Format d'affichage des dates
DATETIME_RENDERING_FORMAT = _(u"Le %d/%m/%Y à %H:%M:%S") # C'est volontaire si ce n'est pas une chaîne unicode !
#: Année jusqu'à laquelle les dates sont en 20nn
YEAR_1900s_OVER = 69

### Masques de droits
#: Droits qu'on n'a pas en se connectant en "restricted"
_acl_restricted = ["myself", "overforced", "transactions_admin", "chgpass", "comptes", "boutons", "admin", "digicode"]
_acl_restricted_weak = ["overforced", "transactions_admin", "chgpass", "comptes", "boutons", "admin", "digicode"]

#: Dico recensant les masques de droits : ``keyword`` -> ``("nom à afficher", <masque>)``
#: ils seront proposés dans l'ordre des keywords
ACL_MASKS = {
    '2_all': (_(u"Tous mes droits"), [[], [], False]),
    '1_note': (_(u"Droits note seulement"), [_acl_restricted, _acl_restricted, True]),
    '0_basic': (_(u"Droits basiques"), [_acl_restricted_weak, _acl_restricted_weak, True]),
    }
_acl_masks_keys = ACL_MASKS.keys()
_acl_masks_keys.sort()

# Liste rencensant les tuples des pages existantes sous le format
# (nom, adresse, droit)
EXISTING_PAGES = [("Index", "index", "login"),
                  ("Consos", "consos", "consos"),
                  ("Comptes", "comptes", "search"),
                  ("Activités", "activites", "activites"),
                  ("Boutons", "boutons", "boutons"),
                  ("Inscriptions", "inscriptions", "inscriptions"),
                  ("Virements", "virements", "dons"),
                  ("Trésorerie","tresorerie","tresorerie"),
                  ("WEI", "wei", "wei"),
                  ("Droits", "listedroits", "liste_droits"),
                 ]

[docs]def dummy(): """Chaîne à traduire. Les valeurs étant générées à la volée ou ne pouvant être déclarable comme à traduire le sont ici. """ # Le noms des pages _(u"Index") _(u"Consos") _(u"Comptes") _(u"Activités") _(u"Boutons") _(u"Inscriptions") _(u"Virements") _(u"Trésorerie") _(u"Wei") # Les noms des catégories des boutons _(u"Alcool") _(u"Autre") _(u"BDA") _(u"Bouffe") _(u"Clubs") _(u"Soft") _(u"TNA") _(u"PR") _(u"Pulls")