Skip to content

Commit

Permalink
fixed problem with uncode
Browse files Browse the repository at this point in the history
  • Loading branch information
SeanHayes committed May 24, 2011
1 parent 2a69d99 commit e05ba34
Show file tree
Hide file tree
Showing 14 changed files with 315 additions and 3 deletions.
4 changes: 3 additions & 1 deletion LICENSE
@@ -1,4 +1,6 @@
Copyright (c) 2010, Seán Hayes Some code in django_config_gen/management/commands/config_gen.py was taken from the file django/template/context.py in Django, which is under a BSD license and is the copyright of the Django Software Foundation.

Copyright (c) 2010, 2011 Seán Hayes
All rights reserved. All rights reserved.


Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Expand Down
7 changes: 6 additions & 1 deletion django_config_gen/__init__.py
@@ -1,3 +1,8 @@
VERSION = (1, 0, 5) # -*- coding: utf-8 -*-
#Copyright (C) 2010, 2011 Seán Hayes
#
#Licensed under a BSD 3-Clause License. See LICENSE file.

VERSION = (1, 0, 6)


__version__ = "".join([".".join(map(str, VERSION[0:3])), "".join(VERSION[3:])]) __version__ = "".join([".".join(map(str, VERSION[0:3])), "".join(VERSION[3:])])
5 changes: 5 additions & 0 deletions django_config_gen/management/__init__.py
@@ -1,3 +1,8 @@
# -*- coding: utf-8 -*-
#Copyright (C) 2010, 2011 Seán Hayes
#
#Licensed under a BSD 3-Clause License. See LICENSE file.

from django.conf import settings from django.conf import settings
import os import os
import defaults import defaults
Expand Down
8 changes: 7 additions & 1 deletion django_config_gen/management/commands/config_gen.py
@@ -1,3 +1,8 @@
# -*- coding: utf-8 -*-
#Copyright (C) 2010, 2011 Seán Hayes
#
#Licensed under a BSD 3-Clause License. See LICENSE file.

from django.core.management.base import NoArgsCommand, CommandError from django.core.management.base import NoArgsCommand, CommandError
from django.conf import settings from django.conf import settings
from django.template.loader import render_to_string from django.template.loader import render_to_string
Expand Down Expand Up @@ -76,7 +81,8 @@ def create_nodes(self, rel_path, dir_list):
fi.close() fi.close()


fo = open(g_filename, 'w') fo = open(g_filename, 'w')
fo.write(t.render(self.ctx)) generated_text = t.render(self.ctx).encode('utf-8')
fo.write(generated_text)
fo.close() fo.close()
elif os.path.isdir(t_filename): elif os.path.isdir(t_filename):
if not os.path.exists(g_filename): if not os.path.exists(g_filename):
Expand Down
5 changes: 5 additions & 0 deletions django_config_gen/management/commands/print_settings.py
@@ -1,3 +1,8 @@
# -*- coding: utf-8 -*-
#Copyright (C) 2010, 2011 Seán Hayes
#
#Licensed under a BSD 3-Clause License. See LICENSE file.

from django.core.management.base import NoArgsCommand, CommandError from django.core.management.base import NoArgsCommand, CommandError
from django.conf import settings from django.conf import settings
from .. import patch_settings from .. import patch_settings
Expand Down
5 changes: 5 additions & 0 deletions django_config_gen/management/defaults.py
@@ -1,3 +1,8 @@
# -*- coding: utf-8 -*-
#Copyright (C) 2010, 2011 Seán Hayes
#
#Licensed under a BSD 3-Clause License. See LICENSE file.

import __main__ import __main__
import os import os
from django.contrib.sites.models import Site from django.contrib.sites.models import Site
Expand Down
Empty file added django_config_gen/models.py
Empty file.
78 changes: 78 additions & 0 deletions django_config_gen/tests/__init__.py
@@ -0,0 +1,78 @@
# -*- coding: utf-8 -*-
#Copyright (C) 2010, 2011 Seán Hayes
#
#Licensed under a BSD 3-Clause License. See LICENSE file.

import os
import shutil
import tempfile

from django.conf import settings
from django.core.management import call_command
from django.test import TestCase

from django_config_gen.management import patch_settings

class CallCommandTestCase(TestCase):
def setUp(self):
self.tmp_files = []

if hasattr(settings, 'CONFIG_GEN_TEMPLATES_DIR'):
self.old_CONFIG_GEN_TEMPLATES_DIR = settings.CONFIG_GEN_TEMPLATES_DIR
if hasattr(settings, 'CONFIG_GEN_GENERATED_DIR'):
self.old_CONFIG_GEN_GENERATED_DIR = settings.CONFIG_GEN_GENERATED_DIR

self.config_dir = os.path.join(tempfile.gettempdir(), 'config')

settings.CONFIG_GEN_TEMPLATES_DIR = os.path.join(self.config_dir, 'templates')
settings.CONFIG_GEN_GENERATED_DIR = os.path.join(self.config_dir, 'generated')

def test_handles_unicode_in_file_contents(self):
"Make sure unicode is supported in file contents."

test_file_name = 'test_file'
test_file_template_path = os.path.join(settings.CONFIG_GEN_TEMPLATES_DIR, test_file_name)
test_file_generated_path = os.path.join(settings.CONFIG_GEN_GENERATED_DIR, test_file_name)
self.tmp_files.append(test_file_template_path)
self.tmp_files.append(test_file_generated_path)

if not os.path.exists(settings.CONFIG_GEN_TEMPLATES_DIR):
os.makedirs(settings.CONFIG_GEN_TEMPLATES_DIR)

config_template = u"""
This is some text with unicode!
-Seán Hayes
""".encode('utf-8')

fo = open(test_file_template_path, 'w')
fo.write(config_template)
fo.close()

self.assertFalse(os.path.exists(test_file_generated_path))

call_command('config_gen')

fi = open(test_file_generated_path, 'r')
generated_text = fi.read()
fi.close()

self.assertTrue(os.path.exists(test_file_generated_path))
#make sure the unicode didn't get silently mangled
self.assertEqual(config_template, generated_text)


def tearDown(self):
for tmp_file in self.tmp_files:
os.remove(tmp_file)

shutil.rmtree(self.config_dir)

if hasattr(self, 'old_CONFIG_GEN_TEMPLATES_DIR'):
settings.CONFIG_GEN_TEMPLATES_DIR = self.old_CONFIG_GEN_TEMPLATES_DIR
else:
delattr(settings, 'CONFIG_GEN_TEMPLATES_DIR')
if hasattr(self, 'old_CONFIG_GEN_GENERATED_DIR'):
settings.CONFIG_GEN_GENERATED_DIR = self.old_CONFIG_GEN_GENERATED_DIR
else:
delattr(settings, 'CONFIG_GEN_GENERATED_DIR')

Empty file.
14 changes: 14 additions & 0 deletions django_config_gen_test_project/manage.py
@@ -0,0 +1,14 @@
#!/usr/bin/env python
from django.core.management import execute_manager
import imp
try:
imp.find_module('settings') # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__)
sys.exit(1)

import settings

if __name__ == "__main__":
execute_manager(settings)
14 changes: 14 additions & 0 deletions django_config_gen_test_project/runtests.py
@@ -0,0 +1,14 @@
#!/usr/bin/env python
import os, sys
import settings
from django.core.management import call_command

os.environ['DJANGO_SETTINGS_MODULE'] = '%s.settings' % settings.PROJECT_MODULE
sys.path.insert(0, settings.PROJECT_PARENT_DIR)

def runtests():
call_command('test', 'django_config_gen')
sys.exit()

if __name__ == '__main__':
runtests()
156 changes: 156 additions & 0 deletions django_config_gen_test_project/settings.py
@@ -0,0 +1,156 @@
# Django settings for django_config_gen_test_project project.

import os
import django.conf.global_settings as DEFAULT_SETTINGS

PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
PROJECT_PARENT_DIR = os.path.dirname(PROJECT_ROOT)

PROJECT_MODULE = __name__[:__name__.rfind('.')] if '.' in __name__ else PROJECT_ROOT.split(os.sep)[-1]

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
# ('Your Name', 'your_email@example.com'),
)

MANAGERS = ADMINS

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # 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 = 'America/Chicago'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
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 = ''

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

# 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
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 = ')v)jqp7voco+%3-9&75)i=u_j8u)+q1-3e&#fx=y#n+jk=!hxt'

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

ROOT_URLCONF = 'django_config_gen_test_project.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',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',

#app that we want to test
'django_config_gen',
)

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
17 changes: 17 additions & 0 deletions django_config_gen_test_project/urls.py
@@ -0,0 +1,17 @@
from django.conf.urls.defaults import patterns, include, url

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
# Examples:
# url(r'^$', 'django_config_gen_test_project.views.home', name='home'),
# url(r'^django_config_gen_test_project/', include('django_config_gen_test_project.foo.urls')),

# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
)
5 changes: 5 additions & 0 deletions setup.py
Expand Up @@ -4,6 +4,9 @@
from setuptools import setup from setuptools import setup
import django_config_gen import django_config_gen


package_name = 'django_config_gen'
test_package_name = '%s_test_project' % package_name

setup(name='django-config-gen', setup(name='django-config-gen',
version=django_config_gen.__version__, version=django_config_gen.__version__,
description="Generates configuration files for Apache, Nginx, etc. using values in settings.py and the Django template system. You can write your own templates for whatever text based config file you need.", description="Generates configuration files for Apache, Nginx, etc. using values in settings.py and the Django template system. You can write your own templates for whatever text based config file you need.",
Expand Down Expand Up @@ -31,9 +34,11 @@
license='BSD', license='BSD',
packages=[ packages=[
'django_config_gen', 'django_config_gen',
'django_config_gen_test_project',
], ],
package_data={'django_config_gen': ['management/commands/example_templates/*']}, package_data={'django_config_gen': ['management/commands/example_templates/*']},
include_package_data=True, include_package_data=True,
install_requires=['Django>=1.2',], install_requires=['Django>=1.2',],
test_suite = '%s.runtests.runtests' % test_package_name,
) )


0 comments on commit e05ba34

Please sign in to comment.