view mp3/management/commands/import_old_mp3.py @ 71:e2868ad47a1e

For Django 1.4, using the new manage.py.
author Brian Neal <bgneal@gmail.com>
date Sat, 14 Apr 2012 16:40:29 -0500
parents madeira/mp3/management/commands/import_old_mp3.py@b8a71c767dc0
children b7cdfdde3999
line wrap: on
line source
"""
import_old_mp3.py - For importing mp3 data from the older version of this
website.

"""
import datetime

from django.core.management.base import LabelCommand
from django.utils import simplejson as json
from django.utils.html import linebreaks

from mp3.models import Collection, Song


class Command(LabelCommand):
    args = '<filename filename ...>'
    help = 'Imports older mp3 & mp3 sets in JSON format'

    collections = {}

    def handle_label(self, filename, **options):
        """
        Process the file of older mp3 & mp3 sets in JSON. Convert to the new
        model scheme.

        """
        with open(filename, 'rb') as f:
            items = json.load(f)

        for item in items:
            if item['model'] == 'band.mp3_set':
                self.process_mp3_set(item)

        for item in items:
            if item['model'] == 'band.mp3':
                self.process_mp3(item)

    def process_mp3_set(self, item):

        fields = item['fields']

        description = linebreaks(fields['text'].strip())

        coll = Collection(
                id=item['pk'],
                title=fields['title'].strip(),
                date_added=datetime.datetime.strptime(fields['date'], '%Y-%m-%d'),
                description=description)

        coll.save()
        self.collections[coll.pk] = coll

    def process_mp3(self, item):

        fields = item['fields']

        song = Song(
                id=item['pk'],
                title=fields['title'].strip(),
                description=fields['desc'].strip(),
                file=fields['file'],
                collection=self.collections[fields['mp3_set']],
                )
        song.save()