def test_was_published_recently_with_future_album(self): """ was_published_recently() should return False for albums whose pub_date is in the future. """ future_album = Album(album_name="Future album", pub_date=timezone.now() + datetime.timedelta(days=30)) self.assertEqual(future_album.was_published_recently(), False)
def test_was_published_recently_with_old_album(self): """ was_published_recently() should return False for albums whose pub_date is older than 1 day. """ old_album = Album(album_name="Old album", pub_date=timezone.now() - datetime.timedelta(days=2)) self.assertEqual(old_album.was_published_recently(), False)
def test_was_published_recently_with_recent_album(self): """ was_published_recently() should return True for albums whose pub_date is within the last day. """ recent_album = Album(album_name="Recent album", pub_date=timezone.now() - datetime.timedelta(hours=1)) self.assertEqual(recent_album.was_published_recently(), True)
def import_albums(self, directory, pk_of_flickr_id): log.debug(f"Importing albums from directory {directory}") with open(f'{directory}/albums.json', 'rt') as f: for data in json.load(f)['albums']: photo_ids = [ pk_of_flickr_id[k] for k in data['photos'] if k != '0' ] photos = Photo.objects.filter( id__in=photo_ids ) # XXX can we use IDs instead of QuerySets later to avoid the SELECT? cover_photo_flickr_id = data['cover_photo'] assert cover_photo_flickr_id.startswith( 'https://www.flickr.com/photos//') cover_photo_flickr_id = cover_photo_flickr_id[31:] cover_photo_id = pk_of_flickr_id.get(cover_photo_flickr_id) created = datetime.fromtimestamp(int(data['created'])) created = make_aware(created) last_updated = datetime.fromtimestamp(int( data['last_updated'])) last_updated = make_aware(last_updated) album = Album(title=data['title'], description=data['description'], creation_date=created, modification_date=last_updated, cover_photo_id=cover_photo_id) album.save() album.photos.set(photos) log.debug(f"Created album model instance {album}")
def __init__(self, *args, **kwargs): super(PictureForm, self).__init__(*args, **kwargs) self.fields['album'].queryset = Album.all().filter("owner =", request.user) # переопределяем запрос так что бы выбор был только между альбомами владельцем которых является текущий пользователь (request.user) # query = Album.all().filter("owner =", request.user).fetch(999) album_list_name = [] # for data in query: # album_list_name.append((str(data.key()), data.name)) # self.fields['album'].choices = album_list_name self.fields['album'].choices = [(x.key(), x.name) for x in Album.all().filter("owner =", request.user)] # генератор списка кортежей для списка альбомов
def __init__(self, *args, **kwargs): super(PictureForm, self).__init__(*args, **kwargs) self.fields['album'].queryset = Album.all().filter( "owner =", request.user ) # переопределяем запрос так что бы выбор был только между альбомами владельцем которых является текущий пользователь (request.user) # query = Album.all().filter("owner =", request.user).fetch(999) album_list_name = [] # for data in query: # album_list_name.append((str(data.key()), data.name)) # self.fields['album'].choices = album_list_name self.fields['album'].choices = [ (x.key(), x.name) for x in Album.all().filter("owner =", request.user) ] # генератор списка кортежей для списка альбомов
def gallery(request): """ Выводит список альбомом. """ if request.user.is_authenticated(): return object_list(request, Album.all().filter("owner =", request.user)) else: return HttpResponseRedirect('/account/login/')
def list_album(request): """ Для desktop клиента отдаем список имен всех альбомов пользователя """ if request.user.is_authenticated(): return object_list(request, Album.all().filter("owner =", request.user), template_name="list_name.html") else: return HttpResponseRedirect('/account/login/')
def photo_load(request, slug): photos = get_object_or_404(Album, slug=slug) username = auth.get_user(request).username if request.user.is_authenticated(): user = User.objects.get(username=username) if user.has_module_perms('gallery'): if request.method == 'POST': form = PhotoForm(request.POST, request.FILES or None) if form.is_valid(): obj = Album(img=request.FILES['img']) obj = form.save(commit=False) obj.save() return render(request, 'photo_album.html', {'photos': photos, 'username': auth.get_user(request).username}) else: form = PhotoForm return render(request, 'photo_load.html', {'form': form, 'username': auth.get_user(request).username}) else: return render(request, 'photo_add.html') else: return render(request, 'photo_add.html') return render(request, 'photo_album.html', {'photos': photos, 'username': auth.get_user(request).username})
def create_album(request): if request.user.is_authenticated(): if request.method == "POST": name = request.POST['name'] path = os.path.join(MEDIA_ROOT, name) logger.debug('pppppath====%s', path) # 防止新建重复的相册 albums = Album.objects.filter(owner=request.user) for album in albums: if name in album.name: error = 'album already exist, please choose another name' return render_to_response('gallery/create_album.html', {'error': error}, context_instance=RequestContext(request)) al = Album(name=name, front_cover='', path=path, owner=request.user) al.save() logger.debug('create_album success') return HttpResponseRedirect('/gallery/create_album_success/') return render_to_response('gallery/create_album.html', {'request': request}, context_instance=RequestContext(request)) else: return HttpResponseRedirect('/login/')
def restore_album(d, s): adict = yaml.load(open(os.path.join(d, "info.yaml"))) a = Album() a.id = adict["id"] a.display_name = adict["display_name"] a.created = adict["created"] a.preview_id = adict["preview_id"] a.descr = adict["descr"] a.hidden = adict["hidden"] a.sort_by = adict["sort_by"] s.add(a) s.commit() for pdict in adict["photos"]: pfile = pdict["name"] if pfile in ["previews", "info.yaml"]: continue ppath = os.path.join(d, pfile) if os.path.isdir(ppath): continue p = Photo() p.id = pdict["id"] p.album_id = a.id p.name = pdict["name"] p.display_name = pdict["display_name"] p.created = pdict["created"] p.width = pdict["width"] p.height = pdict["height"] p.hidden = pdict["hidden"] photo_name = os.path.basename(p.get_path()) preview_name = os.path.basename(p.get_preview_path()) shutil.copy(os.path.join(d, photo_name), p.get_path()) shutil.copy(os.path.join(d, "previews", preview_name), p.get_preview_path()) s.add(p) for afile in os.listdir(d): if afile == "previews": continue apath = os.path.join(d, afile) if not os.path.isdir(apath): continue restore_album(apath, s)
def commitedit(album, req): if not req.params.get("commit"): return HTTPFound(location = req.resource_url(album)) s = DBSession() if req.params.get("new_album"): a = Album(parent_id = album.id) s.add(a) s.commit() else: a = album a.display_name = req.params.get("title") a.descr = req.params.get("description") a.hidden = bool(req.params.get("hide_album", 0)) a.sort_by = int(req.params.get("sort_by", 1)) new_thumb = req.params.get('album_thumbnail') print new_thumb, repr(new_thumb) if type(new_thumb) is types.InstanceType: old_preview = a.preview # add preview name = new_thumb.filename.lstrip(os.sep) preview = Photo(name, a.id, new_thumb.file.read()) new_thumb.file.close() preview.hidden = True s.add(preview) s.commit() a.preview_id = preview.id if old_preview: s.delete(old_preview) s.commit() return HTTPFound(location = req.resource_url(a))