Ejemplo n.º 1
0
def document(request, lang, version, url):
    if lang != 'en' or version != 'dev': raise Http404()

    docroot = Path(settings.DOCS_PICKLE_ROOT)

    # First look for <bits>/index.fpickle, then for <bits>.fpickle
    bits = url.strip('/').split('/') + ['index.fpickle']
    doc = docroot.child(*bits)
    if not doc.exists():
        bits = bits[:-2] + ['%s.fpickle' % bits[-2]]
        doc = docroot.child(*bits)
        if not doc.exists():
            raise Http404("'%s' does not exist" % doc)

    bits[-1] = bits[-1].replace('.fpickle', '')
    template_names = [
        'docs/%s.html' % '-'.join([b for b in bits if b]), 
        'docs/doc.html'
    ]
    return render_to_response(template_names, RequestContext(request, {
        'doc': pickle.load(open(doc, 'rb')),
        'env': pickle.load(open(docroot.child('globalcontext.pickle'), 'rb')),
        'update_date': datetime.datetime.fromtimestamp(docroot.child('last_build').mtime()),
        'home': urlresolvers.reverse('document-index', kwargs={'lang':lang, 'version':version}),
        'search': urlresolvers.reverse('document-search', kwargs={'lang':lang, 'version':version}),
        'redirect_from': request.GET.get('from', None),
    }))
 def handle_noargs(self, **kwargs):
     try:
         verbose = int(kwargs['verbosity']) > 0
     except (KeyError, TypeError, ValueError):
         verbose = True
     
     for release in DocumentRelease.objects.all():
         if verbose:
             print "Updating %s..." % release
             
         destdir = Path(settings.DOCS_BUILD_ROOT).child(release.lang, release.version)
         if not destdir.exists():
             destdir.mkdir(parents=True)
         
         # Make an SCM checkout/update into the destination directory.
         # Do this dynamically in case we add other SCM later.
         getattr(self, 'update_%s' % release.scm)(release.scm_url, destdir)
         
         # Make the directory for the JSON files - sphinx-build doesn't
         # do it for us, apparently.
         json_build_dir = destdir.child('_build', 'json')
         if not json_build_dir.exists():
             json_build_dir.mkdir(parents=True)
         
         # "Shell out" (not exactly, but basically) to sphinx-build.
         sphinx.cmdline.main(['sphinx-build',
             '-b', 'json',      # Use the JSON builder
             '-q',              # Be vewy qwiet
             destdir,           # Source file directory
             json_build_dir,    # Destination directory
         ])
Ejemplo n.º 3
0
 def handle_noargs(self, **options):
     project_dir = Path(__file__).absolute().ancestor(4)
     data_file = project_dir.child("static", "js", "station_polys.json")
     with open(data_file, "r") as f:
         data = json.loads(f.read())
         for station_id, coords in data.items():
             station = Station.objects.get(id=station_id)
             station.polygon = coords
             station.save()
Ejemplo n.º 4
0
def run_benchmarks(control, benchmark_dir, benchmarks, trials, record_dir=None, profile_dir=None):
    if benchmarks:
        print "Running benchmarks: %s" % " ".join(benchmarks)
    else:
        print "Running all benchmarks"

    if record_dir:
        record_dir = Path(record_dir).expand().absolute()
        if not record_dir.exists():
            raise ValueError('Recording directory "%s" does not exist' % record_dir)
        print "Recording data to '%s'" % record_dir

    control_label = get_django_version(control, vcs=None)
    branch_info =  ""
    print "Benchmarking: Django %s (in %s%s)" % (control_label, branch_info, control)
    print "    Control: %s" % cpython
    print "    Experiment: %s" % pypy
    print
    
    control_env = {'PYTHONPATH': '.:%s:%s' % (Path(control).absolute(), Path(benchmark_dir))}
    
    for benchmark in discover_benchmarks(benchmark_dir):
        if not benchmarks or benchmark.name in benchmarks:
            print "Running '%s' benchmark ..." % benchmark.name
            settings_mod = '%s.settings' % benchmark.name
            control_env['DJANGO_SETTINGS_MODULE'] = settings_mod
            experiment_env = control_env.copy()
            if profile_dir is not None:
                control_env['DJANGOBENCH_PROFILE_FILE'] = Path(profile_dir, "cpython-%s" % benchmark.name)
                experiment_env['DJANGOBENCH_PROFILE_FILE'] = Path(profile_dir, "pypy-%s" % benchmark.name)
            try:
                control_data = run_benchmark(benchmark, trials, control_env, cpython)
                experiment_data = run_benchmark(benchmark, trials, experiment_env, pypy)
            except SkipBenchmark, reason:
                print "Skipped: %s\n" % reason
                continue

            options = argparse.Namespace(
                track_memory = False,
                diff_instrumentation = False,
                benchmark_name = benchmark.name,
                disable_timelines = True,
            )
            result = perf.CompareBenchmarkData(control_data, experiment_data, options)
            if record_dir:
                record_benchmark_results(
                    dest = record_dir.child('%s.json' % benchmark.name),
                    name = benchmark.name,
                    result = result,
                    control = 'cpython',
                    experiment = 'pypy',
                    control_data = control_data,
                    experiment_data = experiment_data,
                )
            print format_benchmark_result(result, len(control_data.runtimes))
            print
Ejemplo n.º 5
0
def search(request, lang, version):
    if lang != 'en' or version != 'dev': raise Http404()
    
    docroot = Path(settings.DOCS_PICKLE_ROOT)
    
    # Remove the 'cof' GET variable from the query string so that the page
    # linked to by the Javascript fallback doesn't think its inside an iframe.
    mutable_get = request.GET.copy()
    if 'cof' in mutable_get:
        del mutable_get['cof']
    
    return render_to_response('docs/search.html', RequestContext(request, {
        'query': request.GET.get('q'),
        'query_string': mutable_get.urlencode(),
        'env': pickle.load(open(docroot.child('globalcontext.pickle'), 'rb')),
        'home': urlresolvers.reverse('document-index', kwargs={'lang':lang, 'version':version}),
        'search': urlresolvers.reverse('document-search', kwargs={'lang':lang, 'version':version}),
    }))
Ejemplo n.º 6
0
def run_benchmarks(control,
                   experiment,
                   benchmark_dir,
                   benchmarks,
                   trials,
                   vcs=None,
                   record_dir=None,
                   profile_dir=None,
                   continue_on_error=False):
    if benchmarks:
        print "Running benchmarks: %s" % " ".join(benchmarks)
    else:
        print "Running all benchmarks"

    if record_dir:
        record_dir = Path(record_dir).expand().absolute()
        if not record_dir.exists():
            raise ValueError('Recording directory "%s" does not exist' %
                             record_dir)
        print "Recording data to '%s'" % record_dir

    control_label = get_widgy_version(control, vcs=vcs)
    experiment_label = get_widgy_version(experiment, vcs=vcs)
    branch_info = "%s branch " % vcs if vcs else ""
    print "Control: Widgy %s (in %s%s)" % (control_label, branch_info, control)
    print "Experiment: Widgy %s (in %s%s)" % (experiment_label, branch_info,
                                              experiment)
    print

    # Calculate the subshell envs that we'll use to execute the
    # benchmarks in.
    if vcs:
        control_env = {
            'PYTHONPATH':
            '%s:%s' % (Path.cwd().absolute(), Path(benchmark_dir)),
        }
        experiment_env = control_env.copy()
    else:
        control_env = {
            'PYTHONPATH':
            '%s:%s' % (Path(control).absolute(), Path(benchmark_dir))
        }
        experiment_env = {
            'PYTHONPATH':
            '%s:%s' % (Path(experiment).absolute(), Path(benchmark_dir))
        }

    for benchmark in discover_benchmarks(benchmark_dir):
        if not benchmarks or benchmark.name in benchmarks:
            print "Running '%s' benchmark ..." % benchmark.name
            settings_mod = '%s.settings' % benchmark.name
            control_env['DJANGO_SETTINGS_MODULE'] = settings_mod
            experiment_env['DJANGO_SETTINGS_MODULE'] = settings_mod
            if profile_dir is not None:
                control_env['DJANGOBENCH_PROFILE_FILE'] = Path(
                    profile_dir, "con-%s" % benchmark.name)
                experiment_env['DJANGOBENCH_PROFILE_FILE'] = Path(
                    profile_dir, "exp-%s" % benchmark.name)
            try:
                if vcs: switch_to_branch(vcs, control)
                control_data = run_benchmark(benchmark, trials, control_env)
                if vcs: switch_to_branch(vcs, experiment)
                experiment_data = run_benchmark(benchmark, trials,
                                                experiment_env)
            except SkipBenchmark, reason:
                print "Skipped: %s\n" % reason
                continue
            except RuntimeError, error:
                if continue_on_error:
                    print "Failed: %s\n" % error
                    continue
                raise

            options = argparse.Namespace(
                track_memory=False,
                diff_instrumentation=False,
                benchmark_name=benchmark.name,
                disable_timelines=True,
                control_label=control_label,
                experiment_label=experiment_label,
            )
            result = perf.CompareBenchmarkData(control_data, experiment_data,
                                               options)
            if record_dir:
                record_benchmark_results(
                    dest=record_dir.child('%s.json' % benchmark.name),
                    name=benchmark.name,
                    result=result,
                    control=control_label,
                    experiment=experiment_label,
                    control_data=control_data,
                    experiment_data=experiment_data,
                )
            print format_benchmark_result(result, len(control_data.runtimes))
            print
Ejemplo n.º 7
0
# -*- coding: utf-8 -*-

from unipath import FSPath as Path

PROJECT_ROOT = Path(__file__).absolute().ancestor(2)

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": PROJECT_ROOT.child("dev.db"),
        "USER": "",
        "PASSWORD": "",
        "HOST": "",
        "PORT": "",
    }
}


# -- django-celery

REDIS_CONNECT_RETRY = True
REDIS_HOST = "localhost"
REDIS_PORT = 6379
REDIS_DB = 0

BROKER_HOST = REDIS_HOST
BROKER_PORT = REDIS_PORT
BROKER_VHOST = REDIS_DB
Ejemplo n.º 8
0
    ('Ori Livneh', '*****@*****.**'),
)

MANAGERS = ADMINS

# needed by django-debug-toolbar
INTERNAL_IPS = ('127.0.0.1',)

# l10n / i18n
TIME_ZONE = 'America/New_York'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = True
USE_L10N = True

MEDIA_ROOT = PROJECT_DIR.child('media')
MEDIA_URL = '/media/'

STATIC_ROOT = PROJECT_DIR.child('static_root')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    str(PROJECT_DIR.child('static')),
)

ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'

AUTH_PROFILE_MODULE = 'profiles.Profile'

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
Ejemplo n.º 9
0
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}


######################################
# Media/Static
######################################

MEDIA_ROOT = PROJECT_DIR.parent.child('data')
MEDIA_URL = '/media/'

STATIC_ROOT = PROJECT_DIR.child('static_root')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    str(PROJECT_DIR.child('static')),
)
ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'

# 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',
)

######################################
Ejemplo n.º 10
0
    ('Idan Gazit', '*****@*****.**'),
    ('Yuval Adam', '*****@*****.**'),
)
MANAGERS = ADMINS
INTERNAL_IPS = ('127.0.0.1', )

SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'

TIME_ZONE = 'Etc/UTC'
USE_TZ = True
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = False
USE_L10N = True

MEDIA_ROOT = PROJECT_DIR.child('media')
MEDIA_URL = 'http://' + AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com/media'

STATIC_ROOT = PROJECT_DIR.child('static_root')
STATIC_URL = 'http://' + AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com/'
STATICFILES_DIRS = (str(PROJECT_DIR.child('static')), )
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    #    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'

ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'

SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')
Ejemplo n.º 11
0
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'djangoproject',
        'USER': '******'
    },
    'trac': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'code.djangoproject',
        'USER': '******'
    }
}
DATABASE_ROUTERS = ['django_website.trac.db_router.TracRouter']

USE_I18N = False
USE_L10N = False

TEMPLATE_DIRS = [BASE.child('templates')]
MEDIA_ROOT = BASE.parent.child('media')

if PRODUCTION:
    DEBUG = False
    PREPEND_WWW = True
    CACHE_BACKEND = 'memcached://127.0.0.1:11211/'
    MEDIA_URL = "https://www.djangoproject.com/m/"
    ADMIN_MEDIA_PREFIX = "https://www.djangoproject.com/m/admin/"
else:
    DEBUG = True
    PREPEND_WWW = False
    CACHE_BACKEND = "dummy:///"
    MEDIA_URL = "/media/"
    ADMIN_MEDIA_PREFIX = '/admin_media/'
    EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
Ejemplo n.º 12
0
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'djangoproject',
        'USER': '******'
    },
    'trac': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'code.djangoproject',
        'USER': '******'
    }
}
DATABASE_ROUTERS = ['django_website.trac.db_router.TracRouter']

USE_I18N = False
USE_L10N = False

TEMPLATE_DIRS = [BASE.child('templates')]
MEDIA_ROOT = BASE.parent.child('media')

if PRODUCTION:
    DEBUG = False
    PREPEND_WWW = True
    CACHE_BACKEND = 'memcached://127.0.0.1:11211/'
    MEDIA_URL = "https://www.djangoproject.com/m/"
    ADMIN_MEDIA_PREFIX = "https://www.djangoproject.com/m/admin/"
else:
    DEBUG = True
    PREPEND_WWW = False
    CACHE_BACKEND = "dummy:///"
    MEDIA_URL = "/media/"
    ADMIN_MEDIA_PREFIX = '/admin_media/'
    EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
Ejemplo n.º 13
0
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

# 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: "/var/www/example.com/media/"
MEDIA_ROOT = PROJECT_DIR.child('media_root')

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
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: "/var/www/example.com/static/"
STATIC_ROOT = PROJECT_DIR.child('static_root')
STATICFILES_ROOT = PROJECT_DIR.child('static')

# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
Ejemplo n.º 14
0
from unipath import FSPath as Path

PROJECT_DIR = Path(__file__).absolute().ancestor(2)

#
# My settings
#

_creds = PROJECT_DIR.child('trac-creds.txt').read_file().strip()
TRAC_RPC_URL = "https://%[email protected]/login/rpc" % _creds
TRAC_URL = "https://code.djangoproject.com/"

#
# Django settings follow...
#

DEBUG = False
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', '*****@*****.**'),
)

MANAGERS = ADMINS

TIME_ZONE = 'America/Chicago'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = True
USE_L10N = True
Ejemplo n.º 15
0
    def handle_noargs(self, **kwargs):
        try:
            verbosity = int(kwargs['verbosity'])
        except (KeyError, TypeError, ValueError):
            verbosity = 1

        # Somehow, bizarely, there's a bug in Sphinx such that if I try to
        # build 1.0 before other versions, things fail in weird ways. However,
        # building newer versions first works. I suspect Sphinx is hanging onto
        # some global state. Anyway, we can work around it by making sure that
        # "dev" builds before "1.0". This is ugly, but oh well.
        for release in DocumentRelease.objects.order_by('-version'):
            if verbosity >= 1:
                print "Updating %s..." % release

            # checkout_dir is shared for all languages.
            checkout_dir = Path(settings.DOCS_BUILD_ROOT).child(
                release.version)
            parent_build_dir = Path(settings.DOCS_BUILD_ROOT).child(
                release.lang, release.version)
            if not checkout_dir.exists():
                checkout_dir.mkdir(parents=True)
            if not parent_build_dir.exists():
                parent_build_dir.mkdir(parents=True)

            #
            # Update the release from SCM.
            #

            # Make an SCM checkout/update into the destination directory.
            # Do this dynamically in case we add other SCM later.
            getattr(self, 'update_%s' % release.scm)(release.scm_url,
                                                     checkout_dir)

            if release.docs_subdir:
                source_dir = checkout_dir.child(
                    *release.docs_subdir.split('/'))
            else:
                source_dir = checkout_dir

            if release.lang != 'en':
                scm_url = release.scm_url.replace(
                    'django.git', 'django-docs-translations.git')
                trans_dir = checkout_dir.child('django-docs-translation')
                if not trans_dir.exists():
                    trans_dir.mkdir()
                getattr(self, 'update_%s' % release.scm)(scm_url, trans_dir)
                if not source_dir.child('locale').exists():
                    source_dir.child('locale').write_link(
                        trans_dir.child('translations'))
                subprocess.call("cd %s && make translations" % trans_dir,
                                shell=True)

            #
            # Use Sphinx to build the release docs into JSON and HTML documents.
            #
            for builder in ('json', 'html'):
                # Wipe and re-create the build directory. See #18930.
                build_dir = parent_build_dir.child('_build', builder)
                if build_dir.exists():
                    shutil.rmtree(build_dir)
                build_dir.mkdir(parents=True)

                # "Shell out" (not exactly, but basically) to sphinx-build.
                if verbosity >= 2:
                    print "  building %s (%s -> %s)" % (builder, source_dir,
                                                        build_dir)
                sphinx.cmdline.main([
                    'sphinx-build',
                    '-b',
                    builder,
                    '-D',
                    'language=%s' % release.lang,
                    '-q',  # Be vewy qwiet
                    source_dir,  # Source file directory
                    build_dir,  # Destination directory
                ])

            #
            # Create a zip file of the HTML build for offline reading.
            # This gets moved into MEDIA_ROOT for downloading.
            #
            html_build_dir = parent_build_dir.child('_build', 'html')
            zipfile_name = 'django-docs-%s-%s.zip' % (release.version,
                                                      release.lang)
            zipfile_path = Path(settings.MEDIA_ROOT).child(
                'docs', zipfile_name)
            if not zipfile_path.parent.exists():
                zipfile_path.parent.mkdir(parents=True)
            if verbosity >= 2:
                print "  build zip (into %s)" % zipfile_path

            def zipfile_inclusion_filter(f):
                return f.isfile() and '.doctrees' not in f.components()

            with closing(zipfile.ZipFile(zipfile_path, 'w')) as zf:
                for f in html_build_dir.walk(filter=zipfile_inclusion_filter):
                    zf.write(f, html_build_dir.rel_path_to(f))

            #
            # Copy the build results to the directory used for serving
            # the documentation in the least disruptive way possible.
            #
            build_dir = parent_build_dir.child('_build')
            built_dir = parent_build_dir.child('_built')
            subprocess.check_call([
                'rsync', '--archive', '--delete', '--link-dest=' + build_dir,
                build_dir + '/', built_dir
            ])

            #
            # Rebuild the imported document list and search index.
            #
            if not kwargs['reindex']:
                continue

            if verbosity >= 2:
                print "  reindexing..."

            # Build a dict of {path_fragment: document_object}. We'll pop values
            # out of this dict as we go which'll make sure we know which
            # remaining documents need to be deleted (and unindexed) later on.
            documents = dict(
                (doc.path, doc) for doc in release.documents.all())

            # Walk the tree we've just built looking for ".fjson" documents
            # (just JSON, but Sphinx names them weirdly). Each one of those
            # documents gets a corresponding Document object created which
            # we'll then ask Sphinx to reindex.
            #
            # We have to be a bit careful to reverse-engineer the correct
            # relative path component, especially for "index" documents,
            # otherwise the search results will be incorrect.
            json_built_dir = parent_build_dir.child('_built', 'json')
            for built_doc in json_built_dir.walk():
                if built_doc.isfile() and built_doc.ext == '.fjson':

                    # Convert the built_doc path which is now an absolute
                    # path (i.e. "/home/docs/en/1.2/_built/ref/models.json")
                    # into a path component (i.e. "ref/models").
                    path = json_built_dir.rel_path_to(built_doc)
                    if path.stem == 'index':
                        path = path.parent
                    path = str(path.parent.child(path.stem))

                    # Read out the content and create a new Document object for
                    # it. We'll strip the HTML tags here (for want of a better
                    # place to do it).
                    with open(built_doc) as fp:
                        json_doc = json.load(fp)
                        try:
                            json_doc['body']  # Just to make sure it exists.
                            title = unescape_entities(
                                strip_tags(json_doc['title']))
                        except KeyError, ex:
                            if verbosity >= 2:
                                print "Skipping: %s (no %s)" % (path,
                                                                ex.args[0])
                            continue

                    doc = documents.pop(path,
                                        Document(path=path, release=release))
                    doc.title = title
                    doc.save()
                    haystack.site.update_object(doc)

            # Clean up any remaining documents.
            for doc in documents.values():
                if verbosity >= 2:
                    print "Deleting:", doc
                haystack.site.remove_object(doc)
                doc.delete()
Ejemplo n.º 16
0
from unipath import FSPath as Path

PROJECT_DIR = Path(__file__).absolute().ancestor(2)

#
# My settings
#

_creds = PROJECT_DIR.child('trac-creds.txt').read_file().strip()
TRAC_RPC_URL = "https://%[email protected]/login/rpc" % _creds
TRAC_URL = "https://code.djangoproject.com/"

#
# Django settings follow...
#

DEBUG = False
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', '*****@*****.**'),
)

MANAGERS = ADMINS

TIME_ZONE = 'America/Chicago'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = True
USE_L10N = True
Ejemplo n.º 17
0
import json
import os
import platform

from unipath import FSPath as Path

### Utilities

# The full path to the repository root.
BASE = Path(__file__).absolute().ancestor(2)

# Far too clever trick to know if we're running on the deployment server.
PRODUCTION = ('DJANGOPROJECT_DEBUG' not in os.environ)

# It's a secret to everybody
with open(BASE.child('secrets.json')) as handle:
    SECRETS = json.load(handle)

### Django settings

ADMINS = (
    ('Adrian Holovaty', '*****@*****.**'),
    ('Jacob Kaplan-Moss', '*****@*****.**'),
)

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': SECRETS.get('memcached_host', '127.0.0.1:11211'),
    } if PRODUCTION else {
        'BACKEND': 'django.core.cache.backends.dummy.DummyCache'
Ejemplo n.º 18
0
LANGUAGE_CODE = 'en-us'

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 filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = BASE.child('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 = '/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/'
Ejemplo n.º 19
0
MEDIA_URL = '/media/'

if environ.has_key('AWS_STORAGE_BUCKET'):
    AWS_STORAGE_BUCKET_NAME = environ['AWS_STORAGE_BUCKET']
    AWS_ACCESS_KEY_ID = environ['AWS_ACCESS_KEY_ID']
    AWS_SECRET_ACCESS_KEY = environ['AWS_SECRET_ACCESS_KEY']
    STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
    DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
    S3_URL = 'http://%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME
    STATIC_URL = S3_URL
    ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'
else:
    STATIC_URL = '/static/'


MEDIA_ROOT = BASE.child('media')
STATIC_ROOT = BASE.child('static')
STATICFILES_DIRS = (
    BASE.child('design'),
)
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 = env('SECRET_KEY', 'lo7i8ko)i00be5!%45*l2i6_1$5ylbkv-w1nk87#ge9f^)(cv@')

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
Ejemplo n.º 20
0
from unipath import FSPath as Path

BASE = Path(__file__).parent

DEBUG = TEMPLATE_DEBUG = platform.node() != 'jacobian.org'
MANAGERS = ADMINS = []

TIME_ZONE = 'America/Chicago'
LANGUAGE_CODE = 'en-us'
USE_I18N = False
USE_L10N = False

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE.child('nn.db'),
    }
}
MIDDLEWARE_CLASSES = []

SITE_ID = 1
SECRET_KEY = 'LOCAL' if DEBUG else open('/home/web/sekrit.txt').read().strip()

ROOT_URLCONF = 'djangome.urls'
INSTALLED_APPS = ['djangome', 'gunicorn']
TEMPLATE_DIRS = [BASE.child('templates')]

REDIS = {
    'host': 'localhost',
    'port': 6379,
    'db': 0,
Ejemplo n.º 21
0
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static-deploy')

"""Application Settings"""

# URL prefix for static files.
STATIC_URL = '/static/'

# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
ADMIN_MEDIA_PREFIX = '/static/admin/'

# Additional locations of static files
STATICFILES_DIRS = (
    PROJECT_DIR.child('static'),
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# 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',
)
Ejemplo n.º 22
0
import sys

from unipath import FSPath as Path

PROJECT_ROOT = Path(__file__).absolute().ancestor(2)
sys.path.insert(0, PROJECT_ROOT.child("apps"))

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
# ('Your Name', '*****@*****.**'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'dev.db', # Or path to database file if using sqlite3.
        # The following settings are not used with sqlite3:
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
        'PORT': '', # Set to empty string for default.
    }
}

# Hosts/domain names that are valid for this site; required if DEBUG is False
Ejemplo n.º 23
0
MEDIA_ROOT = BASE.ancestor(1).child('media')

MEDIA_URL = '/m/'

SECRET_KEY = str(SECRETS['secret_key'])

SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTOCOL", "https")

SERVER_EMAIL = "*****@*****.**"

SESSION_COOKIE_SECURE = PRODUCTION

SESSION_COOKIE_HTTPONLY = True

STATICFILES_DIRS = [BASE.child('static')]

STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.CachedStaticFilesStorage'

STATIC_ROOT = BASE.ancestor(1).child('static')

STATIC_URL = '/s/'

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

TEMPLATE_DIRS = [BASE.child('templates')]

TIME_ZONE = 'America/Chicago'
Ejemplo n.º 24
0
TEMPLATE_DEBUG = DEBUG

ADMINS = ()
MANAGERS = ADMINS
INTERNAL_IPS = ('127.0.0.1',)

SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'

TIME_ZONE = 'Etc/UTC'
USE_TZ = True
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = False
USE_L10N = True

MEDIA_ROOT = PROJECT_DIR.child('media')
# the following line is a total lie
MEDIA_URL = 'http://' + AWS_STORAGE_BUCKET_NAME + '/media'

STATIC_ROOT = PROJECT_DIR.child('static_root')
STATICFILES_ROOT = PROJECT_DIR.child('static')
STATIC_URL = '//' + AWS_STORAGE_BUCKET_NAME
STATICFILES_DIRS = [
    (subdir, str(STATICFILES_ROOT.child(subdir))) for subdir in
    ['css', 'fonts', 'img', 'js']]
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
STATICFILES_STORAGE = 'telostats.utils.customstorages.ProtocolRelativeS3BotoStorage'
Ejemplo n.º 25
0
        RETHINK_CONNARGS[v] = p


MANAGERS = ADMINS


ALLOWED_HOSTS = []
TIME_ZONE = 'Etc/UTC'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = False
USE_L10N = True
USE_TZ = True


MEDIA_ROOT = PROJECT_DIR.child('media')
# the following line is a total lie except in production
# MEDIA_URL = 'http://{}.s3.amazonaws.com/media/'.format(AWS_STORAGE_BUCKET_NAME)

STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_ROOT = PROJECT_DIR.child('static')
STATICFILES_DIRS = [
    (subdir, str(STATICFILES_ROOT.child(subdir))) for subdir in
    ['css', 'fonts', 'img', 'js']]
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

SECRET_KEY = get_env_variable('APP_SECRET_KEY')
Ejemplo n.º 26
0
import os
import dj_database_url

from unipath import FSPath as Path


def env_or_default(NAME, default):
    return os.environ.get(NAME, default)


PROJECT_ROOT = Path(__file__).ancestor(3)
PACKAGE_ROOT = PROJECT_ROOT.child('djangocon')

BASE_DIR = PACKAGE_ROOT

DEBUG = bool(int(os.environ.get("DEBUG", "1")))

DATABASES = {
    "default": dj_database_url.config(default="postgres://localhost/djangocon2016")
}

ALLOWED_HOSTS = [
    os.environ.get("GONDOR_INSTANCE_DOMAIN"),
    "2016.djangocon.us",
    "www.djangocon.us",
    "localhost',"
]

# 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.
Ejemplo n.º 27
0
        'USER': '******',
        'PASSWORD': '******',
        'HOST': '127.0.0.1',
        'PORT': '',
    }
}

ALLOWED_HOSTS = []
TIME_ZONE = 'Europe/Rome'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = False
USE_L10N = False
USE_TZ = True

MEDIA_ROOT = BASE.child('media')
MEDIA_URL = '/media/'
STATIC_ROOT = BASE.child('static')
STATIC_URL = '/static/'

STATICFILES_DIRS = ()

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

SECRET_KEY = 'amucggr)7x199cciygmay_!-%m%=k-&g)47_h7c(@dcr^cm=(u'

TEMPLATE_LOADERS = (
Ejemplo n.º 28
0
def run_benchmarks(control, experiment, benchmark_dir, benchmarks, trials, vcs=None, record_dir=None, profile_dir=None):
    if benchmarks:
        print "Running benchmarks: %s" % " ".join(benchmarks)
    else:
        print "Running all benchmarks"

    if record_dir:
        record_dir = Path(record_dir).expand().absolute()
        if not record_dir.exists():
            raise ValueError('Recording directory "%s" does not exist' % record_dir)
        print "Recording data to '%s'" % record_dir

    control_label = get_django_version(control, vcs=vcs)
    experiment_label = get_django_version(experiment, vcs=vcs)
    branch_info = "%s branch " % vcs if vcs else ""
    print "Control: Django %s (in %s%s)" % (control_label, branch_info, control)
    print "Experiment: Django %s (in %s%s)" % (experiment_label, branch_info, experiment)
    print

    # Calculate the subshell envs that we'll use to execute the
    # benchmarks in.
    if vcs:
        control_env = experiment_env = {
            'PYTHONPATH': '%s:%s' % (Path.cwd().absolute(), Path(benchmark_dir)),
        }
    else:
        control_env = {'PYTHONPATH': '%s:%s' % (Path(control).absolute(), Path(benchmark_dir))}
        experiment_env = {'PYTHONPATH': '%s:%s' % (Path(experiment).absolute(), Path(benchmark_dir))}

    for benchmark in discover_benchmarks(benchmark_dir):
        if not benchmarks or benchmark.name in benchmarks:
            print "Running '%s' benchmark ..." % benchmark.name
            settings_mod = '%s.settings' % benchmark.name
            control_env['DJANGO_SETTINGS_MODULE'] = settings_mod
            experiment_env['DJANGO_SETTINGS_MODULE'] = settings_mod
            if profile_dir is not None:
                control_env['DJANGOBENCH_PROFILE_FILE'] = Path(profile_dir, "con-%s" % benchmark.name)
                experiment_env['DJANGOBENCH_PROFILE_FILE'] = Path(profile_dir, "exp-%s" % benchmark.name)
            try:
                if vcs: switch_to_branch(vcs, control)
                control_data = run_benchmark(benchmark, trials, control_env)
                if vcs: switch_to_branch(vcs, experiment)
                experiment_data = run_benchmark(benchmark, trials, experiment_env)
            except SkipBenchmark, reason:
                print "Skipped: %s\n" % reason
                continue

            options = argparse.Namespace(
                track_memory = False,
                diff_instrumentation = False,
                benchmark_name = benchmark.name,
                disable_timelines = True,
                control_label = control_label,
                experiment_label = experiment_label,
            )
            result = perf.CompareBenchmarkData(control_data, experiment_data, options)
            if record_dir:
                record_benchmark_results(
                    dest = record_dir.child('%s.json' % benchmark.name),
                    name = benchmark.name,
                    result = result,
                    control = control_label,
                    experiment = experiment_label,
                    control_data = control_data,
                    experiment_data = experiment_data,
                )
            print format_benchmark_result(result, len(control_data.runtimes))
            print
Ejemplo n.º 29
0
# http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes
LANGUAGE_CODE = 'en-us'

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

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

# Additional locations of static files
STATICFILES_DIRS = (
    BASE_DIR.child("static"),
)

# 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',
)

# 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/'
Ejemplo n.º 30
0
# Language code for this installation. All choices can be found here:
# http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes
LANGUAGE_CODE = 'en-us'

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

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

# Additional locations of static files
STATICFILES_DIRS = (BASE_DIR.child("static"), )

# 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',
)

# 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/'

MIDDLEWARE_CLASSES = (
Ejemplo n.º 31
0
# following PEP 386, versiontools will pick it up
__version__ = (0, 1, 0, "final", 0)

from unipath import FSPath as Path

PROJECT_DIR = Path(__file__).absolute().ancestor(1)
WORKER_BUNDLE = PROJECT_DIR.child("worker_bundle")
Ejemplo n.º 32
0
Archivo: common.py Proyecto: hex2a/mos
# http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes
LANGUAGE_CODE = 'en-us'

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

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

# Additional locations of static files
STATICFILES_DIRS = (
    BASE_DIR.child("static"),
)

# 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',
)

# 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/'
Ejemplo n.º 33
0
        'PASSWORD': SECRETS.get('db_password', ''),
    },
    'trac': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'code.djangoproject',
        'USER': '******',
        'HOST': SECRETS.get('trac_db_host', ''),
        'PASSWORD': SECRETS.get('trac_db_password', ''),
    }
}

DATABASE_ROUTERS = ['tracdb.db_router.TracRouter']

DEFAULT_FROM_EMAIL = "*****@*****.**"

FIXTURE_DIRS = [BASE.child('fixtures')]

INSTALLED_APPS = [
    'django.contrib.sites',
    'django.contrib.auth',
    'django.contrib.admin',
    'django.contrib.contenttypes',
    'django.contrib.flatpages',
    'django.contrib.humanize',
    'django.contrib.messages',
    'django.contrib.redirects',
    'django.contrib.sessions',
    'django.contrib.staticfiles',
    'django.contrib.sitemaps',
    'django_push.subscriber',
    'djangosecure',
Ejemplo n.º 34
0
    def handle_noargs(self, **kwargs):
        try:
            verbosity = int(kwargs['verbosity'])
        except (KeyError, TypeError, ValueError):
            verbosity = 1

        builders = ['json', 'html']

        # Somehow, bizarely, there's a bug in Sphinx such that if I try to
        # build 1.0 before other versions, things fail in weird ways. However,
        # building newer versions first works. I suspect Sphinx is hanging onto
        # some global state. Anyway, we can work around it by making sure that
        # "dev" builds before "1.0". This is ugly, but oh well.
        for release in DocumentRelease.objects.order_by('-version'):
            if verbosity >= 1:
                print "Updating %s..." % release

            # checkout_dir is shared for all languages.
            checkout_dir = Path(settings.DOCS_BUILD_ROOT).child(release.version)
            parent_build_dir = Path(settings.DOCS_BUILD_ROOT).child(release.lang, release.version)
            if not checkout_dir.exists():
                checkout_dir.mkdir(parents=True)
            if not parent_build_dir.exists():
                parent_build_dir.mkdir(parents=True)

            #
            # Update the release from SCM.
            #

            # Make an SCM checkout/update into the destination directory.
            # Do this dynamically in case we add other SCM later.
            getattr(self, 'update_%s' % release.scm)(release.scm_url, checkout_dir)

            if release.docs_subdir:
                source_dir = checkout_dir.child(*release.docs_subdir.split('/'))
            else:
                source_dir = checkout_dir

            if release.lang != 'en':
                scm_url = release.scm_url.replace('django.git', 'django-docs-translations.git')
                trans_dir = checkout_dir.child('django-docs-translation')
                if not trans_dir.exists():
                    trans_dir.mkdir()
                getattr(self, 'update_%s' % release.scm)(scm_url, trans_dir)
                if not source_dir.child('locale').exists():
                    source_dir.child('locale').write_link(trans_dir.child('translations'))
                subprocess.call("cd %s && make translations" % trans_dir, shell=True)

            if release.is_default:
                # Build the pot files (later retrieved by Transifex)
                builders.append('gettext')

            #
            # Use Sphinx to build the release docs into JSON and HTML documents.
            #
            for builder in builders:
                # Wipe and re-create the build directory. See #18930.
                build_dir = parent_build_dir.child('_build', builder)
                if build_dir.exists():
                    shutil.rmtree(build_dir)
                build_dir.mkdir(parents=True)

                if verbosity >= 2:
                    print "  building %s (%s -> %s)" % (builder, source_dir, build_dir)
                subprocess.call(['sphinx-build',
                    '-b', builder,
                    '-D', 'language=%s' % release.lang,
                    '-q',              # Be vewy qwiet
                    source_dir,        # Source file directory
                    build_dir,         # Destination directory
                ])

            #
            # Create a zip file of the HTML build for offline reading.
            # This gets moved into MEDIA_ROOT for downloading.
            #
            html_build_dir = parent_build_dir.child('_build', 'html')
            zipfile_name = 'django-docs-%s-%s.zip' % (release.version, release.lang)
            zipfile_path = Path(settings.MEDIA_ROOT).child('docs', zipfile_name)
            if not zipfile_path.parent.exists():
                zipfile_path.parent.mkdir(parents=True)
            if verbosity >= 2:
                print "  build zip (into %s)" % zipfile_path

            def zipfile_inclusion_filter(f):
                return f.isfile() and '.doctrees' not in f.components()

            with closing(zipfile.ZipFile(zipfile_path, 'w')) as zf:
                for f in html_build_dir.walk(filter=zipfile_inclusion_filter):
                    zf.write(f, html_build_dir.rel_path_to(f))

            #
            # Copy the build results to the directory used for serving
            # the documentation in the least disruptive way possible.
            #
            build_dir = parent_build_dir.child('_build')
            built_dir = parent_build_dir.child('_built')
            subprocess.check_call(['rsync', '--archive', '--delete',
                    '--link-dest=' + build_dir, build_dir + '/', built_dir])

            #
            # Rebuild the imported document list and search index.
            #
            if not kwargs['reindex']:
                continue

            if verbosity >= 2:
                print "  reindexing..."

            # Build a dict of {path_fragment: document_object}. We'll pop values
            # out of this dict as we go which'll make sure we know which
            # remaining documents need to be deleted (and unindexed) later on.
            documents = dict((doc.path, doc) for doc in release.documents.all())

            # Walk the tree we've just built looking for ".fjson" documents
            # (just JSON, but Sphinx names them weirdly). Each one of those
            # documents gets a corresponding Document object created which
            # we'll then ask Sphinx to reindex.
            #
            # We have to be a bit careful to reverse-engineer the correct
            # relative path component, especially for "index" documents,
            # otherwise the search results will be incorrect.
            json_built_dir = parent_build_dir.child('_built', 'json')
            for built_doc in json_built_dir.walk():
                if built_doc.isfile() and built_doc.ext == '.fjson':

                    # Convert the built_doc path which is now an absolute
                    # path (i.e. "/home/docs/en/1.2/_built/ref/models.json")
                    # into a path component (i.e. "ref/models").
                    path = json_built_dir.rel_path_to(built_doc)
                    if path.stem == 'index':
                        path = path.parent
                    path = str(path.parent.child(path.stem))

                    # Read out the content and create a new Document object for
                    # it. We'll strip the HTML tags here (for want of a better
                    # place to do it).
                    with open(built_doc) as fp:
                        json_doc = json.load(fp)
                        try:
                            json_doc['body']  # Just to make sure it exists.
                            title = unescape_entities(strip_tags(json_doc['title']))
                        except KeyError, ex:
                            if verbosity >= 2:
                                print "Skipping: %s (no %s)" % (path, ex.args[0])
                            continue

                    doc = documents.pop(path, Document(path=path, release=release))
                    doc.title = title
                    doc.save()
                    haystack.site.update_object(doc)

            # Clean up any remaining documents.
            for doc in documents.values():
                if verbosity >= 2:
                    print "Deleting:", doc
                haystack.site.remove_object(doc)
                doc.delete()
Ejemplo n.º 35
0
for k, v in rethink_argmap.items():
    p = getattr(RETHINKDB_URL, k, None)
    if p is not None:
        RETHINK_CONNARGS[v] = p

MANAGERS = ADMINS

ALLOWED_HOSTS = []
TIME_ZONE = 'Etc/UTC'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = False
USE_L10N = True
USE_TZ = True

MEDIA_ROOT = PROJECT_DIR.child('media')
# the following line is a total lie except in production
# MEDIA_URL = 'http://{}.s3.amazonaws.com/media/'.format(AWS_STORAGE_BUCKET_NAME)

STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_ROOT = PROJECT_DIR.child('static')
STATICFILES_DIRS = [(subdir, str(STATICFILES_ROOT.child(subdir)))
                    for subdir in ['css', 'fonts', 'img', 'js']]
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

SECRET_KEY = get_env_variable('APP_SECRET_KEY')
Ejemplo n.º 36
0
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
from unipath import FSPath as Path
import os
import json

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

if os.path.exists(BASE.child('_env').child('env-prod.json')):
    env_path = BASE.child('_env').child('env-prod.json')
elif os.path.exists(BASE.child('_env').child('env-dev.json')):
    env_path = BASE.child('_env').child('env-dev.json')
else:
    env_path = BASE.child('_env').child('env.json')

print "Using env file: %s" % env_path

with open(env_path) as handle:
    ENV = json.load(handle)

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

# SECURITY WARNING: keep the secret key used in production secret!
Ejemplo n.º 37
0
ALLOWED_HOSTS = []

TIME_ZONE = 'Asia/Jerusalem'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = True
USE_L10N = True
USE_TZ = True

MEDIA_ROOT = ''
MEDIA_URL = ''
STATIC_ROOT = ''
STATIC_URL = '/static/'

STATICFILES_DIRS = (PROJECT_DIR.child('records', 'static'), )

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    #   'django.contrib.staticfiles.finders.DefaultStorageFinder',
    # 'djangobower.finders.BowerFinder',
)

SECRET_KEY = 'supersecretkeythatisoverridedlateron'

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
    #     'django.template.loaders.eggs.Loader',
)
Ejemplo n.º 38
0
BASE = Path(__file__).absolute().ancestor(2)

TIME_ZONE = 'America/New_York'

LANGUAGE_CODE = 'en-us'

SITE_ID = 1

USE_I18N = True

USE_L10N = True

USE_TZ = True

MEDIA_ROOT = BASE.child('media')

MEDIA_URL = '/m/'

SOUTH_TESTS_MIGRATE = False

STATIC_ROOT = BASE.ancestor(1).child('static_root')

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    BASE.ancestor(1).child('wsgi').child('static'),
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
Ejemplo n.º 39
0
    def handle_noargs(self, **kwargs):
        try:
            verbosity = int(kwargs['verbosity'])
        except (KeyError, TypeError, ValueError):
            verbosity = 1

        for release in DocumentRelease.objects.all():
            if verbosity >= 1:
                print "Updating %s..." % release

            destdir = Path(settings.DOCS_BUILD_ROOT).child(release.lang, release.version)
            if not destdir.exists():
                destdir.mkdir(parents=True)

            #
            # Update the release from SCM.
            #

            # Make an SCM checkout/update into the destination directory.
            # Do this dynamically in case we add other SCM later.
            getattr(self, 'update_%s' % release.scm)(release.scm_url, destdir)

            #
            # Use Sphinx to build the release docs into JSON and HTML documents.
            #
            for builder in ('json', 'html'):
                # Make the directory for the built files - sphinx-build doesn't
                # do it for us, apparently.
                build_dir = destdir.child('_build', builder)
                if not build_dir.exists():
                    build_dir.mkdir(parents=True)

                # "Shell out" (not exactly, but basically) to sphinx-build.
                if verbosity >= 2:
                    print "  building %s (into %s)" % (builder, build_dir)
                sphinx.cmdline.main(['sphinx-build',
                    '-b', builder,
                    '-q',              # Be vewy qwiet
                    destdir,           # Source file directory
                    build_dir,         # Destination directory
                ])

            #
            # Create a zip file of the HTML build for offline reading.
            # This gets moved into MEDIA_ROOT for downloading.
            #
            html_build_dir = destdir.child('_build', 'html')
            zipfile_name = 'django-docs-%s-%s.zip' % (release.version, release.lang)
            zipfile_path = Path(settings.MEDIA_ROOT).child('docs', zipfile_name)
            if not zipfile_path.parent.exists():
                zipfile_path.parent.mkdir(parents=True)
            if verbosity >= 2:
                print "  build zip (into %s)" % zipfile_path
            with closing(zipfile.ZipFile(zipfile_path, 'w')) as zf:
                for f in html_build_dir.walk(filter=Path.isfile):
                    zf.write(f, html_build_dir.rel_path_to(f))

            #
            # Rebuild the imported document list and search index.
            #
            if not kwargs['reindex']:
                continue

            if verbosity >= 2:
                print "  reindexing..."

            # Build a dict of {path_fragment: document_object}. We'll pop values
            # out of this dict as we go which'll make sure we know which
            # remaining documents need to be deleted (and unindexed) later on.
            documents = dict((doc.path, doc) for doc in release.documents.all())

            # Walk the tree we've just built looking for ".fjson" documents
            # (just JSON, but Sphinx names them weirdly). Each one of those
            # documents gets a corresponding Document object created which
            # we'll then ask Sphinx to reindex.
            #
            # We have to be a bit careful to reverse-engineer the correct
            # relative path component, especially for "index" documents,
            # otherwise the search results will be incorrect.
            json_build_dir = destdir.child('_build', 'json')
            for built_doc in json_build_dir.walk():
                if built_doc.isfile() and built_doc.ext == '.fjson':

                    # Convert the built_doc path which is now an absolute
                    # path (i.e. "/home/docs/en/1.2/_build/ref/models.json")
                    # into a path component (i.e. "ref/models").
                    path = json_build_dir.rel_path_to(built_doc)
                    if path.stem == 'index':
                        path = path.parent
                    path = str(path.parent.child(path.stem))

                    # Read out the content and create a new Document object for
                    # it. We'll strip the HTML tags here (for want of a better
                    # place to do it).
                    with open(built_doc) as fp:
                        json_doc = json.load(fp)
                        try:
                            json_doc['body']  # Just to make sure it exists.
                            title = strip_tags(json_doc['title'])
                        except KeyError, ex:
                            if verbosity >= 2:
                                print "Skipping: %s (no %s)" % (path, ex.args[0])
                            continue

                    doc = documents.pop(path, Document(path=path, release=release))
                    doc.title = title
                    doc.save()
                    haystack.site.update_object(doc)

            # Clean up any remaining documents.
            for doc in documents.values():
                if verbosity >= 2:
                    print "Deleting:", doc
                haystack.site.remove_object(doc)
                doc.delete()
Ejemplo n.º 40
0
LANGUAGE_CODE = LANGUAGES[0][0]

MODELTRANSLATION_DEFAULT_LANGUAGE = LANGUAGE_CODE

MODELTRANSLATION_FALLBACK_LANGUAGES = (LANGUAGES[0][0], LANGUAGES[1][0],
                                       LANGUAGES[2][0], LANGUAGES[3][0])

SITE_ID = 1

USE_I18N = True
USE_L10N = True
USE_TZ = True

MEDIA_URL = '/media/'
MEDIA_ROOT = PROJECT_DIR.child('media')
STATIC_ROOT = PROJECT_DIR.child('static_root')
STATICFILES_ROOT = PROJECT_DIR.child('static')
LOCALE_PATHS = (unicode(PROJECT_DIR.child('locale')), )

STATICFILES_DIRS = [
    (subdir, str(STATICFILES_ROOT.child(subdir))) for subdir in
    ['css', 'img', 'js']]
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
SECRET_KEY = "'piotu34fh89v67b4c2y0[R89N21CB[YUIP'NXREQL;BYCW9"

FIXTURE_DIRS = ("fixtures", )
Ejemplo n.º 41
0
def test_module_create(tmpdir):
    p = Path(str(tmpdir))
    m = Module(p)
    m.create()
    assert ls(p) == ['exercises', 'module.yaml']
    assert yaml.safe_load(open(p.child('module.yaml'))) == {'title': p.name.replace('_', ' ').title()}
Ejemplo n.º 42
0
DEBUG = True
TEMPLATE_DEBUG = DEBUG

# The full path to the hweb directory.
BASE = Path(__file__).absolute().ancestor(2)

ADMINS = (
    # ('Your Name', '*****@*****.**'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': BASE.child('hweb').child('hweb.db'), # 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.
    }
}

CACHES = {
    'default' : {
      'BACKEND' : 'django.core.cache.backends.memcached.MemcachedCache',
      'LOCATION' : '127.0.0.1:11211',
      #'BACKEND' : 'django.core.cache.backends.locmem.LocMemCache',
      #'LOCATION' : 'tmcache',
      'TIMEOUT' : 86400, # Cache for 24h
    }
Ejemplo n.º 43
0
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'pagination.middleware.PaginationMiddleware',
]

ROOT_URLCONF = 'calparkssetup.urls'

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
    #   'django.template.loaders.eggs.Loader',
)

TEMPLATE_DIRS = (PROJECT_DIR.child('templates'), )

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.template.context_processors.debug',
    'django.template.context_processors.request',
    'django.template.context_processors.media',
    'django.template.context_processors.static',
    'django.contrib.auth.context_processors.auth',
    'django.contrib.messages.context_processors.messages',
    'calparkssetup.context_processors.globals',
)

WSGI_APPLICATION = 'calparkssetup.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
Ejemplo n.º 44
0

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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'America/New_York'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_ROOT = PROJECT_PATH.child('static')

# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = PROJECT_PATH.child('site_media')
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/


AWS_ACCESS_KEY_ID = env('AWS_ACCESS_KEY_ID')

AWS_SECRET_ACCESS_KEY = env('AWS_SECRET_ACCESS_KEY')

AWS_STORAGE_BUCKET_NAME = env('AWS_STORAGE_BUCKET_NAME','ipoots-static')

AWS_S3_CUSTOM_DOMAIN = env('AWS_S3_CUSTOM_DOMAIN','ipoots-static.s3.amazonaws.com')
Ejemplo n.º 45
0
        'PASSWORD': SECRETS.get('db_password', ''),
    },
    'trac': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'code.djangoproject',
        'USER': '******',
        'HOST': SECRETS.get('trac_db_host', ''),
        'PASSWORD': SECRETS.get('trac_db_password', ''),
    }
}

DATABASE_ROUTERS = ['tracdb.db_router.TracRouter']

DEFAULT_FROM_EMAIL = "*****@*****.**"

FIXTURE_DIRS = [PROJECT_PACKAGE.child('fixtures')]

INSTALLED_APPS = [
    'accounts',
    'aggregator',
    'blog',
    'cla',
    'contact',
    'dashboard',
    'docs.apps.DocsConfig',
    'legacy',
    'releases',
    'svntogit',
    'tracdb',
    'fundraising',
Ejemplo n.º 46
0
# -*- coding: utf-8 -*-

import sys

from unipath import FSPath as Path

PROJECT_ROOT = Path(__file__).absolute().ancestor(2)
sys.path.insert(0, PROJECT_ROOT.child("apps"))

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ("Your Name", "*****@*****.**"),
)

MANAGERS = ADMINS

TIME_ZONE = None
LANGUAGE_CODE = "en-us"
SITE_ID = 1
USE_I18N = True
USE_L10N = True

STATIC_ROOT = PROJECT_ROOT.child("static")
STATIC_URL = "/static/"
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.
)
Ejemplo n.º 47
0
class CLI(object):
    """
    Usage:
        chucks library <name>
        chucks module <name>
        chucks course <name>
        chucks build [<course>...]
        chucks deploy
        chucks clean
    """

    def __init__(self, stdout=None, stderr=None, libpath=None):
        self.out = stdout or sys.stdout
        self.err = stderr or sys.stderr
        self.library = Library(libpath) if libpath else None
        self.support_path = Path(__file__).parent.child('support')
        self._modules = {}

    def run(self, *argv):
        commands = [line.split()[1] for line in CLI.__doc__.strip().split('\n')[1:]]
        arguments = docopt.docopt(CLI.__doc__, argv=argv, version='Chucks 1.0')
        for command in commands:
            if arguments[command]:
                try:
                    getattr(self, 'do_' + command)(arguments)
                except CLIError as e:
                    self.err.write(e.message)
                    self.rv = 1
                self.rv = 0
        return self.rv

    def do_library(self, arguments):
        """
        Create a new library.
        """
        # FIXME: author, copyright should be flags and/or interactive prompts.
        library = Library(Path(arguments['<name>']).absolute())
        library.create()

    def do_module(self, arguments):
        """
        Create a new module.
        """
        mod = Module(self.library.module_path.child(arguments['<name>']))
        mod.create()

    def do_course(self, arguments):
        """
        Create a new course.
        """
        # FIXME: title, modules from flags/prompt
        course = Course(self.library.course_path.child('%s.yaml' % arguments['<name>']))
        course.create(modules=[str(d.name) for d in self.library.module_path.listdir(filter=DIRS)])

    def do_build(self, arguments):
        # If no course arguments are given, build all the courses.
        if arguments['<course>']:
            try:
                courses = [self.library.courses[c] for c in arguments['<course>']]
            except KeyError:
                raise CLIError("No such course:", c)
        else:
            courses = self.library.courses.values()

        for course in courses:
            self.out.write(u'Building %s\n' % course.title)

            # Make the dest directory.
            dest = self.library.build_path.child(course.slug)
            if dest.exists():
                dest.rmtree()
            dest.mkdir(parents=True)

            # Create the sphinx support directories (_static, _templates) by
            # merging directories from the internal chucks-support directory
            # and from the library's theme if it exists. This has to happen
            # before building the handounts and Sphinx docs because both those
            # steps uses these components.
            for subdir in ('_static', '_templates'):
                chucksdir = self.support_path.child(subdir)
                themedir = self.library.theme_path.child(subdir)
                sources = [d for d in (chucksdir, themedir) if d.exists()]
                if not dest.child(subdir).exists():
                    dest.child(subdir).mkdir()
                fileutils.merge_trees(sources, dest.child(subdir))

            # Write out an auth.json for the deployment step. This should
            # probably actually become part of the deployment step at some point.
            if hasattr(course, 'auth'):
                json.dump(course.auth, open(dest.child('auth.json'), 'w'))

            # Handouts have to go first: Sphinx links to the handouts.
            self._build_handouts(course)
            self._build_sphinx(course)

            # Copy over any extra files to be downloaded. FIXME: This is a nasty
            # hack. Inject these into toc.html as download links?
            for fname in getattr(course, 'downloads', []):
                p = Path(fname)
                if p.isabsolute():
                    src = p
                else:
                    src = self.library.path.child(*p.components())
                shutil.copy(src, dest.child('html'))

    def _build_sphinx(self, course):
        self.out.write(u'  compiling exercises... ')
        dest = self.library.build_path.child(course.slug)

        # conf.py
        confpy = self._get_template('conf.py').render(course=course, library=self.library)
        dest.child('conf.py').write_file(confpy)

        # Index document
        index = sphinxfile.SphinxFile(dest.child('index.txt'))
        index.h1(course.title)
        if hasattr(course, 'subtitle'):
            index.p(course.subtitle)

        index.h2('Handouts')
        index.p(":download:`Download handouts (PDF) <%s.pdf>`" % course.title)

        index.h2('Exercises')

        # Start the toctree; the contents will be written while reading each module.
        index.write('.. toctree::\n   :maxdepth: 2\n   :numbered:\n   :glob:\n\n')

        # For each module collect the exercises.
        for module_name in course.modules:
            module = self.library.modules[module_name]
            exercise_dir = module.path.child('exercises')
            if exercise_dir.exists():
                shutil.copytree(module.path.child('exercises'), dest.child(module_name))
                index.writeline('   %s/index' % module_name)

                # If an index document for the exercise doesn't exist create one
                mod_index_path = dest.child(module_name).child('index.txt')
                if not mod_index_path.exists():
                    mod_index = sphinxfile.SphinxFile(mod_index_path)
                    mod_index.h1(module.title)
                    mod_index.write('.. toctree::\n   :glob:\n\n   *\n\n')
                    mod_index.close()

        index.write('\n')
        index.close()

        self.out.write(u'ok\n')

        # Build us some sphinx.
        self.out.write(u'  building sphinx... ')
        dest.child('html').mkdir()
        r = envoy.run('sphinx-build -b html %s %s/html' % (dest, dest))
        if r.status_code == 0:
            self.out.write(u'ok\n')
            if r.std_err:
                self.out.write(u'  warnings:\n')
                self.out.write(u'\n'.join('    %s' % line for line in r.std_err.split('\n')))
        else:
            self.out.write(u'FAILED:\n')
            self.out.write(r.std_err)

    def _build_handouts(self, course):
        dest = self.library.build_path.child(course.slug)
        modules = [self.library.modules[name] for name in course.modules]

        # Gather the TOC entries by parsing the keynote xml
        self.out.write(u'  gathering toc ... ')
        sections = []
        for module in modules:
            toc = []
            for keydoc in module.path.listdir("*.key"):
                for title, slide_num in keyxml.extract_toc(keydoc):
                    # FIXME: convert slide num to page num - divide by two, but
                    # a bit more than that 'cause of partial pages at the end
                    # of the document. Also see the FIXME below about the
                    # slide numbers.
                    toc.append({'title': title, 'page': slide_num})
            sections.append({'title': module.title, 'toc': toc})
        self.out.write(u'ok\n')

        # Generate a toc.html from the toc.html template, then prince it
        # into a pdf. FIXME: technically I'm violating the prince license
        # here. Will Pisa work? Worth buyting a prince license?
        self.out.write(u'  building toc.pdf ... ')
        toc_html = dest.child('toc.html')
        toc_pdf = dest.child('toc.pdf')
        tmpl = self._get_template('toc.html')
        with io.open(toc_html, 'w', encoding='utf8') as fp:
            fp.write(tmpl.render(
                library = self.library,
                course = course,
                sections = sections,
                today = datetime.date.today(),
            ))

        toc_css = self._get_theme_file('toc.css')
        r = envoy.run('prince %s -s %s -o %s' % (toc_html, toc_css, toc_pdf))
        if r.status_code == 0:
            self.out.write(u'ok\n')
            if r.std_err:
                self.out.write(u'  warnings:\n')
                self.out.write(u'\n'.join('    %s' % line for line in r.std_err.strip().split('\n')))
        else:
            self.out.write(u'FAILED:\n')
            self.out.write(r.std_err)

        # Create a handout pdf
        self.out.write(u'  building handout ... ')
        handouts = pyPdf.PdfFileWriter()

        # FIXME: a great thing to do here would be to add real page numbers
        # (instead of slide numbers) to each section. This is technically
        # possible by creating a "page number" PDF, then "merging" it with the
        # PDFs produced by Keynote. pdfgrid
        # (http://pypi.python.org/pypi/pdfgrid/) does something like this and
        # it looks fairly streightforward. Not sure how fast it'd be, but
        # it'd certainly be pretty awesome for the TOC.

        # Start by adding the doc document.
        pr = pyPdf.PdfFileReader(open(toc_pdf))
        for i in xrange(pr.numPages):
            handouts.addPage(pr.getPage(i))

        # Now add each module's slides. It'd be great if we could automate key
        # -> pdf, but I can't seem to figure out how without requireing UI
        # scripting, which is super brittle. So for now modules need to be
        # exported to PDF by hand :(
        for module in modules:
            for module_pdf in module.path.listdir('*.pdf'):
                pr = pyPdf.PdfFileReader(open(module_pdf))
                for i in xrange(pr.numPages):
                    handouts.addPage(pr.getPage(i))
        handouts.write(open(dest.child('%s.pdf' % course.title), 'w'))

        self.out.write(u'ok\n')

    def _get_template(self, name):
        """
        Load a Jinja template, letting the theme override the default.
        """
        return jinja2.Template(self._get_theme_file(name).read_file())

    def _get_theme_file(self, name):
        """
        Find a file in the theme, falling back to the support dir.
        """
        if self.library.theme_path.child(name).exists():
            return self.library.theme_path.child(name)
        else:
            return self.support_path.child(name)

    def _get_module(self, name):
        if name not in self._modules:
            self._modules[name] = Module(self.library.module_path.child(name))
        return self._modules[name]

    def do_deploy(self, arguments):
        # FIXME: this assumes the app's created and set up and auth works and
        # everything; it would be pretty grand if this command could do that
        # for you. heroku.py would probably help here a lot.
        try:
            app = self.library.app
        except AttributeError:
            raise CLIError("Must define 'app' in library.yaml to deploy.")

        self.out.write(u'Deploying to %s.herokuapp.com...\n' % app)

        # Copy the build dir to a temp location so we can do git-fu without
        # leaving a trail.
        self.out.write(u'  staging files for deploy... ')
        tempdir = Path(tempfile.mkdtemp()).child('chucks')
        shutil.copytree(self.library.build_path, tempdir)

        # Copy over the heroku bits
        for app_bit in self.support_path.child('heroku').listdir():
            shutil.copy(app_bit, tempdir)

        # Now make this thing into a git repo. I don't know how to make
        # this work without changing the cwd...
        os.chdir(tempdir)
        envoy.run('git init')
        envoy.run('git add .')
        envoy.run('git commit -m "deploy"')
        envoy.run('git remote add heroku [email protected]:%s.git' % app)
        self.out.write(u' ok\n')

        # Push that bad boy.
        self.out.write(u'  pushing to heroku ... ')
        r = envoy.run(u'git push --force heroku master')
        if r.status_code == 0:
            self.out.write(u' ok\n')
        else:
            self.out.write(u' FAILED:\n')
            self.out.write(r.std_err)

        # Clean up.
        shutil.rmtree(tempdir.parent)

    def do_clean(self, arguments):
        self.library.build_path.rmtree()
        self.library.build_path.mkdir()
Ejemplo n.º 48
0
USE_L10N = True

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

# 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 = ''

# 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 = PROJECT_DIR.child('static_root')

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

# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'

# Additional locations of static files
# Additional locations of static files
STATICFILES_DIRS = (
        str(PROJECT_DIR.child('static')),
)
Ejemplo n.º 49
0
import os
import dj_database_url

from unipath import FSPath as Path


def env_or_default(NAME, default):
    return os.environ.get(NAME, default)


PROJECT_ROOT = Path(__file__).ancestor(3)
PACKAGE_ROOT = PROJECT_ROOT.child('djangocon')

BASE_DIR = PACKAGE_ROOT

DEBUG = bool(int(os.environ.get("DEBUG", "1")))

DATABASES = {
    "default":
    dj_database_url.config(default="postgres://localhost/djangocon2016")
}

ALLOWED_HOSTS = [
    os.environ.get("GONDOR_INSTANCE_DOMAIN"), "2016.djangocon.us",
    "www.djangocon.us", "localhost',"
]

# 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
Ejemplo n.º 50
0
LANGUAGE_CODE = LANGUAGES[0][0]

MODELTRANSLATION_DEFAULT_LANGUAGE = LANGUAGE_CODE

MODELTRANSLATION_FALLBACK_LANGUAGES = (LANGUAGES[0][0], LANGUAGES[1][0],
                                       LANGUAGES[2][0], LANGUAGES[3][0])

SITE_ID = 1

USE_I18N = True
USE_L10N = True
USE_TZ = True

MEDIA_URL = '/media/'
MEDIA_ROOT = PROJECT_DIR.child('media')
STATIC_ROOT = PROJECT_DIR.child('static_root')
STATICFILES_ROOT = PROJECT_DIR.child('static')
LOCALE_PATHS = (unicode(PROJECT_DIR.child('locale')), )

STATICFILES_DIRS = [(subdir, str(STATICFILES_ROOT.child(subdir)))
                    for subdir in ['css', 'img', 'js']]
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    #    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
SECRET_KEY = "'piotu34fh89v67b4c2y0[R89N21CB[YUIP'NXREQL;BYCW9"

FIXTURE_DIRS = ("fixtures", )
TEMPLATE_LOADERS = (
Ejemplo n.º 51
0
import os
import platform

from unipath import FSPath as Path


### Utilities

# The full path to the repository root.
BASE = Path(__file__).absolute().ancestor(2)

# Far too clever trick to know if we're running on the deployment server.
PRODUCTION = ('DJANGOPROJECT_DEBUG' not in os.environ)

# It's a secret to everybody
with open(BASE.child('secrets.json')) as handle:
    SECRETS = json.load(handle)


### Django settings

ADMINS = (
    ('Adrian Holovaty', '*****@*****.**'),
    ('Jacob Kaplan-Moss', '*****@*****.**'),
)

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': SECRETS.get('memcached_host', '127.0.0.1:11211'),
    } if PRODUCTION else {
Ejemplo n.º 52
0
TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth",
                                "django.core.context_processors.debug",
                                "django.core.context_processors.i18n",
                                "django.core.context_processors.media",
                                "django.core.context_processors.static",
                                "django.contrib.messages.context_processors.messages",
                                "findapartner.utils.context_processors.social_context")

MEDIA_ROOT = PROJECT_DIR.parent.child('data')
MEDIA_URL = '/media/'

STATIC_ROOT = PROJECT_DIR.parent.child('static_root')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    str(PROJECT_DIR.child('static')),
)
ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

SECRET_KEY = 'c120v)_7u%=(nfn*bjpswynqbr_l(1q28t=0x#&1ed*m@gqhd1'

# 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',
Ejemplo n.º 53
0
from django.core.exceptions import ImproperlyConfigured

def get_environ(key):
    ''' KeyError would not be properly raised by manage.py '''
    try:
        return os.environ[key]
    except KeyError:
        raise ImproperlyConfigured("Environment variable '%s' is not set" % key)

SECRET_KEY = get_environ('SECRET_KEY')


# The full path to the root
# The base file should be located under django_twisted/settings/base.py
BASE = Path(__file__).absolute().ancestor(3)
DATA_DIR = BASE.child('data')

DEBUG = True
# Determine if we are on production
ON_PROD = 'apache' in getpass.getuser()


ADMINS = (
    ('Conan Li', '*****@*****.**'),
)

MANAGERS = ADMINS

DEFAULT_FROM_EMAIL = "noreply@django_twisted.com"

if not ON_PROD:
        "formatter": "full",
        "level": "DEBUG",
        "class": "logging.handlers.TimedRotatingFileHandler",
        "filename": "/var/log/django_website/website.log",
        "when": "D",
        "interval": 7,
        "backupCount": 5,
    }
    LOGGING["loggers"]["django.request"]["handlers"].append("logfile")


MANAGERS = (
    ('Jacob Kaplan-Moss', '*****@*****.**'),
)

MEDIA_ROOT = BASE.child('media')

MEDIA_URL = '/m/'

SECRET_KEY = str(SECRETS['secret_key'])

SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTOCOL", "https")

SERVER_EMAIL = "*****@*****.**"

SESSION_COOKIE_SECURE = PRODUCTION

SESSION_COOKIE_HTTPONLY = True

STATICFILES_DIRS = [BASE.child('static')]
Ejemplo n.º 55
0
        'PASSWORD': SECRETS.get('db_password', ''),
    },
    'trac': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'code.djangoproject',
        'USER': '******',
        'HOST': SECRETS.get('trac_db_host', ''),
        'PASSWORD': SECRETS.get('trac_db_password', ''),
    }
}

DATABASE_ROUTERS = ['tracdb.db_router.TracRouter']

DEFAULT_FROM_EMAIL = "*****@*****.**"

FIXTURE_DIRS = [PROJECT_PACKAGE.child('fixtures')]

INSTALLED_APPS = [
    'accounts',
    'aggregator',
    'blog',
    'cla',
    'contact',
    'dashboard',
    'docs.apps.DocsConfig',
    'legacy',
    'releases',
    'svntogit',
    'tracdb',
    'fundraising',
    'flat',