Exemple #1
0
def resources_dumpdata(request):
    response = HttpResponse(content_type="application/json")
    dumpdata.Command(stdout=response).run_from_argv([
        'manage.py', 'dumpdata', 'clist.resource', 'ranking.module',
        '--format', 'json'
    ])
    return response
Exemple #2
0
    def test_restore(self):
        with self.open_dump() as dump:
            dumprestore.load(dump)

        result = dumpdata.Command().handle(format='json', indent=4) + '\n'
        with self.open_fixture() as reference_fixture:
            self.assertTextEqual(reference_fixture.read(), result)
Exemple #3
0
def services_dumpdata(request):
    out = StringIO()
    dumpdata.Command(stdout=out).run_from_argv(
        ['manage.py', 'dumpdata', 'my_oauth.service', '--format', 'json'])
    services = json.loads(out.getvalue())
    for service in services:
        service['fields']['secret'] = None
        service['fields']['app_id'] = None
    return HttpResponse(json.dumps(services), content_type="application/json")
Exemple #4
0
 def handle(self, *args, **options):
     s3_client = boto3.client(
         's3',
         aws_access_key_id=settings.AWS_ACCESS_KEY_ID,
         aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY)
     out = StringIO()
     management.call_command(dumpdata.Command(), 'app', stdout=out)
     s3_client.put_object(Body=out.getvalue(),
                          Bucket='abr-backups',
                          Key='new/db-{}.json'.format(datetime.now().day))
Exemple #5
0
 def test_serialization(self):
     """
     Tests that we can serialize and deserialize.
     """
     from django.core import serializers
     from django.core.management.commands import dumpdata
     out = dumpdata.Command().handle("tests")
     objects = dict((o.object._meta.object_name, o.object)
                    for o in serializers.deserialize("json", out))
     self.assertEqual(self.one, objects['One'])
     self.assertEqual(self.other, objects['Other'])
     self.assertEqual(self.one, objects["One_others"].one)
     self.assertEqual(self.other, objects["One_others"].other)
Exemple #6
0
def generate_seed(request: HttpRequest):
    if str(request.user).__eq__("AnonymousUser"):
        return HttpResponseBadRequest()

    if not request.user.is_superuser:
        message_error(request, "You're not allowed to do that, little burglar!")
        return redirect('/api/admin/')

    try:
        with open('data.json', 'w') as f:
            call_command(dumpdata.Command(), '--natural-foreign', '--natural-primary', '--indent=4', stdout=f)
        message_info(request, 'Toate informaţiile din baza de date au fost salvate în fişierul data.json! '
                              'Îl poţi descărca prin "Descarcă seed"')
    except Exception as err:
        message_error(request, f'A apărut o eroare! Datele nu au putut fi exportate. Error stack: {err}')

    return redirect('/api/admin/')
    def handle(self, **options):
        if options["model"] not in ALL_MODELS:
            raise CommandError(
                f"Unknown model {options['model']}. \n\nRefer to help for supported values"
            )

        try:
            with StringIO() as status:
                management.call_command(
                    dumpdata.Command(),
                    options["model"],
                    format="json",
                    indent=2,
                    stdout=status,
                )

                json_obj = json.loads(status.getvalue())
                data = self._format_from_django_object(json_obj)

                if options["model"] == MODEL_GOV_DEPT:
                    data = self._serialise_gov_department(data)

                with open(options["csvfile"], "w", newline="") as fp:
                    if len(data):
                        header = list(data[0].keys())
                        writer = csv.DictWriter(fp, fieldnames=header)
                        writer.writeheader()

                        writer.writerows(data)

                self.stdout.write(
                    self.style.SUCCESS(
                        f"Successfully extracted data from {options['model']} to {options['csvfile']}"
                    ))
        except Exception as e:
            raise CommandError(f"\n{str(e)}")