def test_was_published_recently_with_future_picture(self): """ was_published_recently() should return False for pictures whose pub_date is in the future. """ future_pic = Picture(name="Future picture", pub_date=timezone.now() + datetime.timedelta(days=30)) self.assertEqual(future_pic.was_published_recently(), False)
def test_was_published_recently_with_recent_picture(self): """ was_published_recently() should return True for pictures whose pub_date is within the last day. """ recent_pic = Picture(name="Recent picture", pub_date=timezone.now() - datetime.timedelta(hours=1)) self.assertEqual(recent_pic.was_published_recently(), True)
def test_was_published_recently_with_old_picture(self): """ was_published_recently() should return False for pictures whose pub_date is older than 1 day. """ old_pic = Picture(name="Old picture", pub_date=timezone.now() - datetime.timedelta(days=2)) self.assertEqual(old_pic.was_published_recently(), False)
def upload_view(request): if request.method == 'POST': form = UploadPictureForm(request.POST, request.FILES) if form.is_valid(): img = request.FILES['image'] notes = request.POST['notes'] new_picture = Picture(image=img, notes=notes) new_picture.save() return HttpResponseRedirect('/') else: return HttpResponseRedirect('/err')
def review_picture(request, key, name): picture = Picture.get(db.Key(key)) query_list_image = Picture.all().filter("album", picture.album).fetch(999) try: next = query_list_image[query_list_image.index(picture)+1] except: next = False try: if not query_list_image.index(picture)==0: last = query_list_image[query_list_image.index(picture)-1] else: last = False except: last = False return render_to_response('view_picture.html', {'picture':picture, 'next':next, 'last':last, 'user': request.user})
def download_file(request, key, name): """ Отдаем картинку из БД по ключу и имени файла получаемые из запроса по url'у""" file = memcache.get("full_" + key) if file is not None: current_time = datetime.datetime.utcnow() response = HttpResponse() last_modified = current_time - datetime.timedelta(days=1) response['Content-Type'] = 'image/jpg' response['Last-Modified'] = last_modified.strftime( '%a, %d %b %Y %H:%M:%S GMT') response['Expires'] = current_time + datetime.timedelta(days=30) response['Cache-Control'] = 'public, max-age=315360000' response['Date'] = current_time response.content = file return response else: file = Picture.get(db.Key(key)) memcache.add("full_" + key, file.data) if file.name != name: raise Http404( 'Could not find file with this name!' ) # если имя файла не соответсвует существующему то выводим сообщение return HttpResponse( file.data, # content_type='image/png', mimetype='image/png')
def setUpClass(cls): """Method called to prepare the test fixture.""" super(BaseModelTestCase, cls).setUpClass() # create user cls.User = get_user_model() cls.user = cls.User.objects.create(username='******', email='*****@*****.**', password='******') # create contest cls.contest = Contest( title="Concours test", theme="Concours de test", description="Description test", date_begin_upload=date(2020, 12, 1), date_end_upload=date(2020, 12, 31), date_begin_vote=date(2021, 1, 1), date_end_vote=date(2021, 1, 31), date_creation=datetime.now(), ) cls.picture = Picture( title='test_title', # file_name=image_file, description='test_description', technical='test_technical', camera='test_camera', place='test_place', taken_date=date(2021, 1, 1), # global_score = 0, user=cls.user, upload_date=datetime.now(), ) cls.picture.save()
def clear_old_picture(request): """ Функция для выполнения в cron Удаляет изображения старше * дней (значение берется из настроек в БД) """ try: days = Settings.all().get().days_for_old_picture except: days = getattr(settings, 'DAYS_FOR_OLD_PICTURE', 30) query = Picture.all().filter( "submitted_date <", datetime.datetime.today() - datetime.timedelta(days=days)) response = HttpResponse() for pic in query: response.write("<br/>Delete: " + str(pic.name)) # код для контролирования кол-ва занимаемого места user_free_size = User.get(pic.submitter.key()) user_free_size.free_size = user_free_size.free_size + len( pic.data) + len(pic.data_small) + len(pic.data_cover) user_free_size.put() pic.delete() response.write("<br/>Delete END: " + str(len(query))) return response
def thumbnail(id, width, height, ext): key = db.Key(id) picture = Picture.get(key) img = images.Image(picture.data) if width != '0': w = int(width) else: w = img.width if height != '0': h = int(height) else: h = img.height if img.height > h and h != 0: w = (int(width) * img.width) / img.height; if img.width > w: h = (int(height) * img.height) / img.width; thumb = images.resize(picture.data, width=w, height=h) response = make_response(thumb) response.headers['Content-Type'] = picture.content_type return response
def picture_carousel(request, key): if request.user.is_authenticated(): return object_list(request, Picture.all().filter("album", db.Key(key)), template_name='picture_carousel.html') else: return HttpResponseRedirect('/account/login/')
def thumbnail(id, width, height, ext): key = db.Key(id) picture = Picture.get(key) img = images.Image(picture.data) if width != '0': w = int(width) else: w = img.width if height != '0': h = int(height) else: h = img.height if img.height > h and h != 0: w = (int(width) * img.width) / img.height if img.width > w: h = (int(height) * img.height) / img.width thumb = images.resize(picture.data, width=w, height=h) response = make_response(thumb) response.headers['Content-Type'] = picture.content_type return response
def setUpClass(cls): """Method called to prepare the test fixture.""" super(BaseViewTestCase, cls).setUpClass() # create user cls.user = get_user_model().objects.create(username='******', email='*****@*****.**') cls.user.set_password('123test') cls.user.save() # create picture small_gif = ( b'\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x00\x00\x00\x21\xf9\x04' b'\x01\x0a\x00\x01\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02' b'\x02\x4c\x01\x00\x3b') cls.picture = Picture( title='test_title', file_name=SimpleUploadedFile(name='small.gif', content=small_gif, content_type='image/gif'), description='test_description', technical='test_technical', camera='test_camera', place='test_place', taken_date=date(2021, 1, 1), user=cls.user, upload_date=datetime.now(), ) cls.picture.save() # create contests vote cls.contest = Contest( title='contest_vote', theme='contest_theme_vote', description='contest_description_vote', date_begin_upload=date(2020, 12, 1), date_end_upload=date(2020, 12, 31), deposit=False, date_begin_vote=date(2021, 1, 1), date_end_vote=date(2021, 1, 31), vote_open=True, archived=False, date_creation=datetime.now(), contest_image=SimpleUploadedFile(name='small.gif', content=small_gif, content_type='image/gif'), ) cls.contest.save() # add picture to contest cls.contest_picture = ContestPicture(picture=cls.picture, contest=cls.contest) cls.contest_picture.save() # user login cls.client_login = Client(HTTP_REFERER=reverse('gallery:home')) cls.logged_in = cls.client_login.login(username='******', password='******')
def edit_picture(id): key = db.Key(id) picture = Picture.get(key) form = PictureForm(request.form, picture) return render_template('admin/pictures/edit.html', title=u'Редактировать рисунок', form=form, picture=picture)
def add_picture(request): global user picture_form = PictureForm args = {} args.update(csrf(request)) args['form'] = picture_form args['username'] = username(request.session.get('user')) if request.POST: file = request.FILES['file'] form = PictureForm(request.POST, request.FILES) if form.is_valid(): print('VALID') image, miniature = encode_picture(request.FILES['file']) user = User.objects.get(pk=request.session.get('user')) pic = Picture(name_of_picture=request.POST['name_of_picture'], pictures=image) pic.id_user = user pic.save() mini = Picture.objects.get(id=pic.id) mini_p = Picture( # create a miniature picture id_pictures_id=mini.id, pictures=miniature, name_of_picture=mini.name_of_picture, id_user_id=mini.id_user_id ) mini_p.save() else: print("NOT VALID") else: return render_to_response('add_picture.html', args) return redirect('/profile/%s/' % user.id_users)
def add_picture(request): form = PictureForm(request.POST, request.FILES) print(form) if form.is_valid(): print('VALID', request.POST) image = encode_picture(request.FILES['file']) miniature= resize_picture(image) size = picture_size(image) user = User.objects.get(pk=request.session.get('user')) pic = Picture(name_of_picture=form.cleaned_data['name_of_picture'], pictures=image, public=int(form.cleaned_data['check']), picture_size=size ) pic.id_user = user pic.save() mini = Picture.objects.get(id=pic.id) mini_p = Picture( # create a miniature picture id_pictures_id=mini.id, pictures=miniature, name_of_picture=mini.name_of_picture, id_user_id=mini.id_user_id, public=int(form.cleaned_data['check']) ) mini_p.save() else: print("NOT VALID")
def delete_picture(request, key): """ Удаление изображения по ключу передаваемого из url'а """ if request.user.is_authenticated(): pic = Picture.get(db.Key(key)) size = len(pic.data)+len(pic.data_cover)+len(pic.data_small) return delete_object(request, Picture, object_id=db.Key(key), post_delete_redirect=reverse('gallery.views.delete_picture_ok', args=[size])) else: return HttpResponseRedirect('/account/login/')
def review_picture(request, key, name): picture = Picture.get(db.Key(key)) query_list_image = Picture.all().filter("album", picture.album).fetch(999) try: next = query_list_image[query_list_image.index(picture) + 1] except: next = False try: if not query_list_image.index(picture) == 0: last = query_list_image[query_list_image.index(picture) - 1] else: last = False except: last = False return render_to_response('view_picture.html', { 'picture': picture, 'next': next, 'last': last, 'user': request.user })
def index(): pictures = Picture.all().filter('status = ', 1) return render_template( 'frontend/index.html', pictures=pictures, title=u'Авторская галлерея', keywords= u"жанр, фэнтези, галереи, арт, художник, аватары, картинки, рисунки, в стиле фэнтези, драконы, эльфы, оборотни, абстратное фентези", description= u"галереи фэнтези, авторские работы, профессиональные авторские рисунки в стиле фентези" )
def delete_picture(request, key): """ Удаление изображения по ключу передаваемого из url'а """ if request.user.is_authenticated(): pic = Picture.get(db.Key(key)) size = len(pic.data) + len(pic.data_cover) + len(pic.data_small) return delete_object(request, Picture, object_id=db.Key(key), post_delete_redirect=reverse( 'gallery.views.delete_picture_ok', args=[size])) else: return HttpResponseRedirect('/account/login/')
def create_picture(): picture = Picture() form = PictureForm(request.form, picture) if form.validate() and request.files['file']: form.populate_obj(picture) picture.data = request.files['file'].read() picture.ext = request.files['file'].filename.rsplit('.', 1)[1] picture.content_type = request.files['file'].content_type picture.put() flash(u'Рисунок успешно добавлен', 'correct') return redirect(url_for("edit_picture", id=picture.key())) else: return render_template('admin/pictures/new.html', title=u'Добавить рисунок', form=form)
def update_picture(id): key = db.Key(id) picture = Picture.get(key) form = PictureForm(request.form, picture) if form.validate(): form.populate_obj(picture) if request.files['file']: picture.data = request.files['file'].read() picture.ext = request.files['file'].filename.rsplit('.', 1)[1] picture.content_type = request.files['file'].content_type picture.put() flash(u'Рисунок успешно сохранен', 'correct') return redirect(url_for("edit_picture", id=picture.key())) else: return render_template('admin/pictures/edit.html', title=u'Редактировать рисунок', form=form, picture=picture)
def delete_album_ok(request, key): """ при успешном удаление альбома, освобождаем свободное место пользователя """ if request.user.is_authenticated(): pictures = Picture.all().filter('album', db.Key(key)).fetch(999) size = 0 for pic in pictures: size = size + len(pic.data) + len(pic.data_cover) + len(pic.data_small) pic.delete() # код для контролирования кол-ва занимаемого места user_free_size = User.get(request.user.key()) user_free_size.free_size = user_free_size.free_size + size user_free_size.put() return HttpResponseRedirect('/gallery') else: return HttpResponseRedirect('/account/login/')
def delete_album_ok(request, key): """ при успешном удаление альбома, освобождаем свободное место пользователя """ if request.user.is_authenticated(): pictures = Picture.all().filter('album', db.Key(key)).fetch(999) size = 0 for pic in pictures: size = size + len(pic.data) + len(pic.data_cover) + len( pic.data_small) pic.delete() # код для контролирования кол-ва занимаемого места user_free_size = User.get(request.user.key()) user_free_size.free_size = user_free_size.free_size + size user_free_size.put() return HttpResponseRedirect('/gallery') else: return HttpResponseRedirect('/account/login/')
def show_album(request, key): """ Выводит изображения альбома. Выборку делаем по ключу. """ if request.user.is_authenticated(): pic_list = Picture.all().filter("album", db.Key(key)) paginator = Paginator(pic_list, 10) try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 try: pic = paginator.page(page) except (EmptyPage, InvalidPage): pic = paginator.page(paginator.num_pages) return render_to_response('picture_list.html', {"pics": pic, "user":request.user}) else: return HttpResponseRedirect('/account/login/')
def setUpClass(cls): """Method called to prepare the test fixture.""" super(BaseViewTestCase, cls).setUpClass() # create user cls.user = get_user_model().objects.create( username='******', email='*****@*****.**' ) cls.user.set_password('123test') cls.user.save() # create pictures small_gif = ( b'\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x00\x00\x00\x21\xf9\x04' b'\x01\x0a\x00\x01\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02' b'\x02\x4c\x01\x00\x3b' ) cls.picture = Picture( title='test_title', file_name=SimpleUploadedFile( name='small.gif', content=small_gif, content_type='image/gif'), description='test_description', technical='test_technical', camera='test_camera', place='test_place', taken_date=date(2021, 1, 1), user=cls.user, upload_date=datetime.now(), ) cls.picture.save() cls.review = Review( score_intention=4, score_technical=4, score_picture=4, score_global=4, comment_intention="test", picture=cls.picture, user=cls.user ) cls.review.save() cls.client_login = Client(HTTP_REFERER=reverse('gallery:home')) cls.logged_in = cls.client_login.login( username='******', password='******')
def setUpClass(cls): """Method called to prepare the test fixture.""" super(BaseViewTestCase, cls).setUpClass() # create user cls.User = get_user_model() cls.user = cls.User.objects.create(username='******', email='*****@*****.**') cls.user.set_password('123test') cls.user.save() # create pictures cls.pictures = [] cls.small_gif = ( b'\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x00\x00\x00\x21\xf9\x04' b'\x01\x0a\x00\x01\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02' b'\x02\x4c\x01\x00\x3b') cls.file_picture = SimpleUploadedFile(name='small.gif', content=cls.small_gif, content_type='image/gif') for indice in range(1, 9): cls.picture = Picture( title='test_title_%s' % indice, file_name=cls.file_picture, description='test_description', technical='test_technical', camera='test_camera', place='test_place', taken_date=date(2021, 1, 1), user=cls.user, upload_date=datetime.now(), ) cls.picture.save() cls.pictures.append(cls.picture) # create categories for indice in range(1, 6): cls.category = Category(name="category_test_%s" % indice, in_menu=True, order_menu=1) cls.category.save() cls.pictures[0].categories.add(cls.category) cls.client_login = Client(HTTP_REFERER=reverse('gallery:home')) cls.logged_in = cls.client_login.login(username='******', password='******')
def setUpClass(cls): """Method called to prepare the test fixture.""" super(BaseModelTestCase, cls).setUpClass() # create user cls.User = get_user_model() cls.user = cls.User.objects.create( username='******', email='*****@*****.**', password='******' ) # create category cls.category = Category( name="category_test", in_menu=True, order_menu=1 ) cls.category.save() # create pictures cls.pictures = [] small_gif = ( b'\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x00\x00\x00\x21\xf9\x04' b'\x01\x0a\x00\x01\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02' b'\x02\x4c\x01\x00\x3b' ) cls.picture = Picture( title='test_title', file_name=SimpleUploadedFile(name='small.gif', content=small_gif, content_type='image/gif'), description='test_description', technical='test_technical', camera='test_camera', place='test_place', taken_date=date(2021, 1, 1), # global_score = 0, user=cls.user, upload_date=datetime.now(), ) cls.picture.save() cls.picture.categories.add(cls.category)
def show_album(request, key): """ Выводит изображения альбома. Выборку делаем по ключу. """ if request.user.is_authenticated(): pic_list = Picture.all().filter("album", db.Key(key)) paginator = Paginator(pic_list, 10) try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 try: pic = paginator.page(page) except (EmptyPage, InvalidPage): pic = paginator.page(paginator.num_pages) return render_to_response('picture_list.html', { "pics": pic, "user": request.user }) else: return HttpResponseRedirect('/account/login/')
def download_small(request, key, name): """ Отдаем картинку из БД по ключу и имени файла получаемые из запроса по url'у""" file = memcache.get("small_" + key) if file is not None: current_time = datetime.datetime.utcnow() response = HttpResponse() last_modified = current_time - datetime.timedelta(days=1) response['Content-Type'] = 'image/jpg' response['Last-Modified'] = last_modified.strftime('%a, %d %b %Y %H:%M:%S GMT') response['Expires'] = current_time + datetime.timedelta(days=30) response['Cache-Control'] = 'public, max-age=315360000' response['Date'] = current_time response.content = file return response else: file = Picture.get(db.Key(key)) memcache.add("small_" + key, file.data) if file.name != name: raise Http404('Could not find file with this name!') return HttpResponse(file.data_small, content_type='image/png', mimetype='image/png')
def clear_old_picture(request): """ Функция для выполнения в cron Удаляет изображения старше * дней (значение берется из настроек в БД) """ try: days = Settings.all().get().days_for_old_picture except: days = getattr(settings, 'DAYS_FOR_OLD_PICTURE', 30) query = Picture.all().filter("submitted_date <", datetime.datetime.today() - datetime.timedelta(days=days)) response = HttpResponse() for pic in query: response.write("<br/>Delete: "+str(pic.name)) # код для контролирования кол-ва занимаемого места user_free_size = User.get(pic.submitter.key()) user_free_size.free_size = user_free_size.free_size + len(pic.data) + len(pic.data_small) + len(pic.data_cover) user_free_size.put() pic.delete() response.write("<br/>Delete END: "+str(len(query))) return response
def index(): pictures = Picture.all().filter('status = ', 1) return render_template('frontend/index.html', pictures=pictures, title=u'Авторская галлерея', keywords=u"жанр, фэнтези, галереи, арт, художник, аватары, картинки, рисунки, в стиле фэнтези, драконы, эльфы, оборотни, абстратное фентези", description=u"галереи фэнтези, авторские работы, профессиональные авторские рисунки в стиле фентези")
def pictures(): pictures = Picture.all() return render_template('admin/pictures/index.html', pictures=pictures, title=u'Рисунки')
def picture(id): key = db.Key(id) picture = Picture.all().filter('status = ', 1).filter('__key__ = ', key).get() return render_template('frontend/picture.html', picture=picture)