Skip to content

Commit

Permalink
Merge branch 'release/v2.4.0'
Browse files Browse the repository at this point in the history
  • Loading branch information
wolph committed May 30, 2017
2 parents 194667a + 97204a8 commit 1085457
Show file tree
Hide file tree
Showing 4 changed files with 127 additions and 16 deletions.
2 changes: 1 addition & 1 deletion django_utils/__about__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
__package_name__ = 'django-utils2'
__version__ = '2.3.0'
__version__ = '2.4.0'
__author__ = 'Rick van Hattem'
__author_email__ = 'Rick.van.Hattem@Fawo.nl'
__description__ = (
Expand Down
82 changes: 73 additions & 9 deletions django_utils/management/commands/settings.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,93 @@
from __future__ import print_function

from . import base_command
import six
import json
import pprint

from django.conf import settings

from . import base_command


def json_default(obj):
return str(obj)


class Command(base_command.CustomBaseCommand):
help = '''Get a list of the current settings, any arguments given will be
used to match the settings name (case insensitive).
'''
can_import_settings = True
requires_model_validation = False
output_types = ['pprint', 'print', 'json', 'csv']

def add_arguments(self, parser):
parser.add_argument('keys', nargs='+')
parser.add_argument(
'-o', '--output-type', default='pprint', choices=self.output_types)
parser.add_argument('-k', '--show-keys', action='store_true')

def render_output(self, data, output_type='pprint', show_keys=False,
**options):
if output_type == 'pprint':
if show_keys:
pprint.pprint(data)
else:
for key, values in data.items():
pprint.pprint(values)

elif output_type == 'print':
for key, values in data.items():
if show_keys:
print(key, end='')
print(values)

elif output_type == 'csv':
for key, values in data.items():
out = []
if show_keys:
out.append(key)

if isinstance(values, six.string_types):
values = [values]
elif isinstance(values, dict):
values = ['%s=%s' % item for item in values.items()]
else:
try:
values = [str(value) for value in values]
except TypeError:
values = [str(values)]

for i, value in enumerate(values):
if '"' in value:
value = value.replace('"', '""')

if ' ' in value or ',' in value:
value = '"%s"' % value

values[i] = value

out += values
print(','.join(out))

elif output_type == 'json':
print(json.dumps(data, indent=4, sort_keys=True,
default=json_default))

def handle(self, *args, **options):
from django.conf import settings
args = list(map(str.upper, args))
for k in dir(settings):
if k.upper() == k:
v = getattr(settings, k)
super(Command, self).handle(*args, **options)
args = list(map(str.upper, options.get('keys', args)))
data = dict()
for key in dir(settings):
if key.isupper():
value = getattr(settings, key)
found = False
for arg in args:
if arg in k:
if arg in key:
found = True
break

if found:
pprint.pprint(v)
data[key] = value

super(Command, self).handle(*args, **options)
self.render_output(data, **options)
16 changes: 16 additions & 0 deletions django_utils/view_decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,22 @@ def _process_response(request, response, response_class):
if request.ajax:
if isinstance(response, models.query.QuerySet):
output = serializers.serialize('json', response)
elif request.GET.get('debug'):
from django.core.serializers import json as django_json
output = json.dumps(
response,
indent=4,
sort_keys=True,
cls=django_json.DjangoJSONEncoder,
default=json_default_handler,
)
else:
output = json.dumps(response, default=json_default_handler)

callback = request.GET.get('callback', False)
if callback:
output = '%s(%s)' % (callback, output)

if request.GET.get('debug'):
title = 'Rendering %(view)r in module %(app)r' % (
request.context)
Expand All @@ -79,6 +89,12 @@ def _process_response(request, response, response_class):
<html>
<head>
<title>%s</title>
<style>
textarea{
width: 100%%;
height: 100%%;
}
</style>
</head>
<body>
<textarea>%s</textarea>
Expand Down
43 changes: 37 additions & 6 deletions tests/test_commands.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,45 @@
import pytest
import argparse
import datetime
from django_utils.management import commands


def test_settings_command_empty():
command = commands.settings.Command()
command.handle()
@pytest.fixture
def settings_command():
return commands.settings.Command()


def test_settings_command_empty(settings_command):
settings_command.add_arguments(argparse.ArgumentParser())
settings_command.handle()


def test_settings_command_no_type(settings_command):
settings_command.render_output(None, output_type=None)


@pytest.mark.parametrize('output_type', commands.settings.Command.output_types)
@pytest.mark.parametrize('show_keys', [True, False])
def test_settings_command_arg(settings_command, output_type, show_keys):
settings_command.handle('a', show_keys=show_keys, output_type=output_type)


def test_settings_command_arg():
command = commands.settings.Command()
command.handle('debug')
@pytest.mark.parametrize('output_type', commands.settings.Command.output_types)
@pytest.mark.parametrize('show_keys', [True, False])
def test_settings_command_data(settings_command, output_type, show_keys):
# Test difficult data types
data = dict(
a=['spam"eggs"test,something'],
b=['spam"eggs"'],
c=['spam,eggs'],
d='spam"eggs"test,something',
e='spam"eggs"',
f='spam,eggs',
g=datetime.datetime.now(),
h=datetime.timedelta(),
i=datetime.date.today(),
)
settings_command.render_output(data, output_type, show_keys)


def test_admin_autogen_command():
Expand Down

0 comments on commit 1085457

Please sign in to comment.