]> git.parisson.com Git - telemeta.git/commitdiff
Add Dockerfile and docker-compose config, update sandbox config
authorGuillaume Pellerin <yomguy@parisson.com>
Thu, 12 Mar 2015 16:41:23 +0000 (17:41 +0100)
committerGuillaume Pellerin <yomguy@parisson.com>
Thu, 12 Mar 2015 16:41:23 +0000 (17:41 +0100)
29 files changed:
Dockerfile [new file with mode: 0644]
docker-compose.yml [new file with mode: 0644]
example/apache2/telemeta.conf [deleted file]
example/data/format/original_format.txt [deleted file]
example/sandbox/__init__.py [deleted file]
example/sandbox/diag.sh [deleted file]
example/sandbox/manage.py [deleted file]
example/sandbox/modelviz.py [deleted file]
example/sandbox/robots.txt [deleted file]
example/sandbox/settings.py [deleted file]
example/sandbox/update_schema.sh [deleted file]
example/sandbox/urls.py [deleted file]
example/sandbox/wsgi.py [deleted file]
examples/deploy/apache-app.conf [new file with mode: 0644]
examples/deploy/apt-app.list [new file with mode: 0644]
examples/deploy/nginx-app.conf [new file with mode: 0644]
examples/deploy/start_app.sh [new file with mode: 0644]
examples/fixtures/original_format.txt [new file with mode: 0644]
examples/sandbox/__init__.py [new file with mode: 0644]
examples/sandbox/diag.sh [new file with mode: 0755]
examples/sandbox/manage.py [new file with mode: 0755]
examples/sandbox/modelviz.py [new file with mode: 0644]
examples/sandbox/robots.txt [new file with mode: 0644]
examples/sandbox/settings.py [new file with mode: 0644]
examples/sandbox/update_schema.sh [new file with mode: 0755]
examples/sandbox/urls.py [new file with mode: 0644]
examples/sandbox/wsgi.py [new file with mode: 0644]
setup.py
telemeta/management/commands/telemeta-create-admin-user.py [new file with mode: 0644]

diff --git a/Dockerfile b/Dockerfile
new file mode 100644 (file)
index 0000000..02cfce4
--- /dev/null
@@ -0,0 +1,34 @@
+# Copyright 2013 Thatcher Peskens
+# Copyright 2014-2015 Guillaume Pellerin
+# Copyright 2014-2015 Thomas Fillon
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+FROM parisson/timeside:latest
+
+MAINTAINER Guillaume Pellerin <yomguy@parisson.com>, Thomas fillon <thomas@parisson.com>
+
+# Clone app
+RUN mkdir /opt/Telemeta
+ADD . /opt/Telemeta
+WORKDIR /opt/Telemeta
+
+# Install deps
+RUN pip install -r requirements.txt
+
+# Sandbox setup
+RUN /opt/Telemeta/examples/sandbox/manage.py syncdb --noinput
+RUN /opt/Telemeta/examples/sandbox/manage.py migrate --noinput
+RUN /opt/Telemeta/examples/sandbox/manage.py collectstatic --noinput
+
+EXPOSE 8000
diff --git a/docker-compose.yml b/docker-compose.yml
new file mode 100644 (file)
index 0000000..b196e49
--- /dev/null
@@ -0,0 +1,57 @@
+home:
+  image: debian:wheezy
+  volumes:
+    - ./examples/sandbox:/home/telemeta
+  command: /bin/true
+
+static:
+  image: debian:wheezy
+  volumes:
+    - /var/www/static
+  command: true
+
+log:
+  image: debian:wheezy
+  volumes:
+    - /var/log/nginx
+    - /var/log/postgres
+    - /var/log/uwsgi
+  command: /bin/true
+
+# datadb:
+#   image: debian:wheezy
+#   volumes:
+#     - /var/lib/postgresql
+#   command: /bin/true
+
+# db:
+#   image: postgres
+#   volumes_from:
+#     - datadb
+
+nginx:
+  image: nginx
+  ports:
+    - "8000:80"
+  volumes:
+    - ./examples/deploy/nginx-app.conf:/etc/nginx/conf.d/default.conf
+  volumes_from:
+    - static
+    - home
+    - log
+  links:
+    - app
+
+app:
+  build: .
+  volumes:
+    - .:/opt/Telemeta
+  volumes_from:
+    - static
+    - home
+    - log
+  command: /bin/sh /opt/Telemeta/examples/deploy/start_app.sh
+  ports:
+    - "9000:9000"
+  expose:
+    - "80" #default runserver wsgi port
\ No newline at end of file
diff --git a/example/apache2/telemeta.conf b/example/apache2/telemeta.conf
deleted file mode 100644 (file)
index d0bffa7..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-<VirtualHost *:80>
-       ServerAdmin webmaster@localhost
-        ServerName telemeta.wm22.parisson.org
-
-        LogLevel warn
-       ErrorLog ${APACHE_LOG_DIR}/error-telemeta.log
-       # Possible values include: debug, info, notice, warn, error, crit,
-       # alert, emerg.
-       CustomLog ${APACHE_LOG_DIR}/access-telemeta.log combined
-
-       Alias /media/ /home/dev/telemeta/example/sandbox/media/
-
-        <Directory /home/dev/telemeta/example/sandbox/>
-         Order deny,allow
-         Allow from all
-        </Directory>
-
-        WSGIDaemonProcess telemeta_test user=www-data group=www-data threads=12 processes=4 maximum-requests=1000 deadlock-timeout=300
-        WSGIProcessGroup telemeta_test
-        WSGIApplicationGroup %{GLOBAL}
-        WSGIScriptAlias / /home/dev/telemeta/example/sandbox/wsgi.py
-
-
-#<Location "/media">
-#    SetHandler None
-#</Location>
-
-Alias /favicon.ico /home/dev/telemeta/telemeta/static/telemeta/images/favicon.ico
-
-<LocationMatch "\.(ico|txt)$">
-    SetHandler None
-</LocationMatch>
-
-DocumentRoot /var/www/
-Alias /static/ /var/www/telemeta/
-
-        <Directory /var/www/>
-                Options Indexes FollowSymLinks MultiViews
-                AllowOverride None
-                Order allow,deny
-                allow from all
-        </Directory>
-
-</VirtualHost>
diff --git a/example/data/format/original_format.txt b/example/data/format/original_format.txt
deleted file mode 100644 (file)
index 1a5bc13..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-Bande magnétique 6,25mm (1/4')
-Bande magnétique mini-Nagra 3,81mm 
-Cassette analogique 
-Cassette analogique Type I (Fe)
-Cassette analogique Type II (CrO2)
-Cassette analogique Type IV (Metal)
-Cylindre de cire à gravure directe
-Cylindre de cire édité
-Fil magnétique
-Disque à gravure directe
-Disque 78 tours
-Disque 45 tours
-Disque 33 tours
-Cassette audionumérique PCM F1 Betamax
-Cassette audionumérique PCM 1610/1630 U-Matic
-Cassette audionumérique DAT
-Cassette audionumérique DAT 48 kHz
-Cassette audionumérique DAT 44,1 kHz
-Cassette audionumérique DAT 32 kHz
-Bande magnétique audionumérique 1/4" (DASH, ProDigi, EIAJ-C, Nagra-D)
-Mini-Disc
-CD-A (Audio édité)
-CD-R Audio
-CD-RW Audio
-CD-R Data
-CD-ROM édité
-CD-RW Data
-DVD-R Data
-DVD+R Data
-DVD-ROM édité
-DVD-RW Data
-DVD+RW Data
-BD-ROM édité (Blu-ray)
-BD-R (Blu-ray enregistrable)
-BD-RE (Blu-ray réinscriptible)
-Disque dur (HDD)
-Carte mémoire
-SSD
diff --git a/example/sandbox/__init__.py b/example/sandbox/__init__.py
deleted file mode 100644 (file)
index e69de29..0000000
diff --git a/example/sandbox/diag.sh b/example/sandbox/diag.sh
deleted file mode 100755 (executable)
index 5f6c1e5..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-#!/bin/sh
-
-app="telemeta"
-dir="../../doc/devel"
-
-python modelviz.py -a > $dir/$app-all.dot
-python modelviz.py $app > $dir/$app.dot
-
-dot $dir/$app-all.dot -Tpdf -o $dir/$app-all.pdf
-dot $dir/$app.dot -Tpdf -o $dir/$app.pdf
-
-rsync -a $dir/ doc.parisson.com:/var/www/files/doc/$app/diagram/
diff --git a/example/sandbox/manage.py b/example/sandbox/manage.py
deleted file mode 100755 (executable)
index c632a8a..0000000
+++ /dev/null
@@ -1,9 +0,0 @@
-#!/usr/bin/env python
-import os, sys
-
-if __name__ == "__main__":
-    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
-
-    from django.core.management import execute_from_command_line
-
-    execute_from_command_line(sys.argv)
diff --git a/example/sandbox/modelviz.py b/example/sandbox/modelviz.py
deleted file mode 100644 (file)
index 24af062..0000000
+++ /dev/null
@@ -1,359 +0,0 @@
-#!/usr/bin/env python
-
-"""Django model to DOT (Graphviz) converter
-by Antonio Cavedoni <antonio@cavedoni.org>
-
-Make sure your DJANGO_SETTINGS_MODULE is set to your project or
-place this script in the same directory of the project and call
-the script like this:
-
-$ python modelviz.py [-h] [-a] [-d] [-g] [-n] [-L <language>] [-i <model_names>] <app_label> ... <app_label> > <filename>.dot
-$ dot <filename>.dot -Tpng -o <filename>.png
-
-options:
-    -h, --help
-    show this help message and exit.
-
-    -a, --all_applications
-    show models from all applications.
-
-    -d, --disable_fields
-    don't show the class member fields.
-
-    -g, --group_models
-    draw an enclosing box around models from the same app.
-
-    -i, --include_models=User,Person,Car
-    only include selected models in graph.
-
-    -n, --verbose_names
-    use verbose_name for field and models.
-
-    -L, --language
-    specify language used for verrbose_name localization
-
-    -x, --exclude_columns
-    exclude specific column(s) from the graph.
-
-    -X, --exclude_models
-    exclude specific model(s) from the graph.
-    
-    -e, --inheritance
-    show inheritance arrows.
-"""
-__version__ = "0.9"
-__svnid__ = "$Id$"
-__license__ = "Python"
-__author__ = "Antonio Cavedoni <http://cavedoni.com/>"
-__contributors__ = [
-   "Stefano J. Attardi <http://attardi.org/>",
-   "limodou <http://www.donews.net/limodou/>",
-   "Carlo C8E Miron",
-   "Andre Campos <cahenan@gmail.com>",
-   "Justin Findlay <jfindlay@gmail.com>",
-   "Alexander Houben <alexander@houben.ch>",
-   "Bas van Oostveen <v.oostveen@gmail.com>",
-   "Joern Hees <gitdev@joernhees.de>"
-]
-
-import os
-import sys
-import getopt
-
-from django.core.management import setup_environ
-
-try:
-    import settings
-except ImportError:
-    pass
-else:
-    setup_environ(settings)
-
-from django.utils.translation import activate as activate_language
-from django.utils.safestring import mark_safe
-from django.template import Template, Context, loader
-from django.db import models
-from django.db.models import get_models
-from django.db.models.fields.related import \
-    ForeignKey, OneToOneField, ManyToManyField, RelatedField
-
-try:
-    from django.db.models.fields.generic import GenericRelation
-except ImportError:
-    from django.contrib.contenttypes.generic import GenericRelation
-
-def parse_file_or_list(arg):
-    if not arg:
-        return []
-    if not ',' in arg and os.path.isfile(arg):
-        return [e.strip() for e in open(arg).readlines()]
-    return arg.split(',')
-
-
-def generate_dot(app_labels, **kwargs):
-    disable_fields = kwargs.get('disable_fields', False)
-    include_models = parse_file_or_list(kwargs.get('include_models', ""))
-    all_applications = kwargs.get('all_applications', False)
-    use_subgraph = kwargs.get('group_models', False)
-    verbose_names = kwargs.get('verbose_names', False)
-    inheritance = kwargs.get('inheritance', False)
-    language = kwargs.get('language', None)
-    if language is not None:
-        activate_language(language)
-    exclude_columns = parse_file_or_list(kwargs.get('exclude_columns', ""))
-    exclude_models = parse_file_or_list(kwargs.get('exclude_models', ""))
-
-    def skip_field(field):
-        if exclude_columns:
-            if verbose_names and field.verbose_name:
-                if field.verbose_name in exclude_columns:
-                    return True
-            if field.name in exclude_columns:
-                return True
-        return False
-
-
-
-
-    t = loader.get_template('django_extensions/graph_models/head.html')
-    c = Context({})
-    dot = t.render(c)
-
-    apps = []
-    if all_applications:
-        apps = models.get_apps()
-
-    for app_label in app_labels:
-        app = models.get_app(app_label)
-        if not app in apps:
-            apps.append(app)
-
-    graphs = []
-    for app in apps:
-        graph = Context({
-            'name': '"%s"' % app.__name__,
-            'app_name': "%s" % '.'.join(app.__name__.split('.')[:-1]),
-            'cluster_app_name': "cluster_%s" % app.__name__.replace(".", "_"),
-            'disable_fields': disable_fields,
-            'use_subgraph': use_subgraph,
-            'models': []
-        })
-
-        appmodels = get_models(app)
-        abstract_models = []
-        for appmodel in appmodels:
-            abstract_models = abstract_models + [abstract_model for abstract_model in appmodel.__bases__ if hasattr(abstract_model, '_meta') and abstract_model._meta.abstract]
-        abstract_models = list(set(abstract_models)) # remove duplicates
-        appmodels = abstract_models + appmodels
-        
-
-        for appmodel in appmodels:
-            appmodel_abstracts = [abstract_model.__name__ for abstract_model in appmodel.__bases__ if hasattr(abstract_model, '_meta') and abstract_model._meta.abstract]
-
-            # collect all attribs of abstract superclasses
-            def getBasesAbstractFields(c):
-                _abstract_fields = []
-                for e in c.__bases__:
-                    if hasattr(e, '_meta') and e._meta.abstract:
-                        _abstract_fields.extend(e._meta.fields)
-                        _abstract_fields.extend(getBasesAbstractFields(e))
-                return _abstract_fields
-            abstract_fields = getBasesAbstractFields(appmodel)
-
-            model = {
-                'app_name': appmodel.__module__.replace(".", "_"),
-                'name': appmodel.__name__,
-                'abstracts': appmodel_abstracts,
-                'fields': [],
-                'relations': []
-            }
-
-            # consider given model name ?
-            def consider(model_name):
-                if exclude_models and model_name in exclude_models:
-                    return False
-                return not include_models or model_name in include_models
-
-            if not consider(appmodel._meta.object_name):
-                continue
-
-            if verbose_names and appmodel._meta.verbose_name:
-                model['label'] = appmodel._meta.verbose_name
-            else:
-                model['label'] = model['name']
-
-            # model attributes
-            def add_attributes(field):
-                if verbose_names and field.verbose_name:
-                    label = field.verbose_name
-                else:
-                    label = field.name
-
-                t = type(field).__name__
-                if isinstance(field, (OneToOneField, ForeignKey)):
-                    t += " ({0})".format(field.rel.field_name)
-                # TODO: ManyToManyField, GenericRelation
-
-                model['fields'].append({
-                    'name': field.name,
-                    'label': label,
-                    'type': t,
-                    'blank': field.blank,
-                    'abstract': field in abstract_fields,
-                })
-
-            # Find all the real attributes. Relations are depicted as graph edges instead of attributes
-            attributes = [field for field in appmodel._meta.local_fields if not isinstance(field, RelatedField)]
-
-            # find primary key and print it first, ignoring implicit id if other pk exists
-            pk = appmodel._meta.pk
-            if not appmodel._meta.abstract and pk in attributes:
-                add_attributes(pk)
-            for field in attributes:
-                if skip_field(field):
-                    continue
-                if not field.primary_key:
-                    add_attributes(field)
-            
-            # FIXME: actually many_to_many fields aren't saved in this model's db table, so why should we add an attribute-line for them in the resulting graph?
-            #if appmodel._meta.many_to_many:
-            #    for field in appmodel._meta.many_to_many:
-            #        if skip_field(field):
-            #            continue
-            #        add_attributes(field)
-
-            # relations
-            def add_relation(field, extras=""):
-                if verbose_names and field.verbose_name:
-                    label = field.verbose_name
-                else:
-                    label = field.name
-                    
-                # show related field name
-                if hasattr(field, 'related_query_name'):
-                    label += ' (%s)' % field.related_query_name()
-
-                _rel = {
-                    'target_app': field.rel.to.__module__.replace('.', '_'),
-                    'target': field.rel.to.__name__,
-                    'type': type(field).__name__,
-                    'name': field.name,
-                    'label': label,
-                    'arrows': extras,
-                    'needs_node': True
-                }
-                if _rel not in model['relations'] and consider(_rel['target']):
-                    model['relations'].append(_rel)
-
-            for field in appmodel._meta.local_fields:
-                if field.attname.endswith('_ptr_id'): # excluding field redundant with inheritance relation
-                    continue
-                if field in abstract_fields: # excluding fields inherited from abstract classes. they too show as local_fields
-                    continue
-                if skip_field(field):
-                    continue
-                if isinstance(field, OneToOneField):
-                    add_relation(field, '[arrowhead=none, arrowtail=none]')
-                elif isinstance(field, ForeignKey):
-                    add_relation(field, '[arrowhead=none, arrowtail=dot]')
-
-            for field in appmodel._meta.local_many_to_many:
-                if skip_field(field):
-                    continue
-                if isinstance(field, ManyToManyField):
-                    if (getattr(field, 'creates_table', False) or  # django 1.1.
-                        (hasattr(field.rel.through, '_meta') and field.rel.through._meta.auto_created)):  # django 1.2
-                        add_relation(field, '[arrowhead=dot arrowtail=dot, dir=both]')
-                    elif isinstance(field, GenericRelation):
-                        add_relation(field, mark_safe('[style="dotted", arrowhead=normal, arrowtail=normal, dir=both]'))
-            
-            if inheritance:
-                # add inheritance arrows
-                for parent in appmodel.__bases__:
-                    if hasattr(parent, "_meta"): # parent is a model
-                        l = "multi-table"
-                        if parent._meta.abstract:
-                            l = "abstract"
-                        if appmodel._meta.proxy:
-                            l = "proxy"
-                        l += r"\ninheritance"
-                        _rel = {
-                            'target_app': parent.__module__.replace(".", "_"),
-                            'target': parent.__name__,
-                            'type': "inheritance",
-                            'name': "inheritance",
-                            'label': l,
-                            'arrows': '[arrowhead=empty, arrowtail=none]',
-                            'needs_node': True
-                        }
-                        # TODO: seems as if abstract models aren't part of models.getModels, which is why they are printed by this without any attributes.
-                        if _rel not in model['relations'] and consider(_rel['target']):
-                            model['relations'].append(_rel)
-            
-            graph['models'].append(model)
-        graphs.append(graph)
-
-    nodes = []
-    for graph in graphs:
-        nodes.extend([e['name'] for e in graph['models']])
-
-    for graph in graphs:
-        # don't draw duplication nodes because of relations
-        for model in graph['models']:
-            for relation in model['relations']:
-                if relation['target'] in nodes:
-                    relation['needs_node'] = False
-        # render templates
-        t = loader.get_template('django_extensions/graph_models/body.html')
-        dot += '\n' + t.render(graph)
-
-    for graph in graphs:
-        t = loader.get_template('django_extensions/graph_models/rel.html')
-        dot += '\n' + t.render(graph)
-
-
-    t = loader.get_template('django_extensions/graph_models/tail.html')
-    c = Context({})
-    dot += '\n' + t.render(c)
-    return dot
-
-def main():
-    try:
-        opts, args = getopt.getopt(sys.argv[1:], "hadgi:L:x:X:en",
-                    ["help", "all_applications", "disable_fields", "group_models", "include_models=", "inheritance", "verbose_names", "language=", "exclude_columns=", "exclude_models="])
-    except getopt.GetoptError, error:
-        print __doc__
-        sys.exit(error)
-
-    kwargs = {}
-    for opt, arg in opts:
-        if opt in ("-h", "--help"):
-            print __doc__
-            sys.exit()
-        if opt in ("-a", "--all_applications"):
-            kwargs['all_applications'] = True
-        if opt in ("-d", "--disable_fields"):
-            kwargs['disable_fields'] = True
-        if opt in ("-g", "--group_models"):
-            kwargs['group_models'] = True
-        if opt in ("-i", "--include_models"):
-            kwargs['include_models'] = arg
-        if opt in ("-e", "--inheritance"):
-            kwargs['inheritance'] = True
-        if opt in ("-n", "--verbose-names"):
-            kwargs['verbose_names'] = True
-        if opt in ("-L", "--language"):
-            kwargs['language'] = arg
-        if opt in ("-x", "--exclude_columns"):
-            kwargs['exclude_columns'] = arg
-        if opt in ("-X", "--exclude_models"):
-            kwargs['exclude_models'] = arg
-
-    if not args and not kwargs.get('all_applications', False):
-        print __doc__
-        sys.exit()
-
-    print generate_dot(args, **kwargs)
-
-if __name__ == "__main__":
-    main()
diff --git a/example/sandbox/robots.txt b/example/sandbox/robots.txt
deleted file mode 100644 (file)
index 5ac75eb..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-User-agent: *
-Disallow: *.mp3$
-Disallow: */WIDTHxHEIGHT/
-Disallow: */xml/
diff --git a/example/sandbox/settings.py b/example/sandbox/settings.py
deleted file mode 100644 (file)
index 4f469f5..0000000
+++ /dev/null
@@ -1,259 +0,0 @@
-# -*- coding: utf-8 -*-
-# Django settings for sandbox project.
-
-import os, sys
-from django.core.urlresolvers import reverse_lazy, reverse
-
-sys.dont_write_bytecode = True
-
-BASE_DIR = os.path.dirname(__file__)
-
-DEBUG = True
-TEMPLATE_DEBUG = DEBUG
-
-ALLOWED_HOSTS = ['*']
-
-ADMINS = (
-    ('Guillaume Pellerin', 'yomguy@parisson.com'),
-)
-
-MANAGERS = ADMINS
-
-DATABASES = {
-    'default': {
-        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
-        'NAME': 'sandbox.sql',                      # Or path to database file if using sqlite3.
-        'USER': '',                      # 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'
-
-LANGUAGES = [ ('fr', 'French'),
-              ('en', 'English'),
-              ('de', 'German'),
-              ('zh_CN', 'Simplified Chinese'),
-              ('ar_TN', 'Arabic'),
-]
-
-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
-
-# If you set this to False, Django will not format dates, numbers and
-# calendars according to the current locale
-USE_L10N = True
-
-# Absolute path to the directory that holds media.
-# Example: "/home/media/media.lawrence.com/"
-MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
-
-if not os.path.exists(MEDIA_ROOT):
-    os.mkdir(MEDIA_ROOT)
-
-# URL that handles the media served from MEDIA_ROOT. Make sure to use a
-# trailing slash if there is a path component (optional in other cases).
-# Examples: "http://media.lawrence.com", "http://example.com/media/"
-MEDIA_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 = ''
-
-# URL prefix for static files.
-# Example: "http://media.lawrence.com/static/"
-STATIC_URL = '/static/'
-
-# Additional locations of static files
-STATICFILES_DIRS = (
-# 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',
-)
-# Make this unique, and don't share it with anybody.
-SECRET_KEY = 'a8l7%06wr2k+3=%#*#@#rvop2mmzko)44%7k(zx%lls^ihm9^5'
-
-# List of callables that know how to import templates from various sources.
-TEMPLATE_LOADERS = (
-    'django.template.loaders.filesystem.Loader',
-    'django.template.loaders.app_directories.Loader',
-#     'django.template.loaders.eggs.Loader',
-)
-
-
-MIDDLEWARE_CLASSES = (
-    'django.middleware.common.CommonMiddleware',
-    'django.contrib.sessions.middleware.SessionMiddleware',
-    'django.middleware.csrf.CsrfViewMiddleware',
-    'django.contrib.auth.middleware.AuthenticationMiddleware',
-    'django.contrib.messages.middleware.MessageMiddleware',
-    'django.middleware.locale.LocaleMiddleware',
-    # 'pagination.middleware.PaginationMiddleware',
-)
-
-ROOT_URLCONF = 'urls'
-
-TEMPLATE_DIRS = (
-    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
-    # Always use forward slashes, even on Windows.
-    # Don't forget to use absolute paths, not relative paths.
-)
-
-INSTALLED_APPS = (
-    'django.contrib.auth',
-    'django.contrib.contenttypes',
-    'django.contrib.sessions',
-    'django.contrib.sites',
-    'django.contrib.messages',
-    'suit',
-    'django.contrib.admin',
-    'django.contrib.staticfiles',
-    'django_extensions',
-    'telemeta',
-    'timeside.player',
-    'jsonrpc',
-    'south',
-    'sorl.thumbnail',
-    'timezones',
-    'jqchat',
-    'ipauth',
-    'extra_views',
-    'debug_toolbar',
-    'bootstrap3',
-    'bootstrap_pagination',
-    'googletools',
-    'registration',
-)
-
-TEMPLATE_CONTEXT_PROCESSORS = (
-    'django.core.context_processors.request',
-    'django.contrib.auth.context_processors.auth',
-    "django.core.context_processors.i18n",
-    "django.core.context_processors.media",
-    'django.core.context_processors.static',
-    'django.contrib.messages.context_processors.messages',
-)
-
-
-AUTHENTICATION_BACKENDS = (
-    'django.contrib.auth.backends.ModelBackend',
-    'ipauth.backend.RangeBackend',
-)
-
-SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies"
-
-TELEMETA_ORGANIZATION = 'Parisson'
-TELEMETA_SUBJECTS = ('test', 'telemeta', 'sandbox')
-TELEMETA_DESCRIPTION = "Telemeta TEST sandbox"
-TELEMETA_LOGO = STATIC_URL + 'telemeta/images/logo_telemeta_2.png'
-
-TELEMETA_GMAP_KEY = 'ABQIAAAArg7eSfnfTkBRma8glnGrlxRVbMrhnNNvToCbZQtWdaMbZTA_3RRGObu5PDoiBImgalVnnLU2yN4RMA'
-
-TELEMETA_CACHE_DIR = os.path.join(MEDIA_ROOT, 'cache')
-TELEMETA_EXPORT_CACHE_DIR = os.path.join(MEDIA_ROOT, 'export')
-TELEMETA_DATA_CACHE_DIR = os.path.join(TELEMETA_CACHE_DIR, 'data')
-
-TELEMETA_DOWNLOAD_ENABLED = True
-TELEMETA_STREAMING_FORMATS = ('mp3', 'ogg')
-TELEMETA_DOWNLOAD_FORMATS = ('wav', 'mp3', 'ogg', 'flac')
-TELEMETA_PUBLIC_ACCESS_PERIOD = 51
-
-TELEMETA_STRICT_CODE = False
-
-AUTH_PROFILE_MODULE = 'telemeta.userprofile'
-SESSION_EXPIRE_AT_BROWSER_CLOSE = False
-
-LOGIN_URL = '/login/'
-LOGIN_REDIRECT_URL = '/desk/lists/'
-
-EMAIL_HOST = 'localhost'
-DEFAULT_FROM_EMAIL = 'webmaster@parisson.com'
-
-TIMESIDE_DEFAULT_GRAPHER_ID = 'waveform_centroid'
-TIMESIDE_DEFAULT_WAVEFORM_SIZES = ['346x130', '640x130']
-TIMESIDE_AUTO_ZOOM = False
-
-# Settings for django-bootstrap3
-BOOTSTRAP3 = {
-    'set_required': True,
-    'set_placeholder': False,
-    'error_css_class': 'has-error',
-    'required_css_class': 'has-warning',
-    'javascript_in_head': True,
-}
-
-PAGINATION_SETTINGS = {
-    'PAGE_RANGE_DISPLAYED': 10,
-    'MARGIN_PAGES_DISPLAYED': 2,
-}
-
-DEBUG_TOOLBAR_PATCH_SETTINGS = False
-DEBUG_TOOLBAR_PANELS = [
-    'debug_toolbar.panels.versions.VersionsPanel',
-    'debug_toolbar.panels.timer.TimerPanel',
-    'debug_toolbar.panels.settings.SettingsPanel',
-    'debug_toolbar.panels.headers.HeadersPanel',
-    'debug_toolbar.panels.request.RequestPanel',
-    'debug_toolbar.panels.sql.SQLPanel',
-    'debug_toolbar.panels.staticfiles.StaticFilesPanel',
-    'debug_toolbar.panels.templates.TemplatesPanel',
-    'debug_toolbar.panels.cache.CachePanel',
-    'debug_toolbar.panels.signals.SignalsPanel',
-    'debug_toolbar.panels.logging.LoggingPanel',
-    'debug_toolbar.panels.redirects.RedirectsPanel',
-]
-
-SUIT_CONFIG = {
-    'ADMIN_NAME': 'Telemeta Admin'
-}
-
-
-# LOG_DIR = os.path.join(BASE_DIR, 'log')
-
-# if not os.path.exists(LOG_DIR):
-#     os.mkdir(LOG_DIR)
-
-# LOGGING = {
-#     'version': 1,
-#     'disable_existing_loggers': False,
-#     'handlers': {
-#         'file': {
-#             'level': 'DEBUG',
-#             'class': 'logging.FileHandler',
-#             'filename': os.path.join(LOG_DIR, 'debug.log')
-#         },
-#     },
-#     'loggers': {
-#         'django.request': {
-#             'handlers': ['file'],
-#             'level': 'DEBUG',
-#             'propagate': True,
-#         },
-#     },
-# }
diff --git a/example/sandbox/update_schema.sh b/example/sandbox/update_schema.sh
deleted file mode 100755 (executable)
index 31c658a..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-#!/bin/sh
-
-./manage.py schemamigration telemeta --auto
-./manage.py migrate telemeta
-
diff --git a/example/sandbox/urls.py b/example/sandbox/urls.py
deleted file mode 100644 (file)
index 376539b..0000000
+++ /dev/null
@@ -1,35 +0,0 @@
-# -*- coding: utf-8 -*-
-from django.conf.urls import patterns, url, include
-from django.http import HttpResponse
-
-# Uncomment the next two lines to enable the admin:
-from django.contrib import admin
-admin.autodiscover()
-
-js_info_dict = {
-    'packages': ('telemeta',),
-}
-
-robots_file = open('robots.txt', 'r')
-
-urlpatterns = patterns('',
-    # Example:
-    # (r'^sandbox/', include('sandbox.foo.urls')),
-
-    # Uncomment the admin/doc line below and add 'django.contrib.admindocs'
-    # to INSTALLED_APPS to enable admin documentation:
-    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),
-
-    # Uncomment the next line to enable the admin:
-    (r'^admin/django/', include(admin.site.urls)),
-    #(r'^grappelli/', include('grappelli.urls')), # grappelli URLS
-
-    # Telemeta
-    (r'^', include('telemeta.urls')),
-
-    # Languages
-    (r'^i18n/', include('django.conf.urls.i18n')),
-    (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict),
-    (r'^robots\.txt$', lambda r: HttpResponse(robots_file.read(), mimetype="text/plain")),
-
-    )
diff --git a/example/sandbox/wsgi.py b/example/sandbox/wsgi.py
deleted file mode 100644 (file)
index c3642fe..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-#!/usr/bin/python2.5
-# -*- coding: utf-8 -*-
-
-import os
-import sys
-
-here = os.path.dirname(__file__)
-sys.path.append(here)
-
-os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
-
-import django.core.handlers.wsgi
-application = django.core.handlers.wsgi.WSGIHandler()
-
diff --git a/examples/deploy/apache-app.conf b/examples/deploy/apache-app.conf
new file mode 100644 (file)
index 0000000..e0eecec
--- /dev/null
@@ -0,0 +1,44 @@
+<VirtualHost *:80>
+       ServerAdmin webmaster@localhost
+        ServerName telemeta.wm22.parisson.org
+
+        LogLevel warn
+       ErrorLog ${APACHE_LOG_DIR}/error-telemeta.log
+       # Possible values include: debug, info, notice, warn, error, crit,
+       # alert, emerg.
+       CustomLog ${APACHE_LOG_DIR}/access-telemeta.log combined
+
+       Alias /media/ /home/dev/telemeta/examples/sandbox/media/
+
+        <Directory /home/dev/telemeta/examples/sandbox/>
+         Order deny,allow
+         Allow from all
+        </Directory>
+
+        WSGIDaemonProcess telemeta_test user=www-data group=www-data threads=12 processes=4 maximum-requests=1000 deadlock-timeout=300
+        WSGIProcessGroup telemeta_test
+        WSGIApplicationGroup %{GLOBAL}
+        WSGIScriptAlias / /home/dev/telemeta/examples/sandbox/wsgi.py
+
+
+#<Location "/media">
+#    SetHandler None
+#</Location>
+
+Alias /favicon.ico /home/dev/telemeta/telemeta/static/telemeta/images/favicon.ico
+
+<LocationMatch "\.(ico|txt)$">
+    SetHandler None
+</LocationMatch>
+
+DocumentRoot /var/www/
+Alias /static/ /var/www/telemeta/
+
+        <Directory /var/www/>
+                Options Indexes FollowSymLinks MultiViews
+                AllowOverride None
+                Order allow,deny
+                allow from all
+        </Directory>
+
+</VirtualHost>
diff --git a/examples/deploy/apt-app.list b/examples/deploy/apt-app.list
new file mode 100644 (file)
index 0000000..81a807a
--- /dev/null
@@ -0,0 +1,12 @@
+deb http://ftp.debian.org/debian/ wheezy-backports main contrib non-free
+deb-src http://ftp.debian.org/debian/ wheezy-backports main contrib non-free
+
+deb http://security.debian.org/ wheezy/updates main
+deb-src http://security.debian.org/ wheezy/updates main
+
+deb http://www.deb-multimedia.org wheezy main non-free
+deb http://www.deb-multimedia.org wheezy-backports main
+
+deb http://debian.parisson.com/debian/ wheezy main
+deb-src http://debian.parisson.com/debian wheezy main
+
diff --git a/examples/deploy/nginx-app.conf b/examples/deploy/nginx-app.conf
new file mode 100644 (file)
index 0000000..f1e56db
--- /dev/null
@@ -0,0 +1,30 @@
+server_tokens off;
+
+server {
+       listen 80;
+       server_name nginx;
+       charset utf-8;
+
+       access_log /var/log/nginx/app-access.log;
+       error_log /var/log/nginx/app-error.log;
+
+       # max upload size
+       client_max_body_size 75M; # adjust to taste
+
+       # Django media
+       location /media {
+                       alias /home/telemeta/media; # your Django project's media files - amend as required
+                autoindex on;
+       }
+       # Django static
+       location /static {
+               alias /var/www/static; # your Django project's static files - amend as required
+               autoindex on;
+       }
+
+       location / {
+            uwsgi_pass app:8000;
+            include /etc/nginx/uwsgi_params;
+       }
+}
+
diff --git a/examples/deploy/start_app.sh b/examples/deploy/start_app.sh
new file mode 100644 (file)
index 0000000..2b5deb5
--- /dev/null
@@ -0,0 +1,23 @@
+#!/bin/sh
+
+# paths
+app_dir='/opt/Telemeta/'
+sandbox_dir='/home/telemeta/'
+manage=$sandbox_dir'manage.py'
+wsgi=$sandbox_dir'wsgi.py'
+app_static_dir=$app_dir'telemeta/static/'
+
+# django init
+python $manage syncdb --noinput
+python $manage migrate --noinput
+python $manage collectstatic --noinput
+python $manage telemeta-create-admin-user
+
+# static files auto update
+pip install watchdog
+
+watchmedo shell-command --patterns="*.js;*.css" --recursive \
+    --command='python '$manage' collectstatic --noinput' $app_static_dir &
+
+# app start
+uwsgi --socket :8000 --wsgi-file $wsgi --chdir $sandbox_dir --master --processes 4 --threads 2 --py-autoreload 3
diff --git a/examples/fixtures/original_format.txt b/examples/fixtures/original_format.txt
new file mode 100644 (file)
index 0000000..1a5bc13
--- /dev/null
@@ -0,0 +1,38 @@
+Bande magnétique 6,25mm (1/4')
+Bande magnétique mini-Nagra 3,81mm 
+Cassette analogique 
+Cassette analogique Type I (Fe)
+Cassette analogique Type II (CrO2)
+Cassette analogique Type IV (Metal)
+Cylindre de cire à gravure directe
+Cylindre de cire édité
+Fil magnétique
+Disque à gravure directe
+Disque 78 tours
+Disque 45 tours
+Disque 33 tours
+Cassette audionumérique PCM F1 Betamax
+Cassette audionumérique PCM 1610/1630 U-Matic
+Cassette audionumérique DAT
+Cassette audionumérique DAT 48 kHz
+Cassette audionumérique DAT 44,1 kHz
+Cassette audionumérique DAT 32 kHz
+Bande magnétique audionumérique 1/4" (DASH, ProDigi, EIAJ-C, Nagra-D)
+Mini-Disc
+CD-A (Audio édité)
+CD-R Audio
+CD-RW Audio
+CD-R Data
+CD-ROM édité
+CD-RW Data
+DVD-R Data
+DVD+R Data
+DVD-ROM édité
+DVD-RW Data
+DVD+RW Data
+BD-ROM édité (Blu-ray)
+BD-R (Blu-ray enregistrable)
+BD-RE (Blu-ray réinscriptible)
+Disque dur (HDD)
+Carte mémoire
+SSD
diff --git a/examples/sandbox/__init__.py b/examples/sandbox/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/examples/sandbox/diag.sh b/examples/sandbox/diag.sh
new file mode 100755 (executable)
index 0000000..5f6c1e5
--- /dev/null
@@ -0,0 +1,12 @@
+#!/bin/sh
+
+app="telemeta"
+dir="../../doc/devel"
+
+python modelviz.py -a > $dir/$app-all.dot
+python modelviz.py $app > $dir/$app.dot
+
+dot $dir/$app-all.dot -Tpdf -o $dir/$app-all.pdf
+dot $dir/$app.dot -Tpdf -o $dir/$app.pdf
+
+rsync -a $dir/ doc.parisson.com:/var/www/files/doc/$app/diagram/
diff --git a/examples/sandbox/manage.py b/examples/sandbox/manage.py
new file mode 100755 (executable)
index 0000000..c632a8a
--- /dev/null
@@ -0,0 +1,9 @@
+#!/usr/bin/env python
+import os, sys
+
+if __name__ == "__main__":
+    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
+
+    from django.core.management import execute_from_command_line
+
+    execute_from_command_line(sys.argv)
diff --git a/examples/sandbox/modelviz.py b/examples/sandbox/modelviz.py
new file mode 100644 (file)
index 0000000..24af062
--- /dev/null
@@ -0,0 +1,359 @@
+#!/usr/bin/env python
+
+"""Django model to DOT (Graphviz) converter
+by Antonio Cavedoni <antonio@cavedoni.org>
+
+Make sure your DJANGO_SETTINGS_MODULE is set to your project or
+place this script in the same directory of the project and call
+the script like this:
+
+$ python modelviz.py [-h] [-a] [-d] [-g] [-n] [-L <language>] [-i <model_names>] <app_label> ... <app_label> > <filename>.dot
+$ dot <filename>.dot -Tpng -o <filename>.png
+
+options:
+    -h, --help
+    show this help message and exit.
+
+    -a, --all_applications
+    show models from all applications.
+
+    -d, --disable_fields
+    don't show the class member fields.
+
+    -g, --group_models
+    draw an enclosing box around models from the same app.
+
+    -i, --include_models=User,Person,Car
+    only include selected models in graph.
+
+    -n, --verbose_names
+    use verbose_name for field and models.
+
+    -L, --language
+    specify language used for verrbose_name localization
+
+    -x, --exclude_columns
+    exclude specific column(s) from the graph.
+
+    -X, --exclude_models
+    exclude specific model(s) from the graph.
+    
+    -e, --inheritance
+    show inheritance arrows.
+"""
+__version__ = "0.9"
+__svnid__ = "$Id$"
+__license__ = "Python"
+__author__ = "Antonio Cavedoni <http://cavedoni.com/>"
+__contributors__ = [
+   "Stefano J. Attardi <http://attardi.org/>",
+   "limodou <http://www.donews.net/limodou/>",
+   "Carlo C8E Miron",
+   "Andre Campos <cahenan@gmail.com>",
+   "Justin Findlay <jfindlay@gmail.com>",
+   "Alexander Houben <alexander@houben.ch>",
+   "Bas van Oostveen <v.oostveen@gmail.com>",
+   "Joern Hees <gitdev@joernhees.de>"
+]
+
+import os
+import sys
+import getopt
+
+from django.core.management import setup_environ
+
+try:
+    import settings
+except ImportError:
+    pass
+else:
+    setup_environ(settings)
+
+from django.utils.translation import activate as activate_language
+from django.utils.safestring import mark_safe
+from django.template import Template, Context, loader
+from django.db import models
+from django.db.models import get_models
+from django.db.models.fields.related import \
+    ForeignKey, OneToOneField, ManyToManyField, RelatedField
+
+try:
+    from django.db.models.fields.generic import GenericRelation
+except ImportError:
+    from django.contrib.contenttypes.generic import GenericRelation
+
+def parse_file_or_list(arg):
+    if not arg:
+        return []
+    if not ',' in arg and os.path.isfile(arg):
+        return [e.strip() for e in open(arg).readlines()]
+    return arg.split(',')
+
+
+def generate_dot(app_labels, **kwargs):
+    disable_fields = kwargs.get('disable_fields', False)
+    include_models = parse_file_or_list(kwargs.get('include_models', ""))
+    all_applications = kwargs.get('all_applications', False)
+    use_subgraph = kwargs.get('group_models', False)
+    verbose_names = kwargs.get('verbose_names', False)
+    inheritance = kwargs.get('inheritance', False)
+    language = kwargs.get('language', None)
+    if language is not None:
+        activate_language(language)
+    exclude_columns = parse_file_or_list(kwargs.get('exclude_columns', ""))
+    exclude_models = parse_file_or_list(kwargs.get('exclude_models', ""))
+
+    def skip_field(field):
+        if exclude_columns:
+            if verbose_names and field.verbose_name:
+                if field.verbose_name in exclude_columns:
+                    return True
+            if field.name in exclude_columns:
+                return True
+        return False
+
+
+
+
+    t = loader.get_template('django_extensions/graph_models/head.html')
+    c = Context({})
+    dot = t.render(c)
+
+    apps = []
+    if all_applications:
+        apps = models.get_apps()
+
+    for app_label in app_labels:
+        app = models.get_app(app_label)
+        if not app in apps:
+            apps.append(app)
+
+    graphs = []
+    for app in apps:
+        graph = Context({
+            'name': '"%s"' % app.__name__,
+            'app_name': "%s" % '.'.join(app.__name__.split('.')[:-1]),
+            'cluster_app_name': "cluster_%s" % app.__name__.replace(".", "_"),
+            'disable_fields': disable_fields,
+            'use_subgraph': use_subgraph,
+            'models': []
+        })
+
+        appmodels = get_models(app)
+        abstract_models = []
+        for appmodel in appmodels:
+            abstract_models = abstract_models + [abstract_model for abstract_model in appmodel.__bases__ if hasattr(abstract_model, '_meta') and abstract_model._meta.abstract]
+        abstract_models = list(set(abstract_models)) # remove duplicates
+        appmodels = abstract_models + appmodels
+        
+
+        for appmodel in appmodels:
+            appmodel_abstracts = [abstract_model.__name__ for abstract_model in appmodel.__bases__ if hasattr(abstract_model, '_meta') and abstract_model._meta.abstract]
+
+            # collect all attribs of abstract superclasses
+            def getBasesAbstractFields(c):
+                _abstract_fields = []
+                for e in c.__bases__:
+                    if hasattr(e, '_meta') and e._meta.abstract:
+                        _abstract_fields.extend(e._meta.fields)
+                        _abstract_fields.extend(getBasesAbstractFields(e))
+                return _abstract_fields
+            abstract_fields = getBasesAbstractFields(appmodel)
+
+            model = {
+                'app_name': appmodel.__module__.replace(".", "_"),
+                'name': appmodel.__name__,
+                'abstracts': appmodel_abstracts,
+                'fields': [],
+                'relations': []
+            }
+
+            # consider given model name ?
+            def consider(model_name):
+                if exclude_models and model_name in exclude_models:
+                    return False
+                return not include_models or model_name in include_models
+
+            if not consider(appmodel._meta.object_name):
+                continue
+
+            if verbose_names and appmodel._meta.verbose_name:
+                model['label'] = appmodel._meta.verbose_name
+            else:
+                model['label'] = model['name']
+
+            # model attributes
+            def add_attributes(field):
+                if verbose_names and field.verbose_name:
+                    label = field.verbose_name
+                else:
+                    label = field.name
+
+                t = type(field).__name__
+                if isinstance(field, (OneToOneField, ForeignKey)):
+                    t += " ({0})".format(field.rel.field_name)
+                # TODO: ManyToManyField, GenericRelation
+
+                model['fields'].append({
+                    'name': field.name,
+                    'label': label,
+                    'type': t,
+                    'blank': field.blank,
+                    'abstract': field in abstract_fields,
+                })
+
+            # Find all the real attributes. Relations are depicted as graph edges instead of attributes
+            attributes = [field for field in appmodel._meta.local_fields if not isinstance(field, RelatedField)]
+
+            # find primary key and print it first, ignoring implicit id if other pk exists
+            pk = appmodel._meta.pk
+            if not appmodel._meta.abstract and pk in attributes:
+                add_attributes(pk)
+            for field in attributes:
+                if skip_field(field):
+                    continue
+                if not field.primary_key:
+                    add_attributes(field)
+            
+            # FIXME: actually many_to_many fields aren't saved in this model's db table, so why should we add an attribute-line for them in the resulting graph?
+            #if appmodel._meta.many_to_many:
+            #    for field in appmodel._meta.many_to_many:
+            #        if skip_field(field):
+            #            continue
+            #        add_attributes(field)
+
+            # relations
+            def add_relation(field, extras=""):
+                if verbose_names and field.verbose_name:
+                    label = field.verbose_name
+                else:
+                    label = field.name
+                    
+                # show related field name
+                if hasattr(field, 'related_query_name'):
+                    label += ' (%s)' % field.related_query_name()
+
+                _rel = {
+                    'target_app': field.rel.to.__module__.replace('.', '_'),
+                    'target': field.rel.to.__name__,
+                    'type': type(field).__name__,
+                    'name': field.name,
+                    'label': label,
+                    'arrows': extras,
+                    'needs_node': True
+                }
+                if _rel not in model['relations'] and consider(_rel['target']):
+                    model['relations'].append(_rel)
+
+            for field in appmodel._meta.local_fields:
+                if field.attname.endswith('_ptr_id'): # excluding field redundant with inheritance relation
+                    continue
+                if field in abstract_fields: # excluding fields inherited from abstract classes. they too show as local_fields
+                    continue
+                if skip_field(field):
+                    continue
+                if isinstance(field, OneToOneField):
+                    add_relation(field, '[arrowhead=none, arrowtail=none]')
+                elif isinstance(field, ForeignKey):
+                    add_relation(field, '[arrowhead=none, arrowtail=dot]')
+
+            for field in appmodel._meta.local_many_to_many:
+                if skip_field(field):
+                    continue
+                if isinstance(field, ManyToManyField):
+                    if (getattr(field, 'creates_table', False) or  # django 1.1.
+                        (hasattr(field.rel.through, '_meta') and field.rel.through._meta.auto_created)):  # django 1.2
+                        add_relation(field, '[arrowhead=dot arrowtail=dot, dir=both]')
+                    elif isinstance(field, GenericRelation):
+                        add_relation(field, mark_safe('[style="dotted", arrowhead=normal, arrowtail=normal, dir=both]'))
+            
+            if inheritance:
+                # add inheritance arrows
+                for parent in appmodel.__bases__:
+                    if hasattr(parent, "_meta"): # parent is a model
+                        l = "multi-table"
+                        if parent._meta.abstract:
+                            l = "abstract"
+                        if appmodel._meta.proxy:
+                            l = "proxy"
+                        l += r"\ninheritance"
+                        _rel = {
+                            'target_app': parent.__module__.replace(".", "_"),
+                            'target': parent.__name__,
+                            'type': "inheritance",
+                            'name': "inheritance",
+                            'label': l,
+                            'arrows': '[arrowhead=empty, arrowtail=none]',
+                            'needs_node': True
+                        }
+                        # TODO: seems as if abstract models aren't part of models.getModels, which is why they are printed by this without any attributes.
+                        if _rel not in model['relations'] and consider(_rel['target']):
+                            model['relations'].append(_rel)
+            
+            graph['models'].append(model)
+        graphs.append(graph)
+
+    nodes = []
+    for graph in graphs:
+        nodes.extend([e['name'] for e in graph['models']])
+
+    for graph in graphs:
+        # don't draw duplication nodes because of relations
+        for model in graph['models']:
+            for relation in model['relations']:
+                if relation['target'] in nodes:
+                    relation['needs_node'] = False
+        # render templates
+        t = loader.get_template('django_extensions/graph_models/body.html')
+        dot += '\n' + t.render(graph)
+
+    for graph in graphs:
+        t = loader.get_template('django_extensions/graph_models/rel.html')
+        dot += '\n' + t.render(graph)
+
+
+    t = loader.get_template('django_extensions/graph_models/tail.html')
+    c = Context({})
+    dot += '\n' + t.render(c)
+    return dot
+
+def main():
+    try:
+        opts, args = getopt.getopt(sys.argv[1:], "hadgi:L:x:X:en",
+                    ["help", "all_applications", "disable_fields", "group_models", "include_models=", "inheritance", "verbose_names", "language=", "exclude_columns=", "exclude_models="])
+    except getopt.GetoptError, error:
+        print __doc__
+        sys.exit(error)
+
+    kwargs = {}
+    for opt, arg in opts:
+        if opt in ("-h", "--help"):
+            print __doc__
+            sys.exit()
+        if opt in ("-a", "--all_applications"):
+            kwargs['all_applications'] = True
+        if opt in ("-d", "--disable_fields"):
+            kwargs['disable_fields'] = True
+        if opt in ("-g", "--group_models"):
+            kwargs['group_models'] = True
+        if opt in ("-i", "--include_models"):
+            kwargs['include_models'] = arg
+        if opt in ("-e", "--inheritance"):
+            kwargs['inheritance'] = True
+        if opt in ("-n", "--verbose-names"):
+            kwargs['verbose_names'] = True
+        if opt in ("-L", "--language"):
+            kwargs['language'] = arg
+        if opt in ("-x", "--exclude_columns"):
+            kwargs['exclude_columns'] = arg
+        if opt in ("-X", "--exclude_models"):
+            kwargs['exclude_models'] = arg
+
+    if not args and not kwargs.get('all_applications', False):
+        print __doc__
+        sys.exit()
+
+    print generate_dot(args, **kwargs)
+
+if __name__ == "__main__":
+    main()
diff --git a/examples/sandbox/robots.txt b/examples/sandbox/robots.txt
new file mode 100644 (file)
index 0000000..5ac75eb
--- /dev/null
@@ -0,0 +1,4 @@
+User-agent: *
+Disallow: *.mp3$
+Disallow: */WIDTHxHEIGHT/
+Disallow: */xml/
diff --git a/examples/sandbox/settings.py b/examples/sandbox/settings.py
new file mode 100644 (file)
index 0000000..9ce029c
--- /dev/null
@@ -0,0 +1,260 @@
+# -*- coding: utf-8 -*-
+# Django settings for sandbox project.
+
+import os, sys
+from django.core.urlresolvers import reverse_lazy, reverse
+
+sys.dont_write_bytecode = True
+
+DEBUG = True
+TEMPLATE_DEBUG = DEBUG
+
+ALLOWED_HOSTS = ['*']
+
+ADMINS = (
+    ('Guillaume Pellerin', 'yomguy@parisson.com'),
+)
+
+MANAGERS = ADMINS
+
+# Full filesystem path to the project.
+PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
+
+DATABASES = {
+    'default': {
+        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
+        'NAME': 'sandbox.sql',                      # Or path to database file if using sqlite3.
+        'USER': '',                      # 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'
+
+LANGUAGES = [ ('fr', 'French'),
+              ('en', 'English'),
+              ('de', 'German'),
+              ('zh_CN', 'Simplified Chinese'),
+              ('ar_TN', 'Arabic'),
+]
+
+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
+
+# If you set this to False, Django will not format dates, numbers and
+# calendars according to the current locale
+USE_L10N = True
+
+# Absolute path to the directory that holds media.
+# Example: "/home/media/media.lawrence.com/"
+MEDIA_ROOT = PROJECT_ROOT + '/media/'
+
+if not os.path.exists(MEDIA_ROOT):
+    os.mkdir(MEDIA_ROOT)
+
+# URL that handles the media served from MEDIA_ROOT. Make sure to use a
+# trailing slash if there is a path component (optional in other cases).
+# Examples: "http://media.lawrence.com", "http://example.com/media/"
+MEDIA_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 = '/var/www/static'
+
+# URL prefix for static files.
+# Example: "http://media.lawrence.com/static/"
+STATIC_URL = '/static/'
+
+# Additional locations of static files
+STATICFILES_DIRS = (
+# 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',
+)
+# Make this unique, and don't share it with anybody.
+SECRET_KEY = 'a8l7%06wr2k+3=%#*#@#rvop2mmzko)44%7k(zx%lls^ihm9^5'
+
+# List of callables that know how to import templates from various sources.
+TEMPLATE_LOADERS = (
+    'django.template.loaders.filesystem.Loader',
+    'django.template.loaders.app_directories.Loader',
+#     'django.template.loaders.eggs.Loader',
+)
+
+
+MIDDLEWARE_CLASSES = (
+    'django.middleware.common.CommonMiddleware',
+    'django.contrib.sessions.middleware.SessionMiddleware',
+    'django.middleware.csrf.CsrfViewMiddleware',
+    'django.contrib.auth.middleware.AuthenticationMiddleware',
+    'django.contrib.messages.middleware.MessageMiddleware',
+    'django.middleware.locale.LocaleMiddleware',
+    # 'pagination.middleware.PaginationMiddleware',
+)
+
+ROOT_URLCONF = 'urls'
+
+TEMPLATE_DIRS = (
+    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
+    # Always use forward slashes, even on Windows.
+    # Don't forget to use absolute paths, not relative paths.
+)
+
+INSTALLED_APPS = (
+    'django.contrib.auth',
+    'django.contrib.contenttypes',
+    'django.contrib.sessions',
+    'django.contrib.sites',
+    'django.contrib.messages',
+    'suit',
+    'django.contrib.admin',
+    'django.contrib.staticfiles',
+    'django_extensions',
+    'telemeta',
+    'timeside.player',
+    'jsonrpc',
+    'south',
+    'sorl.thumbnail',
+    'timezones',
+    'jqchat',
+    'ipauth',
+    'extra_views',
+    'debug_toolbar',
+    'bootstrap3',
+    'bootstrap_pagination',
+    'googletools',
+    'registration',
+)
+
+TEMPLATE_CONTEXT_PROCESSORS = (
+    'django.core.context_processors.request',
+    'django.contrib.auth.context_processors.auth',
+    "django.core.context_processors.i18n",
+    "django.core.context_processors.media",
+    'django.core.context_processors.static',
+    'django.contrib.messages.context_processors.messages',
+)
+
+
+AUTHENTICATION_BACKENDS = (
+    'django.contrib.auth.backends.ModelBackend',
+    'ipauth.backend.RangeBackend',
+)
+
+SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies"
+
+TELEMETA_ORGANIZATION = 'Parisson'
+TELEMETA_SUBJECTS = ('test', 'telemeta', 'sandbox')
+TELEMETA_DESCRIPTION = "Telemeta TEST sandbox"
+TELEMETA_LOGO = STATIC_URL + 'telemeta/images/logo_telemeta_2.png'
+
+TELEMETA_GMAP_KEY = 'ABQIAAAArg7eSfnfTkBRma8glnGrlxRVbMrhnNNvToCbZQtWdaMbZTA_3RRGObu5PDoiBImgalVnnLU2yN4RMA'
+
+TELEMETA_CACHE_DIR = os.path.join(MEDIA_ROOT, 'cache')
+TELEMETA_EXPORT_CACHE_DIR = os.path.join(MEDIA_ROOT, 'export')
+TELEMETA_DATA_CACHE_DIR = os.path.join(TELEMETA_CACHE_DIR, 'data')
+
+TELEMETA_DOWNLOAD_ENABLED = True
+TELEMETA_STREAMING_FORMATS = ('mp3', 'ogg')
+TELEMETA_DOWNLOAD_FORMATS = ('wav', 'mp3', 'ogg', 'flac')
+TELEMETA_PUBLIC_ACCESS_PERIOD = 51
+
+TELEMETA_STRICT_CODE = False
+
+AUTH_PROFILE_MODULE = 'telemeta.userprofile'
+SESSION_EXPIRE_AT_BROWSER_CLOSE = False
+
+LOGIN_URL = '/login/'
+LOGIN_REDIRECT_URL = '/desk/lists/'
+
+EMAIL_HOST = 'localhost'
+DEFAULT_FROM_EMAIL = 'webmaster@parisson.com'
+
+TIMESIDE_DEFAULT_GRAPHER_ID = 'waveform_centroid'
+TIMESIDE_DEFAULT_WAVEFORM_SIZES = ['346x130', '640x130']
+TIMESIDE_AUTO_ZOOM = False
+
+# Settings for django-bootstrap3
+BOOTSTRAP3 = {
+    'set_required': True,
+    'set_placeholder': False,
+    'error_css_class': 'has-error',
+    'required_css_class': 'has-warning',
+    'javascript_in_head': True,
+}
+
+PAGINATION_SETTINGS = {
+    'PAGE_RANGE_DISPLAYED': 10,
+    'MARGIN_PAGES_DISPLAYED': 2,
+}
+
+DEBUG_TOOLBAR_PATCH_SETTINGS = False
+DEBUG_TOOLBAR_PANELS = [
+    'debug_toolbar.panels.versions.VersionsPanel',
+    'debug_toolbar.panels.timer.TimerPanel',
+    'debug_toolbar.panels.settings.SettingsPanel',
+    'debug_toolbar.panels.headers.HeadersPanel',
+    'debug_toolbar.panels.request.RequestPanel',
+    'debug_toolbar.panels.sql.SQLPanel',
+    'debug_toolbar.panels.staticfiles.StaticFilesPanel',
+    'debug_toolbar.panels.templates.TemplatesPanel',
+    'debug_toolbar.panels.cache.CachePanel',
+    'debug_toolbar.panels.signals.SignalsPanel',
+    'debug_toolbar.panels.logging.LoggingPanel',
+    'debug_toolbar.panels.redirects.RedirectsPanel',
+]
+
+SUIT_CONFIG = {
+    'ADMIN_NAME': 'Telemeta Admin'
+}
+
+
+# LOG_DIR = os.path.join(BASE_DIR, 'log')
+
+# if not os.path.exists(LOG_DIR):
+#     os.mkdir(LOG_DIR)
+
+# LOGGING = {
+#     'version': 1,
+#     'disable_existing_loggers': False,
+#     'handlers': {
+#         'file': {
+#             'level': 'DEBUG',
+#             'class': 'logging.FileHandler',
+#             'filename': os.path.join(LOG_DIR, 'debug.log')
+#         },
+#     },
+#     'loggers': {
+#         'django.request': {
+#             'handlers': ['file'],
+#             'level': 'DEBUG',
+#             'propagate': True,
+#         },
+#     },
+# }
diff --git a/examples/sandbox/update_schema.sh b/examples/sandbox/update_schema.sh
new file mode 100755 (executable)
index 0000000..31c658a
--- /dev/null
@@ -0,0 +1,5 @@
+#!/bin/sh
+
+./manage.py schemamigration telemeta --auto
+./manage.py migrate telemeta
+
diff --git a/examples/sandbox/urls.py b/examples/sandbox/urls.py
new file mode 100644 (file)
index 0000000..376539b
--- /dev/null
@@ -0,0 +1,35 @@
+# -*- coding: utf-8 -*-
+from django.conf.urls import patterns, url, include
+from django.http import HttpResponse
+
+# Uncomment the next two lines to enable the admin:
+from django.contrib import admin
+admin.autodiscover()
+
+js_info_dict = {
+    'packages': ('telemeta',),
+}
+
+robots_file = open('robots.txt', 'r')
+
+urlpatterns = patterns('',
+    # Example:
+    # (r'^sandbox/', include('sandbox.foo.urls')),
+
+    # Uncomment the admin/doc line below and add 'django.contrib.admindocs'
+    # to INSTALLED_APPS to enable admin documentation:
+    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),
+
+    # Uncomment the next line to enable the admin:
+    (r'^admin/django/', include(admin.site.urls)),
+    #(r'^grappelli/', include('grappelli.urls')), # grappelli URLS
+
+    # Telemeta
+    (r'^', include('telemeta.urls')),
+
+    # Languages
+    (r'^i18n/', include('django.conf.urls.i18n')),
+    (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict),
+    (r'^robots\.txt$', lambda r: HttpResponse(robots_file.read(), mimetype="text/plain")),
+
+    )
diff --git a/examples/sandbox/wsgi.py b/examples/sandbox/wsgi.py
new file mode 100644 (file)
index 0000000..c3642fe
--- /dev/null
@@ -0,0 +1,14 @@
+#!/usr/bin/python2.5
+# -*- coding: utf-8 -*-
+
+import os
+import sys
+
+here = os.path.dirname(__file__)
+sys.path.append(here)
+
+os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
+
+import django.core.handlers.wsgi
+application = django.core.handlers.wsgi.WSGIHandler()
+
index 1c15caa100cdea4ac63d7c9fdbe0eb28af35a86e..80d0be51524dfac5893c5068ca304541bd679542 100644 (file)
--- a/setup.py
+++ b/setup.py
@@ -61,6 +61,7 @@ setup(
         'django-json-rpc',
         'django-suit',
         'django-google-tools',
+        'django-ipauth',
         'timeside>=0.7',
         'south',
         'sorl-thumbnail',
@@ -68,7 +69,7 @@ setup(
         'psutil',
         'pyyaml',
         'python-ebml',
-        'mysql',
+        'mysql',
         'zipstream',
     ],
   tests_require=['pytest-django', 'pytest-cov', 'factory-boy'],
diff --git a/telemeta/management/commands/telemeta-create-admin-user.py b/telemeta/management/commands/telemeta-create-admin-user.py
new file mode 100644 (file)
index 0000000..23a274f
--- /dev/null
@@ -0,0 +1,24 @@
+from optparse import make_option
+from django.conf import settings
+from django.core.management.base import BaseCommand, CommandError
+from django.contrib.auth.models import User
+
+
+class Command(BaseCommand):
+    help = """Create a default admin user if it doesn't exist.
+            you SHOULD change the password and the email afterwards!"""
+
+    username = 'admin'
+    password = 'admin'
+    email = 'root@example.com'
+
+    def handle(self, *args, **options):
+        admin = User.objects.filter(username=self.username)
+        if not admin:
+            user = User(username=self.username)
+            user.set_password(self.password)
+            user.email = self.email
+            user.is_superuser = True
+            user.is_staff = True
+            user.save()
+            print 'User "'+ self.username + '" created'