In [1]:
%config InlineBackend.figure_format = 'retina'
%load_ext autoreload
%autoreload 1

In [2]:
from cast.models import (
    Blog as CastBlog,
    Image,
    Video,
    File,
    Post,
    Gallery,
)

In [3]:
from homepage.blogs.models import (
    Blog,
    BlogImage,
    BlogFile,
    BlogGallery,
    BlogPost,
    BlogVideo,
)

Migrate Blogs


In [4]:
CastBlog.objects.all().delete()


Out[4]:
(0, {})

In [96]:
%%time
blog_attrs = ("pk", "user", "title", "description", "slug", "created", "modified")
cast_blogs = []
for bl in Blog.objects.all():
    params = {attr: getattr(bl, attr) for attr in blog_attrs}
    cast_blogs.append(CastBlog(**params))


CPU times: user 3.35 ms, sys: 1.42 ms, total: 4.77 ms
Wall time: 3.58 ms

In [97]:
%%time
created = CastBlog.objects.bulk_create(cast_blogs)


CPU times: user 1.48 ms, sys: 1.45 ms, total: 2.93 ms
Wall time: 40.9 ms

In [98]:
CastBlog.objects.count()


Out[98]:
2

Migrate Images


In [99]:
Image.objects.all().delete()


Out[99]:
(1077, {'cast.Gallery_images': 507, 'cast.Post_images': 0, 'cast.Image': 570})

In [100]:
%%time
image_attrs = ("pk", "original", "original_height", "original_width", "user", "created", "modified")
cast_images = []
for bi in BlogImage.objects.all():
    params = {attr: getattr(bi, attr) for attr in image_attrs}
    cast_images.append(Image(**params))


CPU times: user 406 ms, sys: 11.8 ms, total: 418 ms
Wall time: 495 ms

In [101]:
%%time
created = Image.objects.bulk_create(cast_images)


CPU times: user 76.6 ms, sys: 2.93 ms, total: 79.6 ms
Wall time: 102 ms

In [102]:
Image.objects.count()


Out[102]:
570

Migrate Videos


In [103]:
Video.objects.all().delete()


Out[103]:
(49, {'cast.Post_videos': 0, 'cast.Video': 49})

In [104]:
%%time
video_attrs = ("pk", "original", "poster", "poster_seconds", "user", "created", "modified")
cast_videos = []
for bv in BlogVideo.objects.all():
    params = {attr: getattr(bv, attr) for attr in video_attrs}
    cast_videos.append(Video(**params))


CPU times: user 41.4 ms, sys: 2.67 ms, total: 44.1 ms
Wall time: 50.1 ms

In [105]:
%%time
created = Video.objects.bulk_create(cast_videos)


CPU times: user 4.93 ms, sys: 1.15 ms, total: 6.09 ms
Wall time: 86.6 ms

In [106]:
Video.objects.count()


Out[106]:
49

Migrate Files


In [107]:
File.objects.all().delete()


Out[107]:
(1, {'cast.File': 1})

In [108]:
%%time
file_attrs = ("pk", "original", "user", "created", "modified")
cast_files = []
for bf in BlogFile.objects.all():
    params = {attr: getattr(bf, attr) for attr in file_attrs}
    cast_files.append(File(**params))


CPU times: user 2.29 ms, sys: 822 µs, total: 3.11 ms
Wall time: 2.37 ms

In [109]:
%%time
created = File.objects.bulk_create(cast_files)


CPU times: user 1.17 ms, sys: 1.34 ms, total: 2.51 ms
Wall time: 41.3 ms

In [110]:
File.objects.count()


Out[110]:
1

Migrate Galleries


In [111]:
Gallery.objects.all().delete()


Out[111]:
(66, {'cast.Gallery_images': 0, 'cast.Post_galleries': 0, 'cast.Gallery': 66})

In [112]:
%%time
gallery_attrs = ("pk", "user", "created", "modified")
for bg in BlogGallery.objects.all():
    params = {attr: getattr(bg, attr) for attr in gallery_attrs}
    gallery = Gallery.objects.create(**params)
    img_pks = [pk for pk, in bg.images.values_list("pk")]
    images = Image.objects.filter(pk__in=img_pks)
    for image in images:
        gallery.images.add(image)
    gallery.save()


CPU times: user 788 ms, sys: 45 ms, total: 833 ms
Wall time: 2.65 s

In [113]:
Gallery.objects.count()


Out[113]:
66

Migrate Posts


In [203]:
Post.objects.all().delete()


Out[203]:
(7,
 {'cast.Post_images': 4,
  'cast.Post_videos': 0,
  'cast.Post_galleries': 2,
  'cast.Post': 1})

In [204]:
%%time
post_attrs = ("pk", "author", "title", "pub_date", "visible_date",
              "content", "slug", "created", "modified")
for bp in BlogPost.objects.all():
    params = {attr: getattr(bp, attr) for attr in post_attrs}
    params["content"] = (params["content"].replace("blog_image", "image")
                                          .replace("blog_gallery", "gallery")
                                          .replace("blog_video", "video"))
    params["blog"] = CastBlog.objects.get(pk=bp.blog.pk)
    post = Post.objects.create(**params)
    
    img_pks = [pk for pk, in bp.images.values_list("pk")]
    images = Image.objects.filter(pk__in=img_pks)
    print(images)
    for image in images:
        post.images.add(image)
    print(post.images.all())
    print(post)
    #post.save()
    #print(post.images.all())
    video_pks = [pk for pk, in bp.videos.values_list("pk")]
    videos = Video.objects.filter(pk__in=video_pks)
    for video in videos:
        post.videos.add(video)

    gallery_pks = [pk for pk, in bp.galleries.values_list("pk")]
    galleries = Gallery.objects.filter(pk__in=gallery_pks)
    for gallery in galleries:
        post.galleries.add(gallery)
    
    #post.save()


<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3164.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3164.jpeg>]>
Zu ersten Mal etwas Möhrenbrei
<QuerySet []>
<QuerySet []>
Zu Besuch bei den Grosseltern
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_31b9.jpeg>, <Image: blogs_images/originals/fullsizeoutput_31ba.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_31b9.jpeg>, <Image: blogs_images/originals/fullsizeoutput_31ba.jpeg>]>
Tapas mit Heike und Chrissie
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_31bd.jpeg>, <Image: blogs_images/originals/fullsizeoutput_31bc.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_31bd.jpeg>, <Image: blogs_images/originals/fullsizeoutput_31bc.jpeg>]>
Martin und Marcus kommen zu Besuch
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_328c.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_328c.jpeg>]>
Kaffeetrinken in der Spoerl-Fabrik
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_395e.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_395e.jpeg>]>
In alten Möbeln
<QuerySet []>
<QuerySet []>
Die U5 ist überstanden
<QuerySet []>
<QuerySet []>
Caddy vs. nginx
<QuerySet []>
<QuerySet []>
Spieldecke
<QuerySet []>
<QuerySet []>
Schnullerversuch
<QuerySet [<Image: blogs_images/originals/B40DA12A-A8C7-4C62-AEEA-9EE70D78B8FE.jpeg>]>
<QuerySet [<Image: blogs_images/originals/B40DA12A-A8C7-4C62-AEEA-9EE70D78B8FE.jpeg>]>
Tartlets
<QuerySet [<Image: blogs_images/originals/Ag7E33vsR6SUEHZGmrbT2A.jpg>]>
<QuerySet [<Image: blogs_images/originals/Ag7E33vsR6SUEHZGmrbT2A.jpg>]>
Ein Wochenende in Abentheuer
<QuerySet []>
<QuerySet []>
Writing my own blog engine: Serving images
<QuerySet []>
<QuerySet []>
Sofagebrabbel
<QuerySet []>
<QuerySet []>
Claas zieht sich zum ersten Mal am Sofa hoch
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_2f16.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_2f16.jpeg>]>
Zum ersten Mal Draussen
<QuerySet []>
<QuerySet []>
Kinderwagen ist ok
<QuerySet []>
<QuerySet []>
Erste Stehversuche
<QuerySet []>
<QuerySet []>
Kurzbesuch bei Uroma Thea
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3065.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3065.jpeg>]>
Zu Besuch in Meersen bei Onkel Jo
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_314b.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_314b.jpeg>]>
Weihnachten 2017
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_316a.jpeg>, <Image: blogs_images/originals/fullsizeoutput_317e.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_316a.jpeg>, <Image: blogs_images/originals/fullsizeoutput_317e.jpeg>]>
Mit Katharina bei Sulis
<QuerySet []>
<QuerySet []>
Claas hält sich zum ersten Mal alleine am Tisch fest
<QuerySet [<Image: blogs_images/originals/DSC_0439.jpg>]>
<QuerySet [<Image: blogs_images/originals/DSC_0439.jpg>]>
Letzte Woche im Wildpark Grafenberger Wald
<QuerySet [<Image: blogs_images/originals/11681FA3-6CB1-4657-8047-FA60D7117F43.jpeg>]>
<QuerySet [<Image: blogs_images/originals/11681FA3-6CB1-4657-8047-FA60D7117F43.jpeg>]>
Milchpumpe
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_396c.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_396c.jpeg>]>
Apple Support
<QuerySet []>
<QuerySet []>
Guten Morgen
<QuerySet []>
<QuerySet []>
Geräusche von Draußen
<QuerySet []>
<QuerySet []>
Claas rollt herum und setzt sich alleine hin
<QuerySet [<Image: blogs_images/originals/IMG_1773.JPG>]>
<QuerySet [<Image: blogs_images/originals/IMG_1773.JPG>]>
Responsive images
<QuerySet []>
<QuerySet []>
On my way to pycon
<QuerySet []>
<QuerySet []>
Video mit grosser Kamera
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3081.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3081.jpeg>]>
Besuch von den Kollegen
<QuerySet [<Image: blogs_images/originals/ForJ0lyTRubTchU5sWztg.jpg>]>
<QuerySet [<Image: blogs_images/originals/ForJ0lyTRubTchU5sWztg.jpg>]>
In der Wiege
<QuerySet []>
<QuerySet []>
Wickeltisch Strampelei
<QuerySet [<Image: blogs_images/originals/beg9Jp2OTs27yUmyH2CndA.jpg>]>
<QuerySet [<Image: blogs_images/originals/beg9Jp2OTs27yUmyH2CndA.jpg>]>
Mit Anke bei Sulis
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3129.jpeg>, <Image: blogs_images/originals/H5R9qVhOSo2anuNv3vh54w.jpg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3129.jpeg>, <Image: blogs_images/originals/H5R9qVhOSo2anuNv3vh54w.jpg>]>
Fuchsmütze
<QuerySet []>
<QuerySet []>
Drehende Händchen sind irre lustig
<QuerySet []>
<QuerySet []>
Using a CDN
<QuerySet []>
<QuerySet []>
Scatter plots with density quartiles with python
<QuerySet []>
<QuerySet []>
Babymodellierung
<QuerySet [<Image: blogs_images/originals/blogs.png>]>
<QuerySet [<Image: blogs_images/originals/blogs.png>]>
Writing my own blog engine: The database model
<QuerySet []>
<QuerySet []>
RSS Feeds
<QuerySet []>
<QuerySet []>
Videos
<QuerySet []>
<QuerySet []>
Guten Morgen
<QuerySet [<Image: blogs_images/originals/IMG_1814.JPG>]>
<QuerySet [<Image: blogs_images/originals/IMG_1814.JPG>]>
Claas Uroma Thea
<QuerySet []>
<QuerySet []>
Guten Morgen
<QuerySet [<Image: blogs_images/originals/IMG_1790.JPG>]>
<QuerySet [<Image: blogs_images/originals/IMG_1790.JPG>]>
Omas Geburtstag!
<QuerySet [<Image: blogs_images/originals/IMG_1824.JPG>, <Image: blogs_images/originals/fullsizeoutput_2f43.jpeg>]>
<QuerySet [<Image: blogs_images/originals/IMG_1824.JPG>, <Image: blogs_images/originals/fullsizeoutput_2f43.jpeg>]>
Unterwegs auf der Kö
<QuerySet []>
<QuerySet []>
Ein paar Portraits
<QuerySet []>
<QuerySet []>
Gute Laune am Freitagabend
<QuerySet []>
<QuerySet []>
Brillenprobe
<QuerySet []>
<QuerySet []>
Wiege mit Ball
<QuerySet []>
<QuerySet []>
Claas sitzt zum ersten Mal alleine
<QuerySet []>
<QuerySet []>
Besuch bei Jo in Maastricht
<QuerySet []>
<QuerySet []>
Added rudimentary gallery support
<QuerySet []>
<QuerySet []>
First post
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_2f15.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_2f15.jpeg>]>
Getting images to work
<QuerySet []>
<QuerySet []>
Ein paar Fotos und ein längeres Video
<QuerySet []>
<QuerySet []>
Claas dreht sich
<QuerySet []>
<QuerySet []>
Party
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_2f9e.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_2f9e.jpeg>]>
Uroma Anita
<QuerySet []>
<QuerySet []>
Geräusche auf dem Wickeltisch
<QuerySet []>
<QuerySet []>
Schmatzen ist toll
<QuerySet []>
<QuerySet []>
Sonntag in Lohmar
<QuerySet []>
<QuerySet []>
Lohmart
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3080.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3080.jpeg>]>
Claas mit Opa Ingo
<QuerySet [<Image: blogs_images/originals/DC6C2E14-C17B-40E9-A083-9A92758BBE06.jpeg>]>
<QuerySet [<Image: blogs_images/originals/DC6C2E14-C17B-40E9-A083-9A92758BBE06.jpeg>]>
Karl und der Ofen
<QuerySet []>
<QuerySet []>
Einmal lächeln bitte
<QuerySet [<Image: blogs_images/originals/DSC_0695.jpg>, <Image: blogs_images/originals/DSC_0664.jpg>, <Image: blogs_images/originals/DSC_0659.jpg>]>
<QuerySet [<Image: blogs_images/originals/DSC_0695.jpg>, <Image: blogs_images/originals/DSC_0664.jpg>, <Image: blogs_images/originals/DSC_0659.jpg>]>
Onkel Jos Geburtstagsfeier
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_2fc8.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_2fc8.jpeg>]>
Onkel Karl
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_2f86.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_2f86.jpeg>]>
PyCon 2017
<QuerySet []>
<QuerySet []>
Added pagination
<QuerySet []>
<QuerySet []>
Wickeltisch
<QuerySet [<Image: blogs_images/originals/DSC_0364.jpg>]>
<QuerySet [<Image: blogs_images/originals/DSC_0364.jpg>]>
Dirk und Sophie waren zu Besuch
<QuerySet []>
<QuerySet []>
Die Hochzeitseinladungen für Katharina sehen nicht nur lecker aus
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_39e8.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_39e8.jpeg>]>
Luftrollenspielzeug
<QuerySet []>
<QuerySet []>
Ausgiebiges Brabbeln
<QuerySet [<Image: blogs_images/originals/eeK81WRQaCrETf1Xz3Ug.jpg>, <Image: blogs_images/originals/NRgRHnUKShCleAHpFOnsg.jpg>]>
<QuerySet [<Image: blogs_images/originals/eeK81WRQaCrETf1Xz3Ug.jpg>, <Image: blogs_images/originals/NRgRHnUKShCleAHpFOnsg.jpg>]>
Spaziergang in Düsseldorf
<QuerySet []>
<QuerySet []>
Wintergarten wieder ohne Kissen
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_39f4.jpeg>, <Image: blogs_images/originals/fullsizeoutput_39f5.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_39f4.jpeg>, <Image: blogs_images/originals/fullsizeoutput_39f5.jpeg>]>
Karfreitag im Carrotcake
<QuerySet []>
<QuerySet []>
Zum ersten Mal beim Krabbeln gefilmt
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3a38.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3a01.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3a2c.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3a27.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3a38.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3a01.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3a2c.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3a27.jpeg>]>
Ostern 2018
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3a59.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3a59.jpeg>]>
Opa Ingos Geburtstag
<QuerySet []>
<QuerySet []>
Die letzte Milch war wohl schlecht
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3a83.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3aa7.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3a83.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3aa7.jpeg>]>
Spaziergang am Rhein
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3a61.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3a55.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3a61.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3a55.jpeg>]>
Zu Besuch bei Huan, Volker und Charlie
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_344b.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_344b.jpeg>]>
Milchbinge
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3a64.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3a75.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3a64.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3a75.jpeg>]>
Claas im Kinderkaffee
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3a81.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3a81.jpeg>]>
Abendlicht
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3abb.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3abb.jpeg>]>
Der erste warme Frühlingstag
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3abc.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3abc.jpeg>]>
Kirmes
<QuerySet []>
<QuerySet []>
Die Küchentürschwelle
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3abd.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3abd.jpeg>]>
Picknick auf dem Spielplatz um die Ecke
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3ac5.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3ac5.jpeg>]>
Spaziergang
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3ac9.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3aca.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3aeb.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3af5.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3ac9.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3aca.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3aeb.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3af5.jpeg>]>
Katharinas und Wolfgangs Hochzeit
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3b27.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3b27.jpeg>]>
Katharinas Geburtstag
<QuerySet []>
<QuerySet []>
Drehknöpfe
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3b38.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3b38.jpeg>]>
Uroma Anita ist zu Besuch
<QuerySet []>
<QuerySet []>
Es hagelt
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3bf6.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3c48.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3c13.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3bf6.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3c48.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3c13.jpeg>]>
Pfingsten im Hof
<QuerySet []>
<QuerySet []>
Grillen bei Johannes
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3c4c.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3c4c.jpeg>]>
Japantag in den Rheinauen
<QuerySet []>
<QuerySet []>
Erste Schritte!
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3b41.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3b3e.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3b45.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3bbd.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3ba2.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3b82.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3b5c.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3b61.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3b41.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3b3e.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3b45.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3bbd.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3ba2.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3b82.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3b5c.jpeg>, <Image: blogs_images/originals/fullsizeoutput_3b61.jpeg>]>
Geburtstag von Oma Thea und Onkel Volker
<QuerySet []>
<QuerySet []>
Leckere Steine
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3d64.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3d64.jpeg>]>
Huan und Rolfs Geburtstag
<QuerySet [<Image: blogs_images/originals/black-label-2018-47.jpg>]>
<QuerySet [<Image: blogs_images/originals/black-label-2018-47.jpg>]>
Motorradtreffen
<QuerySet [<Image: blogs_images/originals/783568F0-5F5C-4184-99D6-123D089FBEA3.jpeg>, <Image: blogs_images/originals/EF76CA1F-FAB4-4E87-88E8-27B3A1F78E00.jpeg>]>
<QuerySet [<Image: blogs_images/originals/783568F0-5F5C-4184-99D6-123D089FBEA3.jpeg>, <Image: blogs_images/originals/EF76CA1F-FAB4-4E87-88E8-27B3A1F78E00.jpeg>]>
Sundowner am Rhein
<QuerySet [<Image: blogs_images/originals/aquazoo-nordpark-2018-2.jpg>, <Image: blogs_images/originals/aquazoo-nordpark-2018-6.jpg>, <Image: blogs_images/originals/IMG_0889.jpg>]>
<QuerySet [<Image: blogs_images/originals/aquazoo-nordpark-2018-2.jpg>, <Image: blogs_images/originals/aquazoo-nordpark-2018-6.jpg>, <Image: blogs_images/originals/IMG_0889.jpg>]>
Besuch im Aquazoo und Nordpark
<QuerySet [<Image: blogs_images/originals/insel-hombroich-2018-20.jpg>, <Image: blogs_images/originals/insel-hombroich-2018-24.jpg>, <Image: blogs_images/originals/insel-hombroich-2018-35.jpg>, <Image: blogs_images/originals/insel-hombroich-2018-51.jpg>, <Image: blogs_images/originals/9.jpg>]>
<QuerySet [<Image: blogs_images/originals/insel-hombroich-2018-20.jpg>, <Image: blogs_images/originals/insel-hombroich-2018-24.jpg>, <Image: blogs_images/originals/insel-hombroich-2018-35.jpg>, <Image: blogs_images/originals/insel-hombroich-2018-51.jpg>, <Image: blogs_images/originals/9.jpg>]>
Museumsinsel Hombroich
<QuerySet []>
<QuerySet []>
Claas hat eine neue Fortbewegungsmethode entdeckt
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3d75.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3d75.jpeg>]>
Hoffentlich ist peak Matscherei bald erreicht
<QuerySet [<Image: blogs_images/originals/schloss-dyck-2018-7.jpg>, <Image: blogs_images/originals/schloss-dyck-2018-13.jpg>, <Image: blogs_images/originals/schloss-dyck-2018-16.jpg>]>
<QuerySet [<Image: blogs_images/originals/schloss-dyck-2018-7.jpg>, <Image: blogs_images/originals/schloss-dyck-2018-13.jpg>, <Image: blogs_images/originals/schloss-dyck-2018-16.jpg>]>
Besuch auf Schloß Dyck
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3dd6.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3dd6.jpeg>]>
Flashback Frühling
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3e1f.jpeg>]>
<QuerySet [<Image: blogs_images/originals/fullsizeoutput_3e1f.jpeg>]>
Claas erste Demo
<QuerySet [<Image: blogs_images/originals/Industriepark-Duisburg-Juli-2018-3.jpg>, <Image: blogs_images/originals/Industriepark-Duisburg-Juli-2018-7.jpg>, <Image: blogs_images/originals/Industriepark-Duisburg-Juli-2018-11.jpg>, <Image: blogs_images/originals/Strandbar_Duisburg.jpg>]>
<QuerySet [<Image: blogs_images/originals/Industriepark-Duisburg-Juli-2018-3.jpg>, <Image: blogs_images/originals/Industriepark-Duisburg-Juli-2018-7.jpg>, <Image: blogs_images/originals/Industriepark-Duisburg-Juli-2018-11.jpg>, <Image: blogs_images/originals/Strandbar_Duisburg.jpg>]>
Picknick vor Hochofen 5
CPU times: user 1.88 s, sys: 154 ms, total: 2.03 s
Wall time: 7.23 s

In [196]:
post.images.all()


Out[196]:
<QuerySet [<Image: blogs_images/originals/Industriepark-Duisburg-Juli-2018-3.jpg>, <Image: blogs_images/originals/Industriepark-Duisburg-Juli-2018-7.jpg>, <Image: blogs_images/originals/Industriepark-Duisburg-Juli-2018-11.jpg>, <Image: blogs_images/originals/Strandbar_Duisburg.jpg>]>

In [146]:
Post.objects.count()


Out[146]:
117

In [121]:
post = Post.objects.get(slug="pycon_2017")

In [140]:
foo = post.content

In [132]:
post.pk


Out[132]:
27

In [131]:
BlogPost.objects.all()[1].description


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-131-817da19a8813> in <module>()
----> 1 BlogPost.objects.all()[1].description

AttributeError: 'BlogPost' object has no attribute 'description'

In [133]:
bp = BlogPost.objects.get(pk=27)

In [135]:
bp.content


Out[135]:
'<a href="https://de.pycon.org/">PyCon 2017</a>&nbsp;is over now and I liked it a lot. It was a really well organized event and the talks were great. I already knew the <a href="http://zkm.de/en">conference location</a>&nbsp;because I lived only a few hundred meters away for a long time. So it didn&#39;t came as a surprise for me that it was awesome.<br />\r\n<br />\r\n{% blog_gallery 8 %}<br />\r\n<br />\r\nI don&#39;t attend conferences like this because of the talks, I have to say. But I always get a strange boost in motivation from events like this - I don&#39;t now why, but I suspect it has something to do with talking to a lot of likeminded people. Talking to my former collegues from&nbsp;<a href="https://www.billiger.de/">billiger.de</a>&nbsp;for example was a lot of fun. They did a lot of cool things since I moved on like having a new search service in pure python or migrating from relational databases to redis and now to elasticsearch for document storage.<br />\r\n<br />\r\n{% blog_gallery 10 %}<br />\r\n<br />\r\nAt the social event we had some concerns that the beer supply could become a problem, since nearly all of the attendees showed up. Turned out that our worries were exaggerated.<br />\r\n<br />\r\n{% blog_image 40 %}<br />\r\n<br />\r\nSince I know Karlsruhe well, I did also met nice people that didn&#39;t have anything to do with pycon.<br />\r\n<br />\r\n{% blog_gallery 11 %}<br />\r\n<br />\r\nThere was a funny installation at one of the exhibitions at the zkm.<br />\r\n<br />\r\n{% blog_video 9 %}'

In [136]:
bp.description


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-136-bf4fcc514fde> in <module>()
----> 1 bp.description

AttributeError: 'BlogPost' object has no attribute 'description'

In [137]:
Post.objects.count()


Out[137]:
0

In [143]:
foo.replace("blog_image", "image").replace("blog_gallery", "gallery").replace()


Out[143]:
'<h3>Besuch im Landschaftspark Duisburg-Nord</h3>\r\n{% image 529 %}<br />\r\n{% image 537 %}<br />\r\n<br />\r\nAuf dem riesigen Gel&auml;nde des ehemaligen H&uuml;ttenwerks in Duisburg gibt es wirklich viel zu entdecken. Es wird sicher spannend in der Anlage herumklettern zu k&ouml;nnen, wenn Claas ein paar Jahre &auml;lter ist. Aber auch zu ebener Erde ist der Anblick der vor sich hinrostenden Hoch&ouml;fen und der Bunkerg&auml;rten einen Besuch wert. Die &quot;Alte Emscher&quot; flie&szlig;t durch das Gel&auml;nde und in den ehemaligen Absetzbecken wuchern die Seerosen. Kurz, dieser Park hat uns nicht zum letzten Mal gesehen.&nbsp;<br />\r\n{% gallery 76 %}<br />\r\nNach unserem Picknick vor Hochofen 5, haben wir mit Claas einige der oberen Steige zu Fu&szlig; erkundet. Daf&uuml;r, dass er noch nicht sehr lange l&auml;uft hat er die langen Wege wirklich super gemeistert. V&ouml;llig angstfrei &uuml;ber Gitterbr&uuml;cken und so begeistert von den Bodenwellen auf einem offenen Platz, dass wir da f&uuml;nf Minuten bleiben mussten.<br />\r\n<br />\r\nUnd es gab so herrlich viel Dreck!<br />\r\n<br />\r\n{% image 533 %}<br />\r\n{% gallery 77 %}<br />\r\nIn ein paar Jahren ist dann auch der riesige Klettergarten oder Tauchen im Gasometer interessant. Hm, vielleicht lassen sich Onkel und Tante ja schon fr&uuml;her daf&uuml;r begeistern :).<br />\r\nGanz zum Schluss haben wir noch die F&uuml;&szlig;e in den feinen weichen Sand der Strandbar anl&auml;sslich des Sommerkinos in der alten Gie&szlig;halle versenkt. Claas hatte seine riesen Buddelkiste um ihn auch wirklich m&uuml;de mit nach Haus zu nehemen und alle ein k&uuml;hles Getr&auml;nk zum Abschluss &ndash; was will man mehr.<br />\r\n<br />\r\n{% image 566 %}'

In [147]:
Image.objects.get(pk=527)


Out[147]:
<Image: blogs_images/originals/Industriepark-Duisburg-Juli-2018-1.jpg>

In [202]:
Post.objects.get(pk=124).images.all()


Out[202]:
<QuerySet [<Image: blogs_images/originals/Industriepark-Duisburg-Juli-2018-3.jpg>, <Image: blogs_images/originals/Industriepark-Duisburg-Juli-2018-7.jpg>, <Image: blogs_images/originals/Industriepark-Duisburg-Juli-2018-11.jpg>, <Image: blogs_images/originals/Strandbar_Duisburg.jpg>]>

In [197]:
bp = BlogPost.objects.get(pk=124)

In [153]:
img_pks = [pk for pk, in bp.images.values_list("pk")]

In [154]:
img_pks


Out[154]:
[529, 533, 537, 566]

In [155]:
images = Image.objects.filter(pk__in=img_pks)

In [156]:
images


Out[156]:
<QuerySet [<Image: blogs_images/originals/Industriepark-Duisburg-Juli-2018-3.jpg>, <Image: blogs_images/originals/Industriepark-Duisburg-Juli-2018-7.jpg>, <Image: blogs_images/originals/Industriepark-Duisburg-Juli-2018-11.jpg>, <Image: blogs_images/originals/Strandbar_Duisburg.jpg>]>

In [205]:
post = Post.objects.get(pk=124)

In [159]:
for image in images:
    post.images.add(image)

In [160]:
post.images.all()


Out[160]:
<QuerySet [<Image: blogs_images/originals/Industriepark-Duisburg-Juli-2018-3.jpg>, <Image: blogs_images/originals/Industriepark-Duisburg-Juli-2018-7.jpg>, <Image: blogs_images/originals/Industriepark-Duisburg-Juli-2018-11.jpg>, <Image: blogs_images/originals/Strandbar_Duisburg.jpg>]>

In [206]:
post.images.all()


Out[206]:
<QuerySet [<Image: blogs_images/originals/Industriepark-Duisburg-Juli-2018-3.jpg>, <Image: blogs_images/originals/Industriepark-Duisburg-Juli-2018-7.jpg>, <Image: blogs_images/originals/Industriepark-Duisburg-Juli-2018-11.jpg>, <Image: blogs_images/originals/Strandbar_Duisburg.jpg>]>

In [207]:
post.created, post.modified


Out[207]:
(datetime.datetime(2018, 8, 3, 17, 30, 54, 936869, tzinfo=<UTC>),
 datetime.datetime(2018, 11, 6, 15, 32, 5, 194251, tzinfo=<UTC>))

In [213]:
video = Video.objects.all().order_by("-created")[0]

In [214]:
video.created


Out[214]:
datetime.datetime(2018, 8, 4, 8, 54, 29, 253890, tzinfo=<UTC>)

In [219]:
sorted([pk for pk, in Post.objects.values_list("pk")])


Out[219]:
[1,
 2,
 3,
 4,
 6,
 7,
 8,
 9,
 10,
 11,
 12,
 13,
 16,
 17,
 18,
 19,
 20,
 21,
 22,
 23,
 24,
 25,
 27,
 28,
 29,
 30,
 31,
 32,
 33,
 34,
 35,
 36,
 37,
 38,
 39,
 40,
 41,
 42,
 43,
 44,
 45,
 46,
 47,
 48,
 49,
 50,
 51,
 52,
 53,
 54,
 55,
 56,
 57,
 58,
 59,
 60,
 61,
 62,
 63,
 64,
 65,
 66,
 67,
 68,
 69,
 70,
 71,
 72,
 73,
 74,
 75,
 76,
 77,
 78,
 79,
 81,
 82,
 83,
 84,
 85,
 86,
 87,
 88,
 89,
 90,
 91,
 92,
 93,
 94,
 95,
 96,
 97,
 98,
 99,
 100,
 101,
 102,
 103,
 104,
 105,
 106,
 107,
 108,
 109,
 110,
 111,
 112,
 113,
 114,
 115,
 116,
 117,
 118,
 119,
 120,
 121,
 124,
 126]

In [224]:
Video.objects.get(pk=59)


---------------------------------------------------------------------------
DoesNotExist                              Traceback (most recent call last)
<ipython-input-224-f73bba3b6de2> in <module>()
----> 1 Video.objects.get(pk=59)

~/.virtualenvs/homepage/lib/python3.7/site-packages/django/db/models/manager.py in manager_method(self, *args, **kwargs)
     80         def create_method(name, method):
     81             def manager_method(self, *args, **kwargs):
---> 82                 return getattr(self.get_queryset(), name)(*args, **kwargs)
     83             manager_method.__name__ = method.__name__
     84             manager_method.__doc__ = method.__doc__

~/.virtualenvs/homepage/lib/python3.7/site-packages/django/db/models/query.py in get(self, *args, **kwargs)
    397             raise self.model.DoesNotExist(
    398                 "%s matching query does not exist." %
--> 399                 self.model._meta.object_name
    400             )
    401         raise self.model.MultipleObjectsReturned(

DoesNotExist: Video matching query does not exist.

In [232]:
max([pk for pk, in Video.objects.values_list("pk")])


Out[232]:
60

In [226]:
max([pk for pk, in BlogVideo.objects.values_list("pk")])


Out[226]:
59

In [4]:
video = BlogVideo.objects.all().order_by("-created")[0]

In [5]:
video.poster


Out[5]:
<ImageFieldFile: blogs_videos/poster/poster_s77g5s3o.jpg>
Out[5]:
<ImageFieldFile: blogs_videos/poster/poster_s77g5s3o.jpg>

In [6]:
video.pk


Out[6]:
59
Out[6]:
59

In [7]:
video = Video.objects.all().order_by("-created")[0]

In [8]:
video.pk


Out[8]:
60
Out[8]:
60

In [9]:
video.poster


Out[9]:
<ImageFieldFile: None>
Out[9]:
<ImageFieldFile: None>

In [ ]:
video.create_poster()


/var/folders/2l/7zccp5bs1234yz4ns62s796m0000gn/T/poster_siswrc9x.jpg
> /Users/jochen/projects/django-cast/cast/models.py(158)_create_poster()
-> self.poster.save(
/var/folders/2l/7zccp5bs1234yz4ns62s796m0000gn/T/poster_siswrc9x.jpg
> /Users/jochen/projects/django-cast/cast/models.py(158)_create_poster()
-> self.poster.save(
(Pdb) import os
(Pdb) print(os.stat(tmp_path)
*** SyntaxError: unexpected EOF while parsing
*** SyntaxError: unexpected EOF while parsing
(Pdb) print(os.stat(tmp_path))
os.stat_result(st_mode=33152, st_ino=8627049245, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=285582, st_atime=1541579098, st_mtime=1541579098, st_ctime=1541579098)
os.stat_result(st_mode=33152, st_ino=8627049245, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=285582, st_atime=1541579098, st_mtime=1541579098, st_ctime=1541579098)
(Pdb) os.path.exists(tmp_path)
True
True
(Pdb) os.path.basename(tmp_path)
'poster_siswrc9x.jpg'
'poster_siswrc9x.jpg'

In [13]:
video.calc_poster


Out[13]:
True
Out[13]:
True

In [14]:
video._create_poster()


/var/folders/2l/7zccp5bs1234yz4ns62s796m0000gn/T/poster_oe5wtm5e.jpg
/var/folders/2l/7zccp5bs1234yz4ns62s796m0000gn/T/poster_oe5wtm5e.jpg
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-14-9a46d2734f29> in <module>()
----> 1 video._create_poster()

~/projects/django-cast/cast/models.py in _create_poster(self)
    157         self.poster.save(
    158             os.path.basename(tmp_path), File(open(tmp_path, 'rb')),
--> 159             save=False)
    160         os.unlink(tmp_path)
    161         logger.info(self.pk)

~/.virtualenvs/homepage/lib/python3.7/site-packages/django/db/models/fields/files.py in save(self, name, content, save)
     85     def save(self, name, content, save=True):
     86         name = self.field.generate_filename(self.instance, name)
---> 87         self.name = self.storage.save(name, content, max_length=self.field.max_length)
     88         setattr(self.instance, self.field.name, self.name)
     89         self._committed = True

~/.virtualenvs/homepage/lib/python3.7/site-packages/django/core/files/storage.py in save(self, name, content, max_length)
     47 
     48         name = self.get_available_name(name, max_length=max_length)
---> 49         return self._save(name, content)
     50 
     51     # These methods are part of the public API, with default implementations.

~/.virtualenvs/homepage/lib/python3.7/site-packages/django/core/files/storage.py in _save(self, name, content)
    266                     try:
    267                         locks.lock(fd, locks.LOCK_EX)
--> 268                         for chunk in content.chunks():
    269                             if _file is None:
    270                                 mode = 'wb' if isinstance(chunk, bytes) else 'wt'

~/.virtualenvs/homepage/lib/python3.7/site-packages/django/core/files/base.py in chunks(self, chunk_size)
     58 
     59         while True:
---> 60             data = self.read(chunk_size)
     61             if not data:
     62                 break

~/.virtualenvs/homepage/lib/python3.7/site-packages/django/core/files/utils.py in <lambda>(self)
     14     isatty = property(lambda self: self.file.isatty)
     15     newlines = property(lambda self: self.file.newlines)
---> 16     read = property(lambda self: self.file.read)
     17     readinto = property(lambda self: self.file.readinto)
     18     readline = property(lambda self: self.file.readline)

AttributeError: 'File' object has no attribute 'read'
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-14-9a46d2734f29> in <module>()
----> 1 video._create_poster()

~/projects/django-cast/cast/models.py in _create_poster(self)
    157         self.poster.save(
    158             os.path.basename(tmp_path), File(open(tmp_path, 'rb')),
--> 159             save=False)
    160         os.unlink(tmp_path)
    161         logger.info(self.pk)

~/.virtualenvs/homepage/lib/python3.7/site-packages/django/db/models/fields/files.py in save(self, name, content, save)
     85     def save(self, name, content, save=True):
     86         name = self.field.generate_filename(self.instance, name)
---> 87         self.name = self.storage.save(name, content, max_length=self.field.max_length)
     88         setattr(self.instance, self.field.name, self.name)
     89         self._committed = True

~/.virtualenvs/homepage/lib/python3.7/site-packages/django/core/files/storage.py in save(self, name, content, max_length)
     47 
     48         name = self.get_available_name(name, max_length=max_length)
---> 49         return self._save(name, content)
     50 
     51     # These methods are part of the public API, with default implementations.

~/.virtualenvs/homepage/lib/python3.7/site-packages/django/core/files/storage.py in _save(self, name, content)
    266                     try:
    267                         locks.lock(fd, locks.LOCK_EX)
--> 268                         for chunk in content.chunks():
    269                             if _file is None:
    270                                 mode = 'wb' if isinstance(chunk, bytes) else 'wt'

~/.virtualenvs/homepage/lib/python3.7/site-packages/django/core/files/base.py in chunks(self, chunk_size)
     58 
     59         while True:
---> 60             data = self.read(chunk_size)
     61             if not data:
     62                 break

~/.virtualenvs/homepage/lib/python3.7/site-packages/django/core/files/utils.py in <lambda>(self)
     14     isatty = property(lambda self: self.file.isatty)
     15     newlines = property(lambda self: self.file.newlines)
---> 16     read = property(lambda self: self.file.read)
     17     readinto = property(lambda self: self.file.readinto)
     18     readline = property(lambda self: self.file.readline)

AttributeError: 'File' object has no attribute 'read'

move images


In [7]:
image = BlogImage.objects.all()[0]

In [8]:
image.original


Out[8]:
<ImageFieldFile: blogs_images/originals/IMG_1773.JPG>

In [10]:
image = Image.objects.all()[0]

In [11]:
image.original


Out[11]:
<ImageFieldFile: blogs_images/originals/IMG_1773.JPG>

In [13]:
image = Image.objects.get(pk=577)

In [14]:
image.original


Out[14]:
<ImageFieldFile: cast_images/originals/iqHs41HGQsW2Ma1jN9iCag.jpg>

video poster


In [4]:
import io
import os
import tempfile

from django.core.files import File
from subprocess import check_output

In [5]:
video = Video.objects.all().order_by("-created")[0]
print(video.pk)


60

In [6]:
video._create_poster()

In [24]:
content = video._get_content()


content:  File object (<_io.BufferedReader name='/var/folders/2l/7zccp5bs1234yz4ns62s796m0000gn/T/poster_fum4jsvc.jpg'>)

In [26]:
content.file


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-26-6b3984707a8c> in <module>()
----> 1 content.file

AttributeError: 'File' object has no attribute 'file'

In [28]:
content.size()


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-28-b2998cadcf16> in <module>()
----> 1 content.size()

AttributeError: 'File' object has no attribute 'size'

In [9]:
content.file = open('/var/folders/2l/7zccp5bs1234yz4ns62s796m0000gn/T/poster_lj52okma.jpg', "rb")

In [11]:
name = "poster_lj52okma.jpg"

In [10]:
print(content)


File object (<_io.BufferedReader name='/var/folders/2l/7zccp5bs1234yz4ns62s796m0000gn/T/poster_lj52okma.jpg'>)

In [9]:
fp, tmp_path = tempfile.mkstemp(prefix='poster_', suffix='.jpg')

In [16]:
print(fp)


57

In [10]:
print(video.original.url)
print(video.original.path)
video_url = video.original.path


/media/blogs_videos/js7CDaxSx2sm0n3VanytQ_V4Sjx0r.MOV
/Users/jochen/projects/homepage/homepage/media/blogs_videos/js7CDaxSx2sm0n3VanytQ_V4Sjx0r.MOV

In [11]:
width, height = video._get_video_dimensions(video_url)

In [12]:
poster_cmd = (
    'ffmpeg -ss {seconds} -i "{video_path}" -vframes 1'
    ' -y -f image2 -s {width}x{height} {poster_path}'
).format(video_path=video_url, seconds=video.poster_seconds,
         poster_path=tmp_path, width=width, height=height)

In [13]:
poster_cmd


Out[13]:
'ffmpeg -ss 1.0 -i "/Users/jochen/projects/homepage/homepage/media/blogs_videos/js7CDaxSx2sm0n3VanytQ_V4Sjx0r.MOV" -vframes 1 -y -f image2 -s 3840x2160 /var/folders/2l/7zccp5bs1234yz4ns62s796m0000gn/T/poster_67_qy0sc.jpg'

In [14]:
check_output(poster_cmd, shell=True)


Out[14]:
b''

In [17]:
tmp_path


Out[17]:
'/var/folders/2l/7zccp5bs1234yz4ns62s796m0000gn/T/poster_67_qy0sc.jpg'

In [14]:
help(video.poster.save)


Help on method save in module django.db.models.fields.files:

save(name, content, save=True) method of django.db.models.fields.files.ImageFieldFile instance


In [18]:
name = os.path.basename(tmp_path)
print(name)


poster_67_qy0sc.jpg

In [19]:
content = File(open(tmp_path, 'rb'))
print("content: ", content)


content:  /var/folders/2l/7zccp5bs1234yz4ns62s796m0000gn/T/poster_67_qy0sc.jpg

In [20]:
fh = open(tmp_path, 'rb')
print(fh)


<_io.BufferedReader name='/var/folders/2l/7zccp5bs1234yz4ns62s796m0000gn/T/poster_67_qy0sc.jpg'>

In [22]:
print(content)


/var/folders/2l/7zccp5bs1234yz4ns62s796m0000gn/T/poster_67_qy0sc.jpg

In [23]:
content = File(fh)

In [25]:
print(repr(content))


<File: /var/folders/2l/7zccp5bs1234yz4ns62s796m0000gn/T/poster_67_qy0sc.jpg>

In [26]:
print(content.file)


<_io.BufferedReader name='/var/folders/2l/7zccp5bs1234yz4ns62s796m0000gn/T/poster_67_qy0sc.jpg'>

In [19]:
help(File)


Help on class File in module django.core.files.base:

class File(django.core.files.utils.FileProxyMixin)
 |  File(file, name=None)
 |  
 |  A mixin class used to forward file methods to an underlaying file
 |  object.  The internal file object has to be called "file"::
 |  
 |      class FileProxy(FileProxyMixin):
 |          def __init__(self, file):
 |              self.file = file
 |  
 |  Method resolution order:
 |      File
 |      django.core.files.utils.FileProxyMixin
 |      builtins.object
 |  
 |  Methods defined here:
 |  
 |  __bool__(self)
 |  
 |  __enter__(self)
 |  
 |  __exit__(self, exc_type, exc_value, tb)
 |  
 |  __init__(self, file, name=None)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __iter__(self)
 |  
 |  __len__(self)
 |  
 |  __repr__(self)
 |      Return repr(self).
 |  
 |  __str__(self)
 |      Return str(self).
 |  
 |  chunks(self, chunk_size=None)
 |      Read the file and yield chunks of ``chunk_size`` bytes (defaults to
 |      ``File.DEFAULT_CHUNK_SIZE``).
 |  
 |  close(self)
 |  
 |  multiple_chunks(self, chunk_size=None)
 |      Return ``True`` if you can expect multiple chunks.
 |      
 |      NB: If a particular file representation is in memory, subclasses should
 |      always return ``False`` -- there's no good reason to read from memory in
 |      chunks.
 |  
 |  open(self, mode=None)
 |  
 |  size = <django.utils.functional.cached_property object>
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  DEFAULT_CHUNK_SIZE = 65536
 |  
 |  ----------------------------------------------------------------------
 |  Methods inherited from django.core.files.utils.FileProxyMixin:
 |  
 |  readable(self)
 |  
 |  seekable(self)
 |  
 |  writable(self)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from django.core.files.utils.FileProxyMixin:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  closed
 |  
 |  encoding
 |  
 |  fileno
 |  
 |  flush
 |  
 |  isatty
 |  
 |  newlines
 |  
 |  read
 |  
 |  readinto
 |  
 |  readline
 |  
 |  readlines
 |  
 |  seek
 |  
 |  tell
 |  
 |  truncate
 |  
 |  write
 |  
 |  writelines


In [7]:
help(open)


Help on built-in function open in module io:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
    Open file and return a stream.  Raise OSError upon failure.
    
    file is either a text or byte string giving the name (and the path
    if the file isn't in the current working directory) of the file to
    be opened or an integer file descriptor of the file to be
    wrapped. (If a file descriptor is given, it is closed when the
    returned I/O object is closed, unless closefd is set to False.)
    
    mode is an optional string that specifies the mode in which the file
    is opened. It defaults to 'r' which means open for reading in text
    mode.  Other common values are 'w' for writing (truncating the file if
    it already exists), 'x' for creating and writing to a new file, and
    'a' for appending (which on some Unix systems, means that all writes
    append to the end of the file regardless of the current seek position).
    In text mode, if encoding is not specified the encoding used is platform
    dependent: locale.getpreferredencoding(False) is called to get the
    current locale encoding. (For reading and writing raw bytes use binary
    mode and leave encoding unspecified.) The available modes are:
    
    ========= ===============================================================
    Character Meaning
    --------- ---------------------------------------------------------------
    'r'       open for reading (default)
    'w'       open for writing, truncating the file first
    'x'       create a new file and open it for writing
    'a'       open for writing, appending to the end of the file if it exists
    'b'       binary mode
    't'       text mode (default)
    '+'       open a disk file for updating (reading and writing)
    'U'       universal newline mode (deprecated)
    ========= ===============================================================
    
    The default mode is 'rt' (open for reading text). For binary random
    access, the mode 'w+b' opens and truncates the file to 0 bytes, while
    'r+b' opens the file without truncation. The 'x' mode implies 'w' and
    raises an `FileExistsError` if the file already exists.
    
    Python distinguishes between files opened in binary and text modes,
    even when the underlying operating system doesn't. Files opened in
    binary mode (appending 'b' to the mode argument) return contents as
    bytes objects without any decoding. In text mode (the default, or when
    't' is appended to the mode argument), the contents of the file are
    returned as strings, the bytes having been first decoded using a
    platform-dependent encoding or using the specified encoding if given.
    
    'U' mode is deprecated and will raise an exception in future versions
    of Python.  It has no effect in Python 3.  Use newline to control
    universal newlines mode.
    
    buffering is an optional integer used to set the buffering policy.
    Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
    line buffering (only usable in text mode), and an integer > 1 to indicate
    the size of a fixed-size chunk buffer.  When no buffering argument is
    given, the default buffering policy works as follows:
    
    * Binary files are buffered in fixed-size chunks; the size of the buffer
      is chosen using a heuristic trying to determine the underlying device's
      "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
      On many systems, the buffer will typically be 4096 or 8192 bytes long.
    
    * "Interactive" text files (files for which isatty() returns True)
      use line buffering.  Other text files use the policy described above
      for binary files.
    
    encoding is the name of the encoding used to decode or encode the
    file. This should only be used in text mode. The default encoding is
    platform dependent, but any encoding supported by Python can be
    passed.  See the codecs module for the list of supported encodings.
    
    errors is an optional string that specifies how encoding errors are to
    be handled---this argument should not be used in binary mode. Pass
    'strict' to raise a ValueError exception if there is an encoding error
    (the default of None has the same effect), or pass 'ignore' to ignore
    errors. (Note that ignoring encoding errors can lead to data loss.)
    See the documentation for codecs.register or run 'help(codecs.Codec)'
    for a list of the permitted encoding error strings.
    
    newline controls how universal newlines works (it only applies to text
    mode). It can be None, '', '\n', '\r', and '\r\n'.  It works as
    follows:
    
    * On input, if newline is None, universal newlines mode is
      enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
      these are translated into '\n' before being returned to the
      caller. If it is '', universal newline mode is enabled, but line
      endings are returned to the caller untranslated. If it has any of
      the other legal values, input lines are only terminated by the given
      string, and the line ending is returned to the caller untranslated.
    
    * On output, if newline is None, any '\n' characters written are
      translated to the system default line separator, os.linesep. If
      newline is '' or '\n', no translation takes place. If newline is any
      of the other legal values, any '\n' characters written are translated
      to the given string.
    
    If closefd is False, the underlying file descriptor will be kept open
    when the file is closed. This does not work when a file name is given
    and must be True in that case.
    
    A custom opener can be used by passing a callable as *opener*. The
    underlying file descriptor for the file object is then obtained by
    calling *opener* with (*file*, *flags*). *opener* must return an open
    file descriptor (passing os.open as *opener* results in functionality
    similar to passing None).
    
    open() returns a file object whose type depends on the mode, and
    through which the standard file operations such as reading and writing
    are performed. When open() is used to open a file in a text mode ('w',
    'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
    a file in a binary mode, the returned class varies: in read binary
    mode, it returns a BufferedReader; in write binary and append binary
    modes, it returns a BufferedWriter, and in read/write mode, it returns
    a BufferedRandom.
    
    It is also possible to use a string or bytearray as a file for both
    reading and writing. For strings StringIO can be used like a file
    opened in a text mode, and for bytes a BytesIO can be used like a file
    opened in a binary mode.


In [12]:
video.poster.save(name, content, save=False)


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-12-c334744140a8> in <module>()
----> 1 video.poster.save(name, content, save=False)

~/.virtualenvs/homepage/lib/python3.7/site-packages/django/db/models/fields/files.py in save(self, name, content, save)
     85     def save(self, name, content, save=True):
     86         name = self.field.generate_filename(self.instance, name)
---> 87         self.name = self.storage.save(name, content, max_length=self.field.max_length)
     88         setattr(self.instance, self.field.name, self.name)
     89         self._committed = True

~/.virtualenvs/homepage/lib/python3.7/site-packages/django/core/files/storage.py in save(self, name, content, max_length)
     47 
     48         name = self.get_available_name(name, max_length=max_length)
---> 49         return self._save(name, content)
     50 
     51     # These methods are part of the public API, with default implementations.

~/.virtualenvs/homepage/lib/python3.7/site-packages/django/core/files/storage.py in _save(self, name, content)
    266                     try:
    267                         locks.lock(fd, locks.LOCK_EX)
--> 268                         for chunk in content.chunks():
    269                             if _file is None:
    270                                 mode = 'wb' if isinstance(chunk, bytes) else 'wt'

~/.virtualenvs/homepage/lib/python3.7/site-packages/django/core/files/base.py in chunks(self, chunk_size)
     58 
     59         while True:
---> 60             data = self.read(chunk_size)
     61             if not data:
     62                 break

~/.virtualenvs/homepage/lib/python3.7/site-packages/django/core/files/utils.py in <lambda>(self)
     14     isatty = property(lambda self: self.file.isatty)
     15     newlines = property(lambda self: self.file.newlines)
---> 16     read = property(lambda self: self.file.read)
     17     readinto = property(lambda self: self.file.readinto)
     18     readline = property(lambda self: self.file.readline)

AttributeError: 'File' object has no attribute 'read'

In [19]:
video.poster.field.max_length


Out[19]:
100

In [20]:
video.poster.storage.save(name, content, max_length=video.poster.field.max_length)


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-20-ab880aa19322> in <module>()
----> 1 video.poster.storage.save(name, content, max_length=video.poster.field.max_length)

~/.virtualenvs/homepage/lib/python3.7/site-packages/django/core/files/storage.py in save(self, name, content, max_length)
     47 
     48         name = self.get_available_name(name, max_length=max_length)
---> 49         return self._save(name, content)
     50 
     51     # These methods are part of the public API, with default implementations.

~/.virtualenvs/homepage/lib/python3.7/site-packages/django/core/files/storage.py in _save(self, name, content)
    266                     try:
    267                         locks.lock(fd, locks.LOCK_EX)
--> 268                         for chunk in content.chunks():
    269                             if _file is None:
    270                                 mode = 'wb' if isinstance(chunk, bytes) else 'wt'

~/.virtualenvs/homepage/lib/python3.7/site-packages/django/core/files/base.py in chunks(self, chunk_size)
     58 
     59         while True:
---> 60             data = self.read(chunk_size)
     61             if not data:
     62                 break

~/.virtualenvs/homepage/lib/python3.7/site-packages/django/core/files/utils.py in <lambda>(self)
     14     isatty = property(lambda self: self.file.isatty)
     15     newlines = property(lambda self: self.file.newlines)
---> 16     read = property(lambda self: self.file.read)
     17     readinto = property(lambda self: self.file.readinto)
     18     readline = property(lambda self: self.file.readline)

AttributeError: 'File' object has no attribute 'read'

In [21]:
video.poster.storage._save(name, content)


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-21-d8be70621cec> in <module>()
----> 1 video.poster.storage._save(name, content)

~/.virtualenvs/homepage/lib/python3.7/site-packages/django/core/files/storage.py in _save(self, name, content)
    266                     try:
    267                         locks.lock(fd, locks.LOCK_EX)
--> 268                         for chunk in content.chunks():
    269                             if _file is None:
    270                                 mode = 'wb' if isinstance(chunk, bytes) else 'wt'

AttributeError: 'File' object has no attribute 'chunks'

In [23]:
content.chunks


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-23-9af485418b76> in <module>()
----> 1 content.chunks

AttributeError: 'File' object has no attribute 'chunks'

In [15]:
content.file.read


Out[15]:
<function BufferedReader.read(size=-1, /)>

In [22]:
video.poster


Out[22]:
<ImageFieldFile: blogs_videos/poster/poster_j3ddhwqm.jpg>

In [21]:
video.save()

In [6]:
video._create_poster()


fh:  <_io.FileIO name='/var/folders/2l/7zccp5bs1234yz4ns62s796m0000gn/T/poster_fyr6w6c_.jpg' mode='rb' closefd=True>
content:  File object (<_io.FileIO name='/var/folders/2l/7zccp5bs1234yz4ns62s796m0000gn/T/poster_fyr6w6c_.jpg' mode='rb' closefd=True>)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-6-9a46d2734f29> in <module>()
----> 1 video._create_poster()

~/projects/django-cast/cast/models.py in _create_poster(self)
    159             content = File(fh)
    160             print("content: ", content)
--> 161             self.poster.save(name, content, save=False)
    162         os.unlink(tmp_path)
    163         logger.info(self.pk)

~/.virtualenvs/homepage/lib/python3.7/site-packages/django/db/models/fields/files.py in save(self, name, content, save)
     85     def save(self, name, content, save=True):
     86         name = self.field.generate_filename(self.instance, name)
---> 87         self.name = self.storage.save(name, content, max_length=self.field.max_length)
     88         setattr(self.instance, self.field.name, self.name)
     89         self._committed = True

~/.virtualenvs/homepage/lib/python3.7/site-packages/django/core/files/storage.py in save(self, name, content, max_length)
     47 
     48         name = self.get_available_name(name, max_length=max_length)
---> 49         return self._save(name, content)
     50 
     51     # These methods are part of the public API, with default implementations.

~/.virtualenvs/homepage/lib/python3.7/site-packages/django/core/files/storage.py in _save(self, name, content)
    266                     try:
    267                         locks.lock(fd, locks.LOCK_EX)
--> 268                         for chunk in content.chunks():
    269                             if _file is None:
    270                                 mode = 'wb' if isinstance(chunk, bytes) else 'wt'

~/.virtualenvs/homepage/lib/python3.7/site-packages/django/core/files/base.py in chunks(self, chunk_size)
     58 
     59         while True:
---> 60             data = self.read(chunk_size)
     61             if not data:
     62                 break

~/.virtualenvs/homepage/lib/python3.7/site-packages/django/core/files/utils.py in <lambda>(self)
     14     isatty = property(lambda self: self.file.isatty)
     15     newlines = property(lambda self: self.file.newlines)
---> 16     read = property(lambda self: self.file.read)
     17     readinto = property(lambda self: self.file.readinto)
     18     readline = property(lambda self: self.file.readline)

AttributeError: 'File' object has no attribute 'read'

In [11]:
video.poster


Out[11]:
<ImageFieldFile: blogs_videos/poster/poster_tq1kzqfv.jpg>

resetting autoincrement


In [215]:
from django.db import connection

In [ ]:
with connection.cursor() as cursor:
    cursor.execute("select max(id) from

In [ ]: