view mp3/management/commands/import_old_mp3.py @ 77:d2e32fa2dc99

Update fabric file for Django 1.4 directory changes.
author Brian Neal <bgneal@gmail.com>
date Sat, 28 Jul 2012 22:25:00 -0500
parents e2868ad47a1e
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()