Login

Do Not Escape Characters When Using dumpdata Command (Tested in Django 1.11)

Author:
oldcai
Posted:
October 7, 2017
Language:
Python
Version:
1.10
Tags:
pretty dumpdata pretty-print
Score:
0 (after 0 ratings)

Adds --pretty option to django ./manage.py dumpdata command, which produces pretty utf-8 strings instead of ugly unicode-escaped s**t:

$ ./manage.py dumpdata app.pricingplan --indent=1

[
 {
  "pk": 1, 
  "model": "app.pricingplan", 
  "fields": {
   "name": "\u0411\u0430\u0437\u043e\u0432\u044b\u0439", 
  }
 }, 
 {
  "pk": 2, 
  "model": "app.pricingplan", 
  "fields": {
   "name": "\u0425\u0443\u044f\u0437\u043e\u0432\u044b\u0439", 
  }
 }
]

./manage.py dumpdata app.pricingplan --indent=1 --pretty

[
 {
  "pk": 1, 
  "model": "app.pricingplan", 
  "fields": {
   "name": "Базовый", 
  }
 }, 
 {
  "pk": 2, 
  "model": "app.pricingplan", 
  "fields": {
   "name": "Хуязовый", 
  }
 }
]

Forked from an old versions snippet

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from io import StringIO
from django.core.management.commands.dumpdata import Command as Dumpdata


class Command(Dumpdata):
    def add_arguments(self, parser):
        super(Command, self).add_arguments(parser)
        parser.add_argument(
            '--pretty', default=False, action='store_true',
            dest='pretty', help='Avoid unicode escape symbols'
        )

    def handle(self, *args, **kwargs):
        captcha_stdout = StringIO()
        old_stdout = self.stdout
        self.stdout = captcha_stdout
        super(Command, self).handle(*args, **kwargs)
        captcha_stdout.seek(0)
        data = captcha_stdout.read()
        data = data.encode()
        if kwargs.get('pretty'):
            data = data.decode("unicode_escape").encode("utf-8")
        old_stdout.write(data.decode('utf-8'))

More like this

Comments

Please login first before commenting.