Commit 8c5f27e0 authored by fred's avatar fred

add command to import from (custom) drupal export

parent 0f2e904c
import datetime
import isodate
import json
import requests
from django.conf import settings
from django.core.files import File
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from django.core.management.base import BaseCommand, CommandError
from django.utils.text import slugify
from django.utils.timezone import make_naive
from ...models import Emission, Episode, Diffusion
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('filename', metavar='FILENAME', type=str,
help='name of file to import')
def handle(self, filename, verbosity, **options):
self.verbose = (verbosity > 1)
for episode_data in json.load(open(filename)).get('episodes').values():
if not episode_data.get('title'):
continue
if not episode_data.get('emission'):
continue
if not episode_data.get('text') and not episode_data.get('sound'):
continue
emission, created = Emission.objects.get_or_create(
slug=slugify(episode_data['emission']),
defaults={'title': episode_data['emission']})
if created:
emission.save()
episode, created = Episode.objects.get_or_create(
slug=episode_data['path'].split('/')[-1],
emission=emission)
episode.title = episode_data['title']
episode.text = episode_data['text']
episode.creation_timestamp = isodate.parse_datetime(
episode_data['pub_date'].replace(' ', 'T', 1).replace(' ', ''))
if not settings.USE_TZ:
episode.creation_timestamp = make_naive(episode.creation_timestamp)
start_datetime = datetime.datetime.combine(
datetime.datetime.strptime(episode_data['start_date'], '%d/%m/%Y').date(),
datetime.datetime.strptime(episode_data['start_time'], '%H:%M').time())
if episode_data['end_time']:
end_datetime = datetime.datetime.combine(
start_datetime.date(),
datetime.datetime.strptime(episode_data['end_time'], '%H:%M').time())
else:
end_datetime = start_datetime # fake
if end_datetime < start_datetime:
end_datetime = end_datetime + datetime.timedelta(days=1)
episode.duration = (end_datetime - start_datetime).seconds // 60
episode.save()
if not episode.image and episode_data.get('image'):
orig_path = 'images/%s/%s' % (emission.slug, episode_data.get('image').split('/')[-1])
if default_storage.exists(orig_path):
path = orig_path
else:
path = default_storage.save(
'images/%s/%s' % (
emission.slug,
episode_data.get('image').split('/')[-1]),
ContentFile(requests.get(episode_data.get('image')).content))
episode.image = default_storage.open(path)
try:
episode.save()
except OSError: # OSError: cannot identify image file
episode.image = None
episode.save()
if episode.diffusion_set.count() == 0:
diffusion = Diffusion(episode=episode)
diffusion.datetime = start_datetime
diffusion.save()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment