def add_img_to_wagtail(path): root = 'http://libraries.cca.edu/' # our query returns a file path, not a URL, so there can be spaces img_url = root + path.replace(' ', '%20') filename = path.split('/')[-1] # Creating image object from URL based off of this gist: # https://gist.github.com/eyesee1/1ea8e1b90bfe632cd31f5a90afc0370c response = requests.get(img_url) image = Image.objects.create(title=filename, file=ImageFile(BytesIO(response.content), name=filename)) # for some reason .create() returns a tuple? # we want to return The Thing Itself instead, unencased return image[0]
def clean(self, value, row=None, *args, **kwargs): p = self.get_queryset(value, row) p.images.all().delete() if value: for item in value.split(self.separator): if item: u, c = item.split(':') if u and c: p.images.create(caption=c, image=ImageFile( File( open(settings.BASE_DIR + u, 'rb') ), name=os.path.basename(u))) return p.images.all()
def fill_drawings(user): drawings = user.drawing_set.all() basepath = os.getcwd() for i in range(26): labeled = drawings.filter(label_index=i) if len(labeled) == 0: path = os.path.join(basepath, os.path.join('textify', os.path.join('handwritten', str(i)))) files = os.listdir(path) for file in files: if file != 'Thumbs.db' and file != 'data': img = ImageFile(open(os.path.join(path, file), 'rb')) db_pic = Drawing(user_id=user.id, name=file, label_index=i, label=symbols[i]) db_pic.image.save(basepath + '/user_files/drawings/' + str(uuid.uuid4()) + '.png', img, True)
def test_post_exists(self): """Проверка наличия поста со всеми полями""" post = Post.objects.create(text='text', author=self.user, group=self.group, image=ImageFile(self.create_image())) urls = self.get_the_urls(user=self.user, post=post, group=self.group) cache.clear() for url in urls: self.check_post_on_page(url=url, text=post.text, author=post.author, group=post.group, image=post.image)
def add_initial_books_and_authors(apps, _schema_editor): Book = apps.get_model('app', 'Book') Author = apps.get_model('app', 'Author') for book_data in books: author_names = book_data.pop('authors') img_path = book_data.pop('img_path') price = book_data.pop('price_cents') / 100 book = Book.objects.create( cover_image=ImageFile(open('initial_book_images/' + img_path, 'rb'), name=img_path), price=price, **book_data) for name in author_names: author, _created = Author.objects.get_or_create(name=name) book.authors.add(author)
def test_compute_diff_without_tolerance(self): """ Check difference is found between two different images """ with open("snapshotServer/tests/data/test_Image1.png", 'rb') as reference: with open("snapshotServer/tests/data/test_Image1Mod.png", 'rb') as step: img_reference = ImageFile(reference) img_step = ImageFile(step) ref_snapshot = Snapshot( stepResult=StepResult.objects.get(id=1), refSnapshot=None, pixelsDiff=None) ref_snapshot.save() ref_snapshot.image.save("img", img_reference) ref_snapshot.save() step_snapshot = Snapshot( stepResult=StepResult.objects.get(id=2), refSnapshot=None, pixelsDiff=None) step_snapshot.save() step_snapshot.image.save("img", img_step) step_snapshot.save() DiffComputer.get_instance().compute_now( ref_snapshot, step_snapshot) # something has been computed self.assertIsNotNone(step_snapshot.pixelsDiff) self.assertTrue(step_snapshot.tooManyDiffs) self.assertEqual(step_snapshot.refSnapshot, ref_snapshot, "refSnapshot should have been updated") self.assertTrue(step_snapshot.computed) self.assertTrue(step_snapshot.computingError == '')
def setUp(self): """ Sets up a test individual prize for the rest of the tests. This prize is not saved, as the round field is not yet set. """ image_path = os.path.join(settings.PROJECT_ROOT, "fixtures", "test_images", "test.jpg") image = ImageFile(open(image_path, "r")) self.prize = Prize( title="Super prize!", short_description="A test prize", long_description="A test prize", image=image, award_to="individual_floor", competition_type="points", value=5, ) self.saved_rounds = settings.COMPETITION_ROUNDS self.current_round = "Round 1" start = datetime.date.today() end = start + datetime.timedelta(days=7) settings.COMPETITION_ROUNDS = { "Round 1": { "start": start.strftime("%Y-%m-%d"), "end": end.strftime("%Y-%m-%d"), }, } # Create test dorms, floors, and users. self.dorm = Dorm(name="Test Dorm") self.dorm.save() self.floors = [ Floor(number=str(i), dorm=self.dorm) for i in range(0, 2) ] map(lambda f: f.save(), self.floors) self.users = [ User.objects.create_user("test%d" % i, "*****@*****.**") for i in range(0, 4) ] # Assign users to floors. for index, user in enumerate(self.users): user.get_profile().floor = self.floors[index % 2] user.get_profile().save()
def upload_file(request): print(request.POST) attachment_form = AttachmentForm(request.POST) if attachment_form.is_valid(): attachment = attachment_form.save() print(attachment.chat_id) chat = Chat.objects.all().filter(id=attachment.chat_id)[0] # user = UserProfile.objects.all().filter(id=request.user.id)[0] user = request.user message = Message.objects.create(chat=chat, user=user, content="Вложение") attachment.message = message attachment.image = ImageFile(open(attachment.key, 'rb')) attachment.type_attachment = magic.from_buffer( (open(attachment.key, 'rb')).read(), mime=True) attachment.save() members = Member.objects.all().filter(chat=attachment.chat_id).exclude( user=user.id) for member in members: if member.new_messages is None: member.new_messages = 0 member.new_messages += 1 member.save() user_member = Member.objects.all().filter(user=user.id, chat=attachment.chat_id)[0] user_member.new_messages = 0 user_member.last_read_message = message user_member.save() chat = Chat.objects.all().filter(id=message.chat_id)[0] chat.last_message = message chat.save() response = { "response": "attachment sent", "user_id": message.user_id, "chat_id": message.chat_id, "added_at": message.added_at, "content": message.content, "attachment_key": attachment.key } return JsonResponse(response) return JsonResponse({"errors": attachment_form.errors}, status=400)
def load_blog(self, item): """ Import content as blog entry :param item: entry in json format """ slug = item['slug'] if Entry.objects.filter(slug=slug).exists(): return status_dict = { 'draft': DRAFT, 'publish': PUBLISHED, } content = self.linebreaks(self.process_images(item['content'])) entry = Entry( title=item['title'], slug=slug, status=status_dict[item['post_status']], creation_date=self.localtime(item['date']), content=content, ) if item['meta'].get('author'): entry.display_author = item['meta']['author'].split(',')[0] if item['tags'] and item['tags'].strip(): entry.tags = item['tags'] if item['thumbnail']: resp = requests.get(item['thumbnail']) entry.image.save(item['thumbnail'].split('/')[-1], ImageFile(StringIO(resp.content)), save=False) entry.save() entry.sites.add(Site.objects.get_current()) for category_title in item['categories'].split(', '): if category_title and category_title.strip(): category_slug = slugify(category_title) category, _ = Category.objects.get_or_create( slug=category_slug, defaults={'title': category_title}) entry.categories.add(category)
def index(request): if not Image.objects.filter(pk=1).exists(): image_ = Image.objects.create(user=get_object_or_404(User, id=1)) image_.image = ImageFile(open("static/img/bg-masthead.jpg", "rb")) image_.save() liked_images = None queryset_list = Image.objects.all().exclude(id=1).annotate( popularity=(F('download_count') + Count('likes'))).order_by('-popularity')[:10] if request.user.is_authenticated: liked_images = Image.objects.filter(likes=request.user) context = { "imagesList": queryset_list, "likedImages": liked_images, } return render(request, "index.html", context)
def test_thumbnails_are_generated_on_save(self): product = models.Product(name='The cathedral and the bazaar', price=Decimal('10.00')) product.save() with open('main/fixtures/dark-mode.PNG', 'rb') as f: image = models.ProductImage( product=product, image=ImageFile(f, name='tctb.jpg'), ) image.save() image.refresh_from_db() image.thumbnail.delete(save=False) image.image.delete(save=False)
def create_meta_data(picture_name: str, slug: str) -> None: """Создаёт инстанс метаданных""" width, high = _get_size(picture_name) average_color = _get_average_color(picture_name) number_of_coins = _count_objects(picture_name) image_instance = Image.objects.get(slug=slug) _get_medium_picture(picture_name) ImageMetaData.objects.create( image=image_instance, high=str(high), width=str(width), average_color=str(average_color), average_color_image=ImageFile(open(f'median-{picture_name}', 'rb')), number_of_coins=int(number_of_coins), # я что дата сайнтист?? # я не знаю как пользоваться cv2 sum_of_coins=105)
def set_images(self): films = parser.get_films() for film in films: r = requests.get(film['image']) film_ob = FilmORM.objects.filter(title=film['title']).first() name = film['image'].split('/')[5] print(name) f = open(name, "wb+") f.write(r.content) djangofile = ImageFile(f) film_ob.image.save('new', djangofile) f.close() os.remove(name)
def upload_image_to_s3(image_url): """ Download image from a given `image_url` and upload to Amazon S3. :param image_url: URL of image to download :return: django-filer Image object """ response = requests.get(image_url) file_obj = ImageFile(StringIO(response.content)) file_name = generate_image_filename(file_obj) file_obj.name = file_name image = Image.objects.create(original_filename=file_name, file=file_obj) return image
def test_thumbnail_are_generated_on_save(self): product = models.Product(name='Laptop',price=Decimal('150.00'),) product.save() with open('main/fixtures/jacket.jpg',"rb") as f: image = models.ProductImage(product=product,image=ImageFile(f,name="tctb.jpg"),) with self.assertLogs("main",level="INFO") as cm: image.save() self.assertGreaterEqual(len(cm.output),1) image.refresh_from_db() with open("main/fixtures/jacket.thumb.jpg","rb",) as f: expected_content = f.read() assert image.thumbnail.read() == expected_content image.thumbnail.delete(save=False) image.image.delete(save=False)
def add_venue(name, address, views, likes, photo, latitude, longitude, info, instagram, twitter, facebook): v = Venue.objects.get_or_create(name=name)[0] v.name = name v.address = address v.views = views v.likes = likes v.photo = ImageFile(open(photo, "rb")) v.latitude = latitude v.longitude = longitude v.info = info v.instagram = instagram v.twitter = twitter v.facebook = facebook v.save() return v
def test_get(self): """Test GET when there are odlcs.""" odlc = Odlc(user=self.team, odlc_type=OdlcType.standard) odlc.save() with open(test_image('A.jpg'), 'rb') as f: odlc.thumbnail.save('%d.%s' % (odlc.pk, 'jpg'), ImageFile(f)) odlc.save() response = self.client.get(odlcs_review_url) self.assertEqual(200, response.status_code) data = json.loads(response.content) self.assertEqual(1, len(data)) self.assertIn('odlc', data[0]) self.assertIn('type', data[0]['odlc']) self.assertEqual('STANDARD', data[0]['odlc']['type'])
def setup_prize(award_to, competition_type): """set the prize for testing""" image_path = os.path.join(settings.PROJECT_ROOT, "fixtures", "test_images", "test.jpg") image = ImageFile(open(image_path, "r")) prize = Prize( title="Super prize!", short_description="A test prize", long_description="A test prize", image=image, award_to=award_to, competition_type=competition_type, value=5, ) prize.save() return prize
def make_alternate(self, size): from io import BytesIO from PIL import Image im = Image.open(self.image.open()) im.thumbnail((size, size)) thumb_image = BytesIO() im.save(thumb_image, im.format) original_path = PurePath(self.image.name) new_name = f"{original_path.stem}_{im.width}x{im.width}{original_path.suffix}" image_file = ImageFile(thumb_image, name=new_name) self.alternates.create(image=image_file)
def convert(request): print request.FILES files = request.FILES['pic'] content = ImageFile(files.read()) img = cv2.imdecode(np.fromstring(content.file, np.uint8), 0) print 'SHAPE', img.shape cv2.imwrite('input.jpg', img) img = cv2.imread('input.jpg', 0) gen = img2img(img) cv2.imwrite('output.jpg', gen) #1 # pprint (dir(request)) # pdb.set_trace() # print request.params return HttpResponse("hi")
def _fetch_icon_from(service): if not service.icon_url: return None try: response = requests.get(service.icon_url, timeout=3) return ImageFile(BytesIO(response.content)) except: LOG.error('MPASS Service icon fetch failed', exc_info=True, extra={ 'data': { 'service_id': service.service_id, 'icon_url': service.icon_url } }) return None
def handle(self, *args, **options): for i in range(20): prod = Product() path = os.path.join(BASE_DIR, 'products/management/commands/res/img.png') prod.image = ImageFile(open(path, 'rb')) prod.save() for l, _ in ProductBody.languages: prod_body = ProductBody() prod_body.name = f"Test Продукт {l} {i}" prod_body.language = l prod_body.product = prod prod_body.save() self.stdout.write(self.style.SUCCESS('Test data created'))
def download_image(url): # Skip empty strings and strings that are not absolute urls. if not url or not rfc3987.match(url, 'absolute_URI'): return None, None # Get url. try: response = requests.get(url) except requests.exceptions.ConnectionError: return None, None if response.status_code == 200: image = BytesIO(response.content) # Check that the file is really an image. image_type = imghdr.what(image) if image_type: return ImageFile(image), image_type return None, None
def test_custom_model_with_file_field(self): with open(os.path.join(FIXTURES_DIR, 'wagtail.jpg'), 'rb') as f: avatar = Avatar.objects.create( image=ImageFile(f, name='wagtail.jpg')) response = self.get({'tests.avatar': [avatar.pk]}) self.assertEqual(response.status_code, 200) data = json.loads(response.content) self.assertEqual(len(data['objects']), 1) obj = data['objects'][0] self.assertEqual(obj['fields']['image']['download_url'], 'http://media.example.com/media/avatars/wagtail.jpg') self.assertEqual(obj['fields']['image']['size'], 1160) self.assertEqual(obj['fields']['image']['hash'], '45c5db99aea04378498883b008ee07528f5ae416')
def handle(self, *args, **options): self.stdout.write("Importing products") c = Counter() reader = csv.DictReader(options.pop("csvfile")) for row in reader: product, created = models.Product.objects.get_or_create( name=row["name"], price=row["price"] ) product.description = row["description"] product.slug = slugify(row["name"]) for import_tag in row["tags"].split("|"): tag, tag_created = models.ProductTag.objects.get_or_create( name=import_tag ) product.tags.add(tag) c["tags"] += 1 if tag_created: c["tags_created"] += 1 with open( os.path.join( options["image_basedir"], row["image_filename"], ), "rb", ) as f: image = models.ProductImage( product=product, image=ImageFile( f, name=row["image_filename"] ), ) image.save() c["images"] += 1 product.save() c["products"] += 1 if created: c["products_created"] += 1 self.stdout.write( "Products processed=%d (created=%d)" % (c["products"], c["products_created"]) ) self.stdout.write( "Tags processed=%d (created=%d)" % (c["tags"], c["tags_created"]) ) self.stdout.write("Images processed=%d" % c["images"])
def handle(self, *args, **options): all_products = ProductPage.objects.all() total_products = all_products.count() try: pni_collection = Collection.objects.get(name="PNI Images") except Collection.DoesNotExist: root_collection = Collection.get_first_root_node() pni_collection = root_collection.add_child(name="PNI Images") for index, product in enumerate(all_products): print(f"Processing product {index+1} of {total_products}") if product.cloudinary_image: mime = MimeTypes() mime_type = mime.guess_type( product.cloudinary_image.url) # -> ('image/jpeg', None) if mime_type: mime_type = mime_type[0].split('/')[1].upper() else: # Default to a JPEG mimetype. mime_type = 'JPEG' # Temporarily download the image response = requests.get(product.cloudinary_image.url, stream=True) if response.status_code == 200: # Create an image out of the Cloudinary URL and write it to a PIL Image. pil_image = PILImage.open(response.raw) f = BytesIO() pil_image.save(f, mime_type) # Get the file name in a nice way. new_image_name = ntpath.basename( product.cloudinary_image.url) # Store the image as a WagtailImage object wagtail_image = WagtailImage.objects.create( title=new_image_name, file=ImageFile(f, name=new_image_name), collection=pni_collection) # Associate product.image with wagtail_image product.image = wagtail_image # Always generate a new revision. revision = product.save_revision() if product.live: # Re-publish existing "live" pages from the latest revision revision.publish()
def _get_local_path_or_file(self): # if file is in static instead of media directory, sorl raises # a suspicious operation error. So we open it safely without errors. if self.startswith('/'): if self.startswith('/static/'): path = self.replace('/static/', '') elif self.startswith(settings.STATIC_URL): path = self.replace(settings.STATIC_URL, '') else: return self.local_path else: return self.local_path path = finders.find(urllib.unquote(path)) image = ImageFile(open(path, 'r')) return image
def handle(self, *args, **options): for i in range(20): post = Post() path = os.path.join(BASE_DIR, 'blog/management/commands/res/img.jpg') post.image = ImageFile(open(path, 'rb')) post.save() for l, _ in PostBody.languages: post_body = PostBody() post_body.name = f"Test Заголовок {l} {i}" post_body.text = "Текст" post_body.language = l post_body.post = post post_body.save() self.stdout.write(self.style.SUCCESS('Test data created'))
def test_post_upload(self): f = BytesIO() image = PIL.Image.new('RGBA', (200, 200), 'white') image.save(f, 'PNG') image_file = ImageFile(f, name='test.png') response = self.client.post( '/parties/%d/edit_share_image/' % self.party.id, { 'share_image_file': SimpleUploadedFile('test.png', image_file.file.getvalue()) }) self.assertRedirects(response, '/parties/%d/' % self.party.id) party = Party.objects.get(id=self.party.id) self.assertTrue(party.share_image_file.name) self.assertTrue(party.share_image_file_url) self.assertEqual(party.share_image_url, party.share_image_file_url) Party.objects.get(id=self.party.id).share_image_file.delete()
def add_artist(name, genre, likes, views, youtube, instagram, soundcloud, twitter, facebook, info, photo, video): a = Artist.objects.get_or_create(name=name)[0] a.name = name a.genre = genre a.views = views a.likes = likes a.youtube = youtube a.instagram = instagram a.soundcloud = soundcloud a.twitter = twitter a.facebook = facebook a.info = info a.photo = ImageFile(open(photo, "rb")) a.video = video a.save() return a