def test_create_event_from_dict_with_all_fields(self): with open(local(__file__).dirname + "/../../static/img/team/alja.jpg") as fp: io = StringIO.StringIO() io.write(fp.read()) uploaded_picture = InMemoryUploadedFile(io, None, "alja.jpg", "jpeg", io.len, None) uploaded_picture.seek(0) event_data = { "end_date": datetime.datetime.now(), "start_date": datetime.datetime.now(), "organizer": "some organizer", "creator": User.objects.filter(pk=1)[0], "title": "event title", "pub_date": datetime.datetime.now(), "country": "SI", "geoposition": Geoposition(46.05528, 14.51444), "location": "Ljubljana", "audience": [1], "theme": [1], "tags": ["tag1", "tag2"], "picture": uploaded_picture, } test_event = create_or_update_event(**event_data) self.assertEqual(2, test_event.pk) self.assertEqual("Ljubljana", test_event.location) self.assertEqual("46.05528", str(test_event.geoposition.latitude)) self.assertIn("tag1", test_event.tags.names()) self.assertIn("tag2", test_event.tags.names()) assert "event_picture/alja" in test_event.picture.path
def save(self, *args, **kwargs): # Change image size and create 50x50 thumbnail if self.photo: if Professor.objects.filter(pk=self.pk).exists(): if self.photo != Professor.objects.get(pk=self.pk).photo: image = Img.open(StringIO.StringIO(self.photo.read())) image.thumbnail((200, 200), Img.ANTIALIAS) output = StringIO.StringIO() image.save(output, format='JPEG', quality=75) output.seek(0) self.photo = InMemoryUploadedFile(output, 'ImageField', "%s" % self.photo.name, 'image/jpeg', output.len, None) image = Img.open(StringIO.StringIO(self.photo.read())) image.thumbnail((50, 50), Img.ANTIALIAS) output = StringIO.StringIO() image.save(output, format='JPEG', quality=75) output.seek(0) self.photo_small = InMemoryUploadedFile(output, 'ImageField', "%s" % self.photo.name, 'image/jpeg', output.len, None) else: image = Img.open(StringIO.StringIO(self.photo.read())) image.thumbnail((200, 200), Img.ANTIALIAS) output = StringIO.StringIO() image.save(output, format='JPEG', quality=75) output.seek(0) self.photo = InMemoryUploadedFile(output, 'ImageField', "%s" % self.photo.name, 'image/jpeg', output.len, None) image = Img.open(StringIO.StringIO(self.photo.read())) image.thumbnail((50, 50), Img.ANTIALIAS) output = StringIO.StringIO() image.save(output, format='JPEG', quality=75) output.seek(0) self.photo_small = InMemoryUploadedFile(output, 'ImageField', "%s" % self.photo.name, 'image/jpeg', output.len, None) super(Professor, self).save(*args, **kwargs)
def create_thumbnail(filename): thumbnail_filename = get_thumb_filename(filename) thumbnail_format = get_image_format(os.path.splitext(filename)[1]) pil_format = thumbnail_format.split('/')[1] image = default_storage.open(filename) image = Image.open(image) # Convert to RGB if necessary # Thanks to Limodou on DjangoSnippets.org # http://www.djangosnippets.org/snippets/20/ if image.mode not in ('L', 'RGB'): image = image.convert('RGB') # scale and crop to thumbnail imagefit = ImageOps.fit(image, THUMBNAIL_SIZE, Image.ANTIALIAS) thumbnail_io = io.StringIO() if sys.version_info >= (3, 0): handle = str(thumbnail_io) else: handle = unicode(thumbnail_io) imagefit.save(handle, format=pil_format) thumbnail = InMemoryUploadedFile( thumbnail_io, None, thumbnail_filename, thumbnail_format, len(thumbnail_io.getvalue()), None) thumbnail.seek(0) return default_storage.save(thumbnail_filename, thumbnail)
def _update_image(facebook_id, image_url): ''' Updates the user profile's image to the given image url Unfortunately this is quite a pain to get right with Django Suggestions to improve this are welcome ''' image_name = 'fb_image_%s.jpg' % facebook_id image_temp = NamedTemporaryFile() try: image_response = urllib2.urlopen(image_url) except AttributeError: image_response = urllib.request.urlopen(image_url) image_content = image_response.read() image_temp.write(image_content) http_message = image_response.info() image_size = len(image_content) try: content_type = http_message.type except AttributeError: content_type = http_message.get_content_type() image_file = InMemoryUploadedFile( file=image_temp, name=image_name, field_name='image', content_type=content_type, size=image_size, charset=None ) image_file.seek(0) image_temp.flush() return image_name, image_file
def get_shp_from_zip(zip_file): """ extract components file parts of a shapefile from a zip file zip_file -- zip file """ try: zip_f = ZipFile(zip_file, 'r') except BadZipfile: return None list_names = zip_f.namelist() d = {} for elem in list_names: t = elem.split('.') d[t[1].lower()] = t[0] ll = d.values() # shp name validation (same name) if all(x == ll[0] for x in ll): k = d.keys() # shp file type validation if len(k) == 4 and ( 'shp' in k and 'dbf' in k and 'shx' in k and 'prj' in k): res = {} for name in zip_f.namelist(): io = StringIO.StringIO() zo = zip_f.open(name, 'r') io.write(zo.read()) # .decode('ISO8859-1').encode('utf-8')) zo.close() res_file = InMemoryUploadedFile( io, None, name.lower(), 'text', io.len, None) res_file.seek(0) res[name.split('.')[1].lower()] = res_file return res else: return None
def test_create_event_with_image(admin_user, admin_client, db): with open(local(__file__).dirname + "/../../static/img/team/alja.jpg") as fp: io = StringIO.StringIO() io.write(fp.read()) uploaded_picture = InMemoryUploadedFile(io, None, "alja.jpg", "jpeg", io.len, None) uploaded_picture.seek(0) event_data = { "audience": [4, 5], "theme": [1, 2], "contact_person": u"*****@*****.**", "country": u"SI", "description": u"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod\r\ntempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,\r\nquis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo\r\nconsequat. Duis aute irure dolor in reprehenderit in voluptate velit esse\r\ncillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non\r\nproident, sunt in culpa qui officia deserunt mollit anim id est laborum.", "event_url": u"", "location": u"Ljubljana, Slovenia", "organizer": u"Mozilla Slovenija", "picture": uploaded_picture, "start_date": datetime.datetime.now(), "end_date": datetime.datetime.now() + datetime.timedelta(days=3, hours=3), "tags": [u"css", u"html", u"web"], "title": u"Webmaker Ljubljana", "user_email": u"*****@*****.**", } response = admin_client.post(reverse("web.add_event"), event_data) assert response.status_code == 302 response = admin_client.get(response.url) assert "event_picture/alja" in response.content
def create_thumbnail(file_path): thumbnail_filename = utils.get_thumb_filename(os.path.basename(file_path)) thumbnail_format = utils.get_image_format(os.path.splitext(file_path)[1]) file_format = thumbnail_format.split('/')[1] image_from_url = cStringIO.StringIO(urllib.urlopen(file_path).read()) image = Image.open(image_from_url) # Convert to RGB if necessary # Thanks to Limodou on DjangoSnippets.org # http://www.djangosnippets.org/snippets/20/ if image.mode not in ('L', 'RGB'): image = image.convert('RGB') # scale and crop to thumbnail imagefit = ImageOps.fit(image, THUMBNAIL_SIZE, Image.ANTIALIAS) thumbnail_io = BytesIO() imagefit.save(thumbnail_io, format=file_format) thumbnail = InMemoryUploadedFile( thumbnail_io, None, thumbnail_filename, thumbnail_format, len(thumbnail_io.getvalue()), None) thumbnail.seek(0) cc = CloudContainer('mediaplan-images') data = thumbnail.read() cc.upload_data(filename=thumbnail_filename, data=data) return thumbnail_filename
def get_temporary_text_file(name): io = StringIO.StringIO() io.write('test') text_file = InMemoryUploadedFile( io, None, name, 'text', io.len, None) text_file.seek(0) return text_file
def get_temporary_text_file(): sio = io.StringIO() sio.write('text') uploadedfile = InMemoryUploadedFile( sio, None, 'text.txt', 'text/plain', sio.tell(), None) uploadedfile.seek(0) return uploadedfile
def get_file(self): # read image from InMemoryUploadedFile self.upload_file.file.seek(0) data = self.upload_file.file # create PIL Image instance image = Image.open(data) watermark_img = Image.open("/app/ojoalplato/static/wpfamily/img/logo2_white.png") rgba_image = image.convert('RGBA') rgba_watermark = watermark_img.convert('RGBA') # resize watermark image image_x, image_y = rgba_image.size watermark_x = watermark_y = max(math.floor(image_x / 10), math.floor(image_y / 10)) new_size = (watermark_x, watermark_y) rgba_watermark = rgba_watermark.resize(new_size, resample=Image.ANTIALIAS) # apply watermark position = ((image_x - watermark_x - 10), (image_y - watermark_y - 10)) rgba_image = watermark(rgba_image, rgba_watermark, position=position) # save new watermarked image cimage = BytesIO() rgba_image.save(cimage, format="PNG") cimage.seek(0) try: field_name = self.upload_file.field_name except: field_name = self.upload_file.name image_file = InMemoryUploadedFile(cimage, field_name, self.upload_file.name, self.upload_file.content_type, rgba_image.tell, None) image_file.seek(0) self.upload_file = image_file return image_file
def test_parse(self): import StringIO from django.core.files.uploadedfile import InMemoryUploadedFile io = StringIO.StringIO() text = 'year;year_range;indicator_id;friendly_name;type_data;selection_type;' \ 'deprivation_type;country;city;region;value;description;category\n' \ '1992;;indicator_id;indicator text;p;Total;;Netherlands;;;13.3;Global_UNHABITAT-DHS;Health\n' \ '1993;;indicator_id;indicator text;p;Total;;Netherlands;;;13.5;Global_UNHABITAT-DHS;Health\n' io.write(text) uploaded_file = InMemoryUploadedFile(io, None, 'testindicator.csv', 'csv', io.len, None) uploaded_file.seek(0) class MockObject(object): user = None self.parser.parse(uploaded_file, None, MockObject()) self.assertEqual(2, Indicator.objects.all().count()) self.assertEqual(1, IndicatorData.objects.all().count()) self.assertEqual(2, IndicatorDataValue.objects.all().count()) self.assertEqual('indicator_id', Indicator.objects.all()[1].id) self.assertEqual(self.country, IndicatorData.objects.all()[0].country) self.assertEqual(13.5, IndicatorDataValue.objects.all()[1].value) self.assertEqual(1993, IndicatorDataValue.objects.all()[1].year)
def create_thumbnail(file_path): thumbnail_filename = utils.get_thumb_filename(file_path) thumbnail_format = utils.get_image_format(os.path.splitext(file_path)[1]) image = default_storage.open(file_path) image = Image.open(image) file_format = image.format # Convert to RGB if necessary # Thanks to Limodou on DjangoSnippets.org # http://www.djangosnippets.org/snippets/20/ if image.mode not in ('L', 'RGB'): image = image.convert('RGB') # scale and crop to thumbnail imagefit = ImageOps.fit(image, THUMBNAIL_SIZE, Image.ANTIALIAS) thumbnail_io = BytesIO() imagefit.save(thumbnail_io, format=file_format) thumbnail = InMemoryUploadedFile( thumbnail_io, None, thumbnail_filename, thumbnail_format, len(thumbnail_io.getvalue()), None) thumbnail.seek(0) return default_storage.save(thumbnail_filename, thumbnail)
def test_create_event_with_image(admin_user, admin_client, db): with open(local(__file__).dirname + '/../../static/img/team/alja.jpg') as fp: io = StringIO.StringIO() io.write(fp.read()) uploaded_picture = InMemoryUploadedFile(io, None, "alja.jpg", "jpeg", io.len, None) uploaded_picture.seek(0) event_data = { 'audience': [4, 5], 'theme': [1,2], 'contact_person': u'*****@*****.**', 'country': u'SI', 'description': u'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod\r\ntempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,\r\nquis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo\r\nconsequat. Duis aute irure dolor in reprehenderit in voluptate velit esse\r\ncillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non\r\nproident, sunt in culpa qui officia deserunt mollit anim id est laborum.', 'event_url': u'', 'location': u'Ljubljana, Slovenia', 'organizer': u'Mozilla Slovenija', 'picture': uploaded_picture, 'start_date': datetime.datetime.now(), 'end_date': datetime.datetime.now() + datetime.timedelta(days=3, hours=3), 'tags': [u'css', u'html', u'web'], 'title': u'Webmaker Ljubljana', 'user_email': u'*****@*****.**' } response = admin_client.post(reverse('web.add_event'), event_data) assert response.status_code == 302 response = admin_client.get(response.url) assert 'event_picture/alja' in response.content
def resize_image(upload, file_name): resized_image_filename = file_name thumbnail_format = 'JPEG' #file_format = thumbnail_format.split('/')[1] file_format = 'JPEG' #image = default_storage.open(file_path) image = Image.open(upload) # Convert to RGB if necessary # Thanks to Limodou on DjangoSnippets.org # http://www.djangosnippets.org/snippets/20/ if image.mode not in ('L', 'RGB'): image = image.convert('RGB') # scale and crop original photo resized_imagefit = ImageOps.fit(image, PHOTO_SIZE, Image.ANTIALIAS) resized_image_io = BytesIO() resized_imagefit.save(resized_image_io, format=file_format) resized_image = InMemoryUploadedFile( resized_image_io, None, resized_image_filename, thumbnail_format, len(resized_image_io.getvalue()), None) resized_image.seek(0) return resized_image
def get_temporary_xml_file(xml_abs_path): fp = open(xml_abs_path) io = StringIO.StringIO(fp.read()) fp.close() xml_file = InMemoryUploadedFile(io, field_name='file', name='foo.xml', content_type='text/xml', size=io.len, charset='utf8') xml_file.seek(0) return xml_file
def process_thumbnail(instance, sizes, crop=False): file = StringIO.StringIO(instance.original_photo.read()) original_image = Image.open(file) # open the image using PIL # pull a few variables out of that full path filename = os.path.basename(instance.original_photo.name).rsplit('.', 1)[0] extension = os.path.basename(instance.original_photo.name).rsplit('.', 1)[1] # the file extension # If there is no extension found try jpg if extension == '': extension = 'jpg' # use the file extension to determine if the image is valid before proceeding if extension not in ['jpg', 'jpeg', 'gif', 'png']: return False for size_name, size in sizes.iteritems(): im = original_image.copy() (x_size, y_size) = im.size original_ratio = float(x_size) / float(y_size) width = size['width'] height = size['height'] new_ratio = float(width / height) if new_ratio > original_ratio: im = im.resize((width, int(width / original_ratio)), Image.ANTIALIAS) if crop: clip_amount = int((int(width / original_ratio) - height) / 2) im = im.crop((0, clip_amount, width,height + clip_amount)) else: im = im.resize((int(height * original_ratio), height), Image.ANTIALIAS) if crop: clip_amount = int((int(height * original_ratio) - width) / 2) im = im.crop((clip_amount, 0, width + clip_amount, height)) name = "%s.jpg" % filename tempfile_io = StringIO.StringIO() if im.mode != "RGB": im = im.convert("RGB") im.save(tempfile_io, 'JPEG') temp_file = InMemoryUploadedFile(tempfile_io, None, name, 'image/jpeg', tempfile_io.len, None) done, tries = False, 0 while not done: try: # Make sure we're at the beginning of the file for reading when saving temp_file.seek(0) getattr(instance, size_name).save(name, temp_file) done = True except SSLError: pass # Try at max, 10 times before quitting tries += 1 if tries > 10: done = True return True
def _get_temporary_file(self, type='application/pdf', extension='pdf'): io = StringIO.StringIO() io.write('foo') text_file = InMemoryUploadedFile( io, None, 'foo.%s' % extension, type, io.len, None ) text_file.seek(0) return text_file
class MyData(models.Model): class Meta(object): verbose_name = "Personal Data" name = models.CharField( validators=[validate_name_fields], max_length=30) last_name = models.CharField( validators=[validate_name_fields], max_length=30) birthday = models.DateField(validators=[validate_birthday]) bio = models.TextField( max_length=256, blank=True, null=True) email = models.EmailField( max_length=30) jabber = models.EmailField( max_length=30) skype = models.CharField( max_length=30) other_conts = models.TextField( max_length=256, blank=True, null=True) photo = models.ImageField( blank=True, null=True, upload_to='img/') def save(self, *args, **kwargs): if self.photo: size = (200, 200) image = Image.open(StringIO.StringIO(self.photo.read())) (width, height) = image.size if (width > 200) or (height > 200): image.thumbnail(size, Image.ANTIALIAS) output = StringIO.StringIO() image.save(output, format='jpeg', quality=70) output.seek(0) self.photo = InMemoryUploadedFile( output, 'ImageField', "%s.jpg" % self.photo.name.split('.')[0], 'image/jpeg', output.len, None) try: this = MyData.objects.get(id=self.id) if this.photo == self.photo: self.photo = this.photo else: this.photo.delete(save=False) except: pass super(MyData, self).save(*args, **kwargs) def __unicode__(self): return u"%s %s" % (self.name, self.last_name)
def get_temporary_image(): io = StringIO.StringIO() size = (200, 200) color = (255, 0, 0, 0) image = Image.new("RGBA", size, color) image.save(io, format='JPEG') image_file = InMemoryUploadedFile(io, None, 'foo.jpg', 'jpeg', io.len, None) image_file.seek(0) return image_file
def get_in_memory_file(image: "Image"): temp_file_io = BytesIO() image.save(temp_file_io, "jpeg", optimize=True) temp_file_io.seek(0) image_file = InMemoryUploadedFile(temp_file_io, None, str(uuid.uuid4()) + ".jpeg", "jpeg", None, None) image_file.seek(0) return image_file
def get_temporary_image_file(): bio = io.BytesIO() size, color = (300, 300,), (200, 50, 200, 80,) image = Image.new("RGBA", size, color) image.save(bio, format='PNG') uploadedfile = InMemoryUploadedFile( bio, None, 'image.png', 'png', bio.tell(), None) uploadedfile.seek(0) return uploadedfile
def get_temporary_image_file(): io = StringIO.StringIO() size = (200, 200) color = (255, 0, 0, 0) image = Image.new("RGBA", size, color) image.save(io, format='PNG') image_file = InMemoryUploadedFile(io, field_name='file', name='foo.png', content_type='png', size=io.len, charset=None) image_file.seek(0) return image_file
def test_ambassadors_list(db, client): test_country_name = "Austria" test_country_code = "AT" test_username = "******" test_email = "*****@*****.**" test_first_name = "Testko" test_last_name = "Test" test_full_name = test_first_name + " " + test_last_name test_ambassador = User.objects.create( username=test_username, email=test_email, first_name=test_first_name, last_name=test_last_name ) test_ambassador_profile = UserProfile.objects.create(user=test_ambassador, country=test_country_code) group = Group.objects.get(name="ambassadors") group.user_set.add(test_ambassador) with open(local(__file__).dirname + "/../../static/img/team/alja.jpg") as fp: io = StringIO.StringIO() io.write(fp.read()) uploaded_picture = InMemoryUploadedFile(io, None, "alja17.jpg", "jpeg", io.len, None) uploaded_picture.seek(0) avatar = Avatar(user=test_ambassador, primary=True) avatar.avatar.save(uploaded_picture.name, uploaded_picture) avatar.save() new_avatar = get_primary_avatar(test_ambassador, size=80) test_amb_avatar = new_avatar.avatar_url(80) response = client.get(reverse("web.ambassadors")) # We're expecting to the Ambassador under the right country, # with the right avatar and the right email contact expected_result = """ <h2 class="clearfix">%s</h2> <div class="ambassador clearfix"> <img src="%s" alt="%s" width="80" height="80" class="img-circle" /> <h4>%s <span> <a alt="Send me an email" href="mailto:%s"><i class="fa fa-envelope"></i></a> """ % ( test_country_name, test_amb_avatar, test_username, test_full_name, test_email, ) expected_result = expected_result.replace("\t", "").replace("\n", "") ambassadors_content = response.content.replace("\t", "").replace("\n", "") # Check this test and modify it to integrating the Ambassadors page changes # assert expected_result in ambassadors_content test_ambassador.delete() avatar.delete()
def get_temporary_image(): # Testing utility. io = BytesIO() size = (200, 200) color = (255, 0, 0, 0) image = Image.new('RGBA', size, color) image.save(io, format='JPEG') image_file = InMemoryUploadedFile(io, None, 'foo.jpg', 'jpeg', 1, None) image_file.seek(0) return image_file
def get_temporary_image(): output = StringIO.StringIO() size = (1200, 700) color = (255, 0, 0, 0) image = Img.new("RGBA", size, color) image.save(output, format='JPEG') image_file = InMemoryUploadedFile( output, None, 'test.jpg', 'jpeg', output.len, None) image_file.seek(0) return image_file
def test_file(title): """ Create text file. """ io = BytesIO() io.write(b'test') text_file = InMemoryUploadedFile( io, None, title, 'text', 'utf-8', None) text_file.seek(0) return text_file
class File(BaseModel): """Model for storing uploaded images. Uploaded images can be stored prior to creating Photo instance. This way you can upload images while user is typing other data. Images are checked if meet size and format requirements before saving. """ class Meta: """File Meta options.""" verbose_name = _('file') verbose_name_plural = _('files') #: uploaded file file = models.ImageField(upload_to=generate_file_filename) #: thumbnail of uploaded file thumbnail = models.ImageField(upload_to=generate_thumb_filename) def save(self, *args, **kwargs): # pylint: disable=arguments-differ """Add photo thumbnail and save object.""" if not self.pk: # on create image = Image.open(self.file) image.thumbnail((100, 100), Image.ANTIALIAS) thumb = io.BytesIO() image.save(thumb, format="jpeg", quality=100, optimize=True, progressive=True) self.thumbnail = InMemoryUploadedFile(thumb, None, self.file.name, 'image/jpeg', thumb.tell(), None) super(File, self).save(*args, **kwargs) def delete(self, *args, **kwargs): # pylint: disable=arguments-differ """Delete attached images and actual object.""" self.file.delete(save=False) # pylint: disable=no-member self.thumbnail.delete(save=False) # pylint: disable=no-member super(File, self).delete(*args, **kwargs) def get_long_edge(self): """Return longer edge of the image.""" return max(self.file.width, self.file.height) # pylint: disable=no-member def __str__(self): """Return string representation of File object.""" photo = self.photo_set.first() # pylint: disable=no-member photo_title = photo.title if photo else '?' photo_id = photo.pk if photo else '?' return "id: {}, filename: {}, photo id: {}, photo title: {}".format( self.pk, self.file.name, photo_id, photo_title)
def get_temporary_image(): """ Quick hack, credit to https://stackoverflow.com/questions/43135771/ """ io = BytesIO() size = (200, 200) color = (255, 0, 0) image = Image.new("RGB", size, color) image.save(io, format="JPEG") image_file = InMemoryUploadedFile( io, None, "foo.jpg", "jpeg", image.size, None ) image_file.seek(0) return image_file
def save(self, commit=True): """ Saves the uploaded image in the designated location. If image type is not SVG, a byteIO of image content_type is created and subsequently save; otherwise, the SVG is saved in its existing ``charset`` as an ``image/svg+xml``. *Note*: The dimension of image files (excluding SVG) are set using ``PIL``. :param commit: If ``True``, the file is saved to the disk; otherwise, it is held in the memory. :type commit: bool :return: An instance of saved image if ``commit is True``, else ``namedtuple(path, image)``. :rtype: bool, namedtuple """ image = self.files.get('image') content_type = image.content_type file_name = image.name image_extension = content_type.split('/')[-1].upper() image_size = image.size if content_type.lower() != self._SVG_TYPE: # Processing the raster graphic image. # Note that vector graphics in SVG format # do not require additional processing and # may be stored as uploaded. image = self._process_raster(image, image_extension) image_size = image.tell() image.seek(0, SEEK_SET) # Processed file (or the actual file in the case of SVG) is now # saved in the memory as a Django object. uploaded_image = InMemoryUploadedFile( file=image, field_name=None, name=file_name, content_type=content_type, size=image_size, charset=None ) if (content_type.lower() == self._SVG_TYPE and MARKDOWNX_SVG_JAVASCRIPT_PROTECTION and xml_has_javascript(uploaded_image.read())): raise MarkdownxImageUploadError( 'Failed security monitoring: SVG file contains JavaScript.' ) return self._save(uploaded_image, file_name, commit)
def create_inmemory_image(file_name='tmp.png', format=None, width=200, height=200): from PIL import Image if not format: _, extension = os.path.splitext(file_name) format = extension[1:].upper() stream = six.BytesIO() size = (width, height) color = (255, 0, 0, 0) image = Image.new('RGBA', size, color) image.save(stream, format=format) image_file = InMemoryUploadedFile(stream, None, file_name, format, stream.tell(), None) image_file.seek(0) return image_file
def post(self, request, *args, **kwargs): brabform = BrabForm(data=request.POST) if brabform.is_valid(): # Fill comments.auth_user_id with request.user.id brabform.instance.auth_user_id = request.user.id # Fill comments.brab_id with pk of the current brab tags = brabform.cleaned_data['tags'] tags = self.parse_tags(tags) category = brabform.cleaned_data['category'] brab = brabform.save(commit=False) brabformset = BrabFormSet(request.POST, request.FILES, instance=brab) # -------------------------------------------------------------------------------------------- picture_string = brabformset.forms[0].data[ 'pictures_set-0-new_picture'] # This POST variable will only be filled if client browser supports awesomecropper plugin # because then the HTML5 canvas content will be posted, and not file read from the disk number_of_turns = int( brabformset.forms[0].data['pictures_set-0-rotate']) if picture_string: file_to_add = CreateInMemoryUploadedFileFromBase64EncodedImage( picture_string, "pictures_set-0-picture", number_of_turns) if file_to_add: request.FILES.appendlist("pictures_set-0-picture", file_to_add) brabformset = BrabFormSet(request.POST, request.FILES, instance=brab) else: try: image_file_name = request.FILES[ u'pictures_set-0-picture'].name new_image_file_present = True except: new_image_file_present = False if new_image_file_present: image_file_extension = image_file_name.split(".")[-1] content_type = request.FILES[ u'pictures_set-0-picture'].content_type new_file_name = md5(str( localtime())).hexdigest() + image_file_extension if number_of_turns == 0: request.FILES[ u'pictures_set-0-picture'].name = new_file_name else: rotated_file = RotateImage( request.FILES["pictures_set-0-picture"], number_of_turns, image_file_extension) if rotated_file: in_memory_uploaded_file = InMemoryUploadedFile( rotated_file, "pictures_set-0-picture", new_file_name, content_type, rotated_file.size, None) request.FILES[ "pictures_set-0-picture"] = in_memory_uploaded_file brabformset = BrabFormSet(request.POST, request.FILES, instance=brab) # -------------------------------------------------------------------------------------------- if brabformset.is_valid(): brab.save() picture = brabformset.save(commit=False) picture[0].visible = 1 picture[0].main = 1 picture[0].save() tag_count = self.add_tag_records(tags, request.user.id, brab.pk) category_count = self.add_category_records( category, request.user.id, brab.pk) # add vote totals - one per each vote choice... for x in Vote.objects.filter(visible=1): vote_total = Vote_totals(brab_id=brab.pk, vote_id=x.id, total=0) vote_total.save() return HttpResponseRedirect(brab.get_absolute_url()) else: brabformset = BrabFormSet(request.POST, request.FILES) self.object = None context = self.get_context_data(object=self.object, brabform=brabform, brabformset=brabformset) return self.render_to_response(context)
def resize_image(self, image_file): """ 对图片大小进行缩放 :param image_file: 图片对象 :return: """ if image_file.file.content_type != "image/jpeg" and image_file.size < 600 * 1024: return image_file data = image_file.file.read() if image_file.file.content_type == "image/gif": return image_file # 如果未传递filename,那么就实用上传图片的名字 if not self.filename and image_file.file.name: self.filename = image_file.file.name image_tmp = PImage.open(image_file) # 方向处理 try: if image_tmp._getexif(): exif = dict(image_tmp._getexif().items()) for orientation in ExifTags.TAGS.keys(): if ExifTags.TAGS[orientation] == "Orientation": break if orientation in exif: if exif[orientation] == 3: image_tmp = image_tmp.rotate(180, expand=True) elif exif[orientation] == 6: image_tmp = image_tmp.rotate(270, expand=True) elif exif[orientation] == 8: image_tmp = image_tmp.rotate(90, expand=True) except Exception as e: print(e) output_io_stream = BytesIO() w, h = image_tmp.size scale = 1 if w > 1600: scale = 1600.0 / w image_resize = image_tmp.resize((int(w * scale), int(h * scale))) try: image_resize.save(output_io_stream, format='JPEG', quality=80) except OSError as e: if str(e).find("RGBA") > 0: # cannot write mode RGBA as JPEG image_resize = image_resize.convert('RGB') image_resize.save(output_io_stream, format='JPEG', quality=80) else: print(e) # 返回原来的图片吧 return image_file output_io_stream.seek(0) image = InMemoryUploadedFile(output_io_stream, 'ImageField', "%s.jpg" % image_file.name.split('.')[0], 'image/jpeg', sys.getsizeof(output_io_stream), None) return image
def SaveDetection(request, user, profile, detection_name, status, water_stress, water_stress_percent, note_name, note_text, mosaic): """Save detection in DB.""" #https://stackoverflow.com/questions/35581356/save-matplotlib-plot-image-into-django-model/35633462 #https://stackoverflow.com/questions/3723220/how-do-you-convert-a-pil-image-to-a-django-file # Paths if mosaic is True: path_picture = 'media/temp/bands/' + str( request.user.username) + '/RGB_temp.JPG' else: path_picture = 'media/temp/bands/' + str( request.user.username) + '/RGB_temp.JPG' path_picture_ndvi = 'media/temp/results/' + str( request.user.username) + '/NDVI.jpg' path_picture_savi = 'media/temp/results/' + str( request.user.username) + '/SAVI.jpg' path_picture_evi2 = 'media/temp/results/' + str( request.user.username) + '/EVI2.jpg' path_picture_without = 'media/temp/results/' + str( request.user.username) + '/WITHOUT.jpg' picture_name = 'RGB.jpg' picture_ndvi_name = 'NDVI.jpg' picture_savi_name = 'SAVI.jpg' picture_evi2_name = 'EVI2.jpg' picture_without_name = 'WITHOUT.jpg' path_pictures = [ path_picture, path_picture_ndvi, path_picture_savi, path_picture_evi2, path_picture_without ] picture_names = [ picture_name, picture_ndvi_name, picture_savi_name, picture_evi2_name, picture_without_name ] picture_files = [] for path, name in zip(path_pictures, picture_names): picture_file = Image.open(path) tempfile_io = BytesIO() picture_file.save(tempfile_io, format='JPEG') picture_file = InMemoryUploadedFile(tempfile_io, None, name, 'image/jpeg', tempfile_io.tell, None) picture_files.append(picture_file) detection_instance = Detection( user=user, profile=profile, name=detection_name, water_stress=water_stress, water_stress_percent=water_stress_percent, satatus_of_field=status, ) detection_instance.picture.save(picture_name, picture_files[0]) detection_instance.picture_ndvi.save(picture_ndvi_name, picture_files[1]) detection_instance.picture_savi.save(picture_savi_name, picture_files[2]) detection_instance.picture_evi2.save(picture_evi2_name, picture_files[3]) detection_instance.picture_without.save(picture_without_name, picture_files[4]) detection_instance.save() if note_name: note_instance = Note( note_detection=detection_instance, name=note_name, user=user, text=note_text, ) note_instance.save() return True
def get_crop_image_2(request, pk): crop_image = request.POST.get('image') im = Image.open(BytesIO(base64.b64decode(crop_image.split(',')[1]))) file_name = f'{pk}.png' path = f'{settings.MEDIA_ROOT}/' + file_name print("file_name : " + file_name) area = (190, 113, 440, 370) im = im.crop(area) im = im.resize((224, 224)) im.save(path) img = image.load_img(path) img = image.img_to_array(img) img = img.reshape((1, ) + img.shape) img = img / 255 with graph.as_default(): preds = model.predict(img) m = np.argmax(preds) # print(model.summary()) print("판독결과 : ", m) # tmp_path='./static/media/' # if m == 0: # playsound(path+"cs_732020_0_31_2_1.wav") # elif m == 1: # playsound(path+"cs_732020_0_31_2_1.wav") # elif m == 2: # playsound(path+"2.mp3") # else: # playsound(path+"3.mp3") buffer = BytesIO() im.save(fp=buffer, format='PNG') image_file = ContentFile(buffer.getvalue()) # DB에 이미지 저장 visitor = Visitor.objects.get(pk=pk) visitor.image.save( file_name, InMemoryUploadedFile( image_file, # file None, # field_name file_name, # file name 'image/png', # content_type im.tell, # size None, # content_type_extra )) visitor.save() # 마스크 판독 messages = { 0: '마스크 미착용. 마스크를 착용하지 않으셨습니다.', 1: '마스크 착용. 즐거운 시간 되십시오.', 2: '마스크 인식 불가. 마스크를 제대로 착용해주세요.', 3: '얼굴 인식 불가. 초록색 네모칸 안에 얼굴을 다시 맞춰주세요.', } data = { 'mask': int(m), 'message': messages.get(int(m)), } return JsonResponse(data, safe=False)
def test_update_form_edit(self): """ """ read_group = self._create_group('read') self._create_capability('Read-Scope', [], read_group) # create user and add it to the read group user = self._create_user('john', '123456') user.groups.add(read_group) # create an application self._create_application('john_app', user=user) # Test form with exact app name has error data = {'name': 'john_app'} form = CustomRegisterApplicationForm(user, data) form.is_valid() self.assertNotEqual(form.errors.get('name'), None) form = CustomAdminApplicationForm(data) form.is_valid() self.assertNotEqual(form.errors.get('name'), None) # Test form with same app name and Uppercase has error data = {'name': 'John_App'} form = CustomRegisterApplicationForm(user, data) form.is_valid() self.assertNotEqual(form.errors.get('name'), None) # Test form with different app name is OK data = {'name': 'Dave_app'} form = CustomRegisterApplicationForm(user, data) form.is_valid() self.assertEqual(form.errors.get('name'), None) # Test form with empty app name has error. data = {'name': ''} form = CustomRegisterApplicationForm(user, data) form.is_valid() self.assertNotEqual(form.errors.get('name'), None) # Test form with website_uri valid URI. data = {'website_uri': 'https://www.example.org'} form = CustomRegisterApplicationForm(user, data) form.is_valid() self.assertEqual(form.errors.get('website_uri'), None) # Test form with website_uri in-valid URI. data = {'website_uri': 'xyzs:/www.example.org'} form = CustomRegisterApplicationForm(user, data) form.is_valid() self.assertNotEqual(form.errors.get('website_uri'), None) # Test form with website_uri EMPTY URI is OK. data = {'website_uri': ''} form = CustomRegisterApplicationForm(user, data) form.is_valid() self.assertEqual(form.errors.get('website_uri'), None) # Test form with empty description. data = {'description': ''} form = CustomRegisterApplicationForm(user, data) form.is_valid() self.assertEqual(form.errors.get('description'), None) form = CustomAdminApplicationForm(data) form.is_valid() self.assertEqual(form.errors.get('description'), None) # Test form with valid description. data = {'description': 'Testing short description here!'} form = CustomRegisterApplicationForm(user, data) form.is_valid() self.assertEqual(form.errors.get('description'), None) form = CustomAdminApplicationForm(data) form.is_valid() self.assertEqual(form.errors.get('description'), None) # Test form with description over 1000 characters. data = {'description': 'T' * 1001} form = CustomRegisterApplicationForm(user, data) form.is_valid() self.assertNotEqual(form.errors.get('description'), None) form = CustomAdminApplicationForm(data) form.is_valid() self.assertEqual(form.errors.get('description'), None) # Test form with description exactly 1000 characters. data = {'description': 'T' * 1000} form = CustomRegisterApplicationForm(user, data) form.is_valid() self.assertEqual(form.errors.get('description'), None) # Test form with HTML tags in the description. data = { 'description': '<b>Test</b> <button>Test</button> a <span>Test</span>' } form = CustomRegisterApplicationForm(user, data) form.is_valid() self.assertNotEqual(form.errors.get('description'), None) form = CustomAdminApplicationForm(data) form.is_valid() self.assertEqual(form.errors.get('description'), None) # Testing valid logo_image with max dimensions file = BytesIO() image = Image.new('RGB', size=(int(settings.APP_LOGO_WIDTH_MAX), int(settings.APP_LOGO_HEIGHT_MAX)), color='red') image.save(file, 'jpeg') file.seek(0) image = InMemoryUploadedFile(file, None, 'test.jpg', 'image/jpeg', len(file.getvalue()), None) data = {} files = {'logo_image': image} form = CustomRegisterApplicationForm(user, data, files) form.is_valid() self.assertEqual(form.errors.get('logo_image'), None) # Testing logo_image exceeding max width file = BytesIO() image = Image.new('RGB', size=(int(settings.APP_LOGO_WIDTH_MAX) + 1, int(settings.APP_LOGO_HEIGHT_MAX)), color='red') image.save(file, 'jpeg') file.seek(0) image = InMemoryUploadedFile(file, None, 'test.jpg', 'image/jpeg', len(file.getvalue()), None) data = {} files = {'logo_image': image} form = CustomRegisterApplicationForm(user, data, files) form.is_valid() self.assertNotEqual(form.errors.get('logo_image'), None) form = CustomAdminApplicationForm(data, files) form.is_valid() self.assertNotEqual(form.errors.get('logo_image'), None) # Testing logo_image exceeding max height file = BytesIO() image = Image.new('RGB', size=(int(settings.APP_LOGO_WIDTH_MAX), int(settings.APP_LOGO_HEIGHT_MAX) + 1), color='red') image.save(file, 'jpeg') file.seek(0) image = InMemoryUploadedFile(file, None, 'test.jpg', 'image/jpeg', len(file.getvalue()), None) data = {} files = {'logo_image': image} form = CustomRegisterApplicationForm(user, data, files) form.is_valid() self.assertNotEqual(form.errors.get('logo_image'), None) form = CustomAdminApplicationForm(data, files) form.is_valid() self.assertNotEqual(form.errors.get('logo_image'), None) # Testing logo_image not JPEG type file = BytesIO() image = Image.new('RGB', size=(50, 50), color='red') image.save(file, 'png') file.seek(0) image = InMemoryUploadedFile(file, None, 'test.png', 'image/png', len(file.getvalue()), None) data = {} files = {'logo_image': image} form = CustomRegisterApplicationForm(user, data, files) form.is_valid() self.assertNotEqual(form.errors.get('logo_image'), None) form = CustomAdminApplicationForm(data, files) form.is_valid() self.assertNotEqual(form.errors.get('logo_image'), None) # Test require_demographic_scopes value True data = {'require_demographic_scopes': True} form = CustomRegisterApplicationForm(user, data) form.is_valid() self.assertEqual(form.errors.get('require_demographic_scopes'), None) # Test require_demographic_scopes value False data = {'require_demographic_scopes': False} form = CustomRegisterApplicationForm(user, data) form.is_valid() self.assertEqual(form.errors.get('require_demographic_scopes'), None) # Test require_demographic_scopes invalid value data = {'require_demographic_scopes': None} form = CustomRegisterApplicationForm(user, data) form.is_valid() self.assertNotEqual(form.errors.get('require_demographic_scopes'), None) # Base set of passing data fields passing_app_fields = { 'name': 'john_app_new', 'client_type': 'confidential', 'authorization_grant_type': 'authorization-code', 'redirect_uris': 'http://localhost:8000/social-auth/complete/oauth2io/', 'logo_uri': '', 'logo_image': '', 'website_uri': '', 'description': '', 'policy_uri': '', 'tos_uri': '', 'support_email': '', 'support_phone_number': '', 'contacts': '', 'require_demographic_scopes': True, 'agree': True } # Test that passing_app_fields are OK/valid. form = CustomRegisterApplicationForm(user, passing_app_fields) self.assertTrue(form.is_valid()) # Test client_type = 'confidential' and authorization_grant_type = 'implicit' not allowed. data = passing_app_fields data['client_type'] = 'confidential' data['authorization_grant_type'] = 'implicit' form = CustomRegisterApplicationForm(user, data) self.assertFalse(form.is_valid()) self.assertIn( 'Only a confidential client and authorization-code grant type are allowed at this time.', str(form.errors.get('__all__'))) # Test client_type = 'public' and grant_type = 'authorization-code' not allowed. data = passing_app_fields data['client_type'] = 'public' data['authorization_grant_type'] = 'authorization-code' form = CustomRegisterApplicationForm(user, data) self.assertFalse(form.is_valid()) self.assertIn( 'Only a confidential client and authorization-code grant type are allowed at this time.', str(form.errors.get('__all__'))) # Test client_type = 'public' and grant_type = 'implicit' not allowed. data = passing_app_fields data['client_type'] = 'public' data['authorization_grant_type'] = 'implicit' form = CustomRegisterApplicationForm(user, data) self.assertFalse(form.is_valid()) self.assertIn( 'Only a confidential client and authorization-code grant type are allowed at this time.', str(form.errors.get('__all__')))
collection=data['collection'], name__startswith=base_subdir).count() # don't count current instance if self.instance.pk is not None and nres != 0: nres -= 1 safe_name = '{0}_{1}'.format(base_subdir, nres) data['name'] = base_subdir if nres == 0 else safe_name ttl_name = os.path.split(self.nidm.ttl.filename)[-1] provn_name = os.path.split(self.nidm.provn.filename)[-1] data['ttl_file'] = InMemoryUploadedFile( # fix ttl for spm12 file=ContentFile( self.nidm.fix_spm12_ttl(self.nidm.zip.read(self.nidm.ttl))), field_name='file', name=ttl_name, content_type='text/turtle', size=self.nidm.ttl.file_size, charset='utf-8') data['provn_file'] = InMemoryUploadedFile( file=ContentFile(self.nidm.zip.read(self.nidm.provn)), field_name='file', name=provn_name, content_type='text/provenance-notation', size=self.nidm.provn.file_size, charset='utf-8') return data
def get_temporary_text_file(): io = StringIO() io.write('foo') text_file = InMemoryUploadedFile(io, None, 'test.txt', 'text', None, None) text_file.seek(0) return text_file
def load_image(name, folder): content_file = ContentFile(open(folder + name + '.gif', 'rb').read()) return InMemoryUploadedFile(content_file, None, name + '.gif', 'image/gif', content_file.tell, None)
def replace_bg_image(request): if os.path.exists(other_path): raise Http404("Invalid Image!") image = request.FILES.get("image", None) background = request.FILES.get("background", None) blur = request.data.get("blur", 0) try: blur = int(blur) if image is None or background is None: raise AttributeError # load bytes image = Image.open(BytesIO(image.read())) background = Image.open(BytesIO(background.read())) print(image.size) print(background.size) image_width, image_height = image.size background_width, background_height = background.size scale = max(1, image_height / background_height, image_width / background_width) background_width = (background_width * scale) background_height = (background_height * scale) background_width, background_height = list( map(int, (background_width, background_height))) background = background.resize((background_width, background_height), Image.ANTIALIAS) print(background_width, background_height) left = .5 * (background_width - image_width) right = left + image_width top = .5 * (background_height - image_height) bottom = top + image_height left, top, right, bottom = list(map(int, (left, top, right, bottom))) print(left, top, right, bottom) background = background.crop((left, top, right, bottom)) new_image = Image.new('RGBA', background.size, (0, 0, 0, 0)) print('blur', blur) for _ in range(blur): print("bluring...") background = background.filter(ImageFilter.BLUR) new_image.paste(background, (0, 0)) new_image.paste(image, (0, 0), mask=image) new_image_io = BytesIO() new_image.save(new_image_io, format='PNG') new_image_bytes = InMemoryUploadedFile(new_image_io, None, 'result.png', 'image/png', new_image_io.tell, None) return HttpResponse(new_image_bytes, content_type="image/png") except (IOError, AttributeError) as e: print(e) raise Http404("Invalid Image!")
def convert_image_to_file(self, image, name): temp = BytesIO() image.save(temp, format='PNG') file_size = temp.tell() return InMemoryUploadedFile(temp, None, name, 'image/png', file_size, None)
def test_open_resets_file_to_start_and_returns_context_manager(self): uf = InMemoryUploadedFile(StringIO('1'), '', 'test', 'text/plain', 1, 'utf8') uf.read() with uf.open() as f: self.assertEqual(f.read(), '1')
def _save(self, name, content): blob_service = BlobService(account_name=accountName, account_key=accountKey) import mimetypes small_content = content content.open() content_type = None if hasattr(content.file, 'content_type'): content_type = content.file.content_type else: content_type = mimetypes.guess_type(name)[0] content_str = content.read() blob_service.put_blob( 'pictures', name, content_str, x_ms_blob_type='BlockBlob', x_ms_blob_content_type=content_type, x_ms_blob_cache_control= 'public, max-age=3600, s-maxage=86400' #cache in the browser for 1 hr, on the edge for 24 hrs ) content.close() if "avatars" in name: #creating and saving thumbnail small_image_name = name small_image_name = string.replace(small_image_name, "avatars", "thumbnails") thumbnail = StringIO.StringIO() size = 22, 22 image = small_content.file image = Image.open(image) small_image = image.resize(size, Image.ANTIALIAS) small_image.save(thumbnail, 'JPEG', quality=70, optimize=True) img = InMemoryUploadedFile(thumbnail, None, 'small.jpg', 'image/jpeg', thumbnail.len, None) small_content.file = img small_content.open() stream = small_content.read() blob_service.put_blob( 'pictures', small_image_name, stream, x_ms_blob_type='BlockBlob', x_ms_blob_content_type=content_type, x_ms_blob_cache_control= 'public, max-age=604800, s-maxage=604800' #cache in the browser and on the edge for 7 days ) small_content.close() elif "photos" in name: small_image_name = name small_image_name = string.replace(small_image_name, "photos", "thumbnails") thumbnail = StringIO.StringIO() #size = 40, 40 height = 38 image = small_content.file image = Image.open(image) wpercent = (height / float(image.size[1])) bsize = int((float(image.size[0]) * float(wpercent))) small_image = image.resize((bsize, height), PIL.Image.ANTIALIAS) small_image.save(thumbnail, 'JPEG', quality=70, optimize=True) img = InMemoryUploadedFile(thumbnail, None, 'small.jpg', 'image/jpeg', thumbnail.len, None) small_content.file = img small_content.open() stream = small_content.read() blob_service.put_blob( 'pictures', small_image_name, stream, x_ms_blob_type='BlockBlob', x_ms_blob_content_type=content_type, x_ms_blob_cache_control= 'public, max-age=3600, s-maxage=86400' #cache in the browser for 1 hr, on the edge for 24 hrs ) small_content.close() else: pass return name
print(type(pic)) # 创建一个文件 # save_path = "%s/booktest/%s" % (settings.MEDIA_ROOT, pic.name) save_path = "E:/不常用工作/已解密文件/%s" % pic.name with open(save_path, "wb") as f: # 获取上传文件的内容并写入打开的文件 for content in pic.chunks(): f.write(content) # 复制一份文件放入桌面 save_path_desktop = "C:/Users/931304/Desktop/已解密文件/%s" % pic.name with open(save_path_desktop, "wb") as f: for content in pic.chunks(): f.write(content) # 返回 return redirect("/decrypt") pic_io = BytesIO(b"C:/Users/931304/Desktop") pic = InMemoryUploadedFile(file=pic_io, field_name="pic", name="wenjian.xlsx", content_type=None, size=11854, charset=None) save_path = "E:/不常用工作/已解密文件/wenjian.xlsx" with open(save_path, "wb") as f: # 获取上传文件的内容并写入打开的文件 for content in pic.chunks(): f.write(content)
# Generate the actual image. custom_image = banner_image.copy() # Calculate and draw border box. coords = settings.FACEBOOK_CUSTOM_IMG_COORDS border = settings.FACEBOOK_CUSTOM_IMG_BORDER box_coords = (coords[0] - border['width'], coords[1] - border['width'], coords[0] + 49 + border['width'], coords[1] + 49 + border['width']) ImageDraw.Draw(custom_image).rectangle(box_coords, fill=border['color']) # Draw user avatar custom_image.paste(user_image, coords) # Store the image in memory so we can save it to the model. io = StringIO() custom_image.save(io, format='PNG') custom_image_file = InMemoryUploadedFile(io, None, 'custom_image.png', 'image/png', io.len, None) banner_instance.custom_image.save('custom_image.png', custom_image_file) banner_instance.processed = True banner_instance.save() @task def update_user_info(user_id): user = get_object_or_none(FacebookUser, id=user_id) if user is not None: FacebookUser.objects.update_user_info(user)
def set_PIL_image(self, pil_image): file = StringIO() pil_image.save(file, format='png') self.image_file = InMemoryUploadedFile(file, None, 'foo.png', 'image/png', file.len, None)
def post(self, request): # surveys = request.data['answer'] # surveys_list = ast.literal_eval(surveys) axis = request.data['axis'] #lat,long axis_list = ast.literal_eval(axis) try: f = request.FILES['image'].read() except: return Response("invalid image file!", status=status.HTTP_400_BAD_REQUEST) existing_filename = request.FILES['image'].name input_image = io.BytesIO(f) instance = face.FaceClass() emotion_dict, img = instance.face(input_image) img_io = io.BytesIO() img.save(img_io, "JPEG") filename = '%s%s' % (uuid.uuid4(), existing_filename) today = datetime.date.today() emotion_list = list(emotion_dict.values()) weather_str = weather_report(axis_list[0], axis_list[1]) weathers = weather_translator(weather_str) emotion = None if not Emotion.objects.filter(profile=request.user, pubdate=today).exists(): emotion = Emotion() emotion_str = str(emotion_list) emotion.emotions = emotion_str emotion.profile = request.user emotion.weather = weathers emotion.image = InMemoryUploadedFile(img_io, None, filename, 'image/jpeg', sys.getsizeof(img_io), None) image_path = emotion.image.url emotion.save() else: emotion = Emotion.objects.get(profile=request.user, pubdate=today) emotion_str = str(emotion_list) emotion.emotions = emotion_str emotion.profile = request.user emotion.weather = weathers emotion.image = InMemoryUploadedFile(img_io, None, filename, 'image/jpeg', sys.getsizeof(img_io), None) image_path = emotion.image.url emotion.save() emotion_json = {} emotion_json['image'] = image_path emotion_stat, emotion_max = emotion_stat_output_generator(emotion_list) tendancy = Tendancy.objects.get(profile=request.user).answer tendancy = ast.literal_eval(tendancy) emotion_musics = music_classifier(emotion_max, emotion, tendancy) emotion_json['emotions'] = emotion_stat emotion_json['max_emotion'] = emotion_max emotion_json['musics'] = emotion_musics return Response(emotion_json)
# PROJECT : django-easy-validator
def test_submission_tracking(self): """Test that submissions are tracked""" segment_mock = MagicMock() appoptics_mock = MagicMock() onadata.libs.utils.analytics.segment_analytics = segment_mock onadata.libs.utils.analytics.init_analytics() self.assertEqual(segment_mock.write_key, '123') # Test out that the track_object_event decorator # Tracks created submissions view = XFormSubmissionViewSet.as_view({ 'post': 'create', 'head': 'create' }) self._publish_xls_form_to_project() onadata.libs.utils.analytics.appoptics_api = appoptics_mock s = self.surveys[0] media_file = "1335783522563.jpg" path = os.path.join(self.main_directory, 'fixtures', 'transportation', 'instances', s, media_file) request_path = f"/{self.user.username}/submission" with open(path, 'rb') as f: f = InMemoryUploadedFile(f, 'media_file', media_file, 'image/jpg', os.path.getsize(path), None) submission_path = os.path.join(self.main_directory, 'fixtures', 'transportation', 'instances', s, s + '.xml') with open(submission_path, 'rb') as sf: data = {'xml_submission_file': sf, 'media_file': f} request = self.factory.post(request_path, data) request.user = AnonymousUser() response = view(request, username=self.user.username) self.assertContains(response, 'Successful submission', status_code=201) self.assertTrue(response.has_header('X-OpenRosa-Version')) self.assertTrue( response.has_header('X-OpenRosa-Accept-Content-Length')) self.assertTrue(response.has_header('Date')) self.assertEqual(response['Content-Type'], 'text/xml; charset=utf-8') self.assertEqual(response['Location'], 'http://testserver' + request_path) form_id = self.xform.pk username = self.user.username segment_mock.track.assert_called_with( '*****@*****.**', 'Submission created', { 'xform_id': self.xform.pk, 'organization': 'Bob Inc.', 'from': 'XML Submissions', 'label': f'form-{form_id}-owned-by-{username}', 'value': 1, 'event_by': 'anonymous' }, { 'source': 'test-server', 'organization': 'Bob Inc.', 'event_by': 'anonymous', 'action_from': 'XML Submissions', 'xform_id': self.xform.pk, 'path': f'/{username}/submission', 'url': f'http://testserver/{username}/submission', 'ip': '127.0.0.1', 'userId': self.user.id }) appoptics_mock.submit_measurement.assert_called_with( 'Submission created', 1, tags={ 'source': 'test-server', 'event_by': 'anonymous', 'organization': 'Bob_Inc.', 'action_from': 'XML_Submissions', 'xform_id': self.xform.pk, 'path': f'/{username}/submission', 'url': f'http://testserver/{username}/submission', 'ip': '127.0.0.1', 'userId': self.user.id })
def save(self, *args, **kwargs): if self.main == True: qs = ProductImage.objects.filter(product=self.product).exclude( id=self.id) qs.update(main=False) size = ((150, 100), (245, 164), (500, 333), (900, 600), (1280, 860)) method = Image.ANTIALIAS im = Image.open(io.BytesIO(self.image.read())) # im = Image.open(self.image) imw, imh = im.size if imw > 1920: img_big = ImageOps.fit(im, (1920, 1280), method=method, bleed=0.0, centering=(0.5, 0.5)) output = io.BytesIO() img_big.save(output, format="JPEG", quality=90) output.seek(0) self.image = InMemoryUploadedFile( output, "ImageField", f"{self.image.name}", "image/jpeg", output.getbuffer().nbytes, "utf-8", None, ) # Rectangle 150x100 img150 = ImageOps.fit(im, size[0], method=method, bleed=0.0, centering=(0.5, 0.5)) output = io.BytesIO() img150.save(output, format="JPEG", quality=90) output.seek(0) self.img150 = InMemoryUploadedFile( output, "ImageField", f"{self.image.name}", "image/jpeg", output.getbuffer().nbytes, "utf-8", None, ) # Rectangle 150x150 img150x150 = ImageOps.fit(im, (150, 150), method=method, bleed=0.0, centering=(0.5, 0.5)) output = io.BytesIO() img150x150.save(output, format="JPEG", quality=90) output.seek(0) self.img150x150 = InMemoryUploadedFile( output, "ImageField", f"{self.image.name}", "image/jpeg", output.getbuffer().nbytes, "utf-8", None, ) # Rectangle 245x164 img245 = ImageOps.fit(im, size[1], method=method, bleed=0.0, centering=(0.5, 0.5)) output = io.BytesIO() img245.save(output, format="JPEG", quality=90) output.seek(0) self.img245 = InMemoryUploadedFile( output, "ImageField", f"{self.image.name}", "image/jpeg", output.getbuffer().nbytes, "utf-8", None, ) # Square 245x245 img245x245 = ImageOps.fit(im, (245, 245), method=method, bleed=0.0, centering=(0.5, 0.5)) output = io.BytesIO() img245x245.save(output, format="JPEG", quality=90) output.seek(0) self.img245x245 = InMemoryUploadedFile( output, "ImageField", f"{self.image.name}", "image/jpeg", output.getbuffer().nbytes, "utf-8", None, ) # Rectangle 500x333 img500 = ImageOps.fit(im, size[2], method=method, bleed=0.0, centering=(0.5, 0.5)) output = io.BytesIO() img500.save(output, format="JPEG", quality=90) output.seek(0) self.img500 = InMemoryUploadedFile( output, "ImageField", f"{self.image.name}", "image/jpeg", output.getbuffer().nbytes, "utf-8", None, ) # Square 500x500 img500x500 = ImageOps.fit(im, (500, 500), method=method, bleed=0.0, centering=(0.5, 0.5)) output = io.BytesIO() img500x500.save(output, format="JPEG", quality=90) output.seek(0) self.img500x500 = InMemoryUploadedFile( output, "ImageField", f"{self.image.name}", "image/jpeg", output.getbuffer().nbytes, "utf-8", None, ) # Rectangle 900x600 img800 = ImageOps.fit(im, size[3], method=method, bleed=0.0, centering=(0.5, 0.5)) output = io.BytesIO() img800.save(output, format="JPEG", quality=90) output.seek(0) self.img800 = InMemoryUploadedFile( output, "ImageField", f"{self.image.name}", "image/jpeg", output.getbuffer().nbytes, "utf-8", None, ) # Square 900x900 img800x800 = ImageOps.fit(im, (900, 900), method=method, bleed=0.0, centering=(0.5, 0.5)) output = io.BytesIO() img800x800.save(output, format="JPEG", quality=90) output.seek(0) self.img800x800 = InMemoryUploadedFile( output, "ImageField", f"{self.image.name}", "image/jpeg", output.getbuffer().nbytes, "utf-8", None, ) super().save(*args, **kwargs)
def upload_file(file: InMemoryUploadedFile): with open('users/{}'.format(file.name), 'wb') as f: for i in file.chunks(): f.write(i)
def populate_feat_directory(request, collection, existing_dir=None): from nidmfsl.fsl_exporter.fsl_exporter import FSLtoNIDMExporter tmp_dir = tempfile.mkdtemp() if existing_dir is None else existing_dir exc = ValidationError try: if existing_dir is None: zip = zipfile.ZipFile(request.FILES['file']) zip.extractall(path=tmp_dir) rootpaths = [ v for v in os.listdir(tmp_dir) if not v.startswith('.') and not v.startswith('__MACOSX') ] if not rootpaths: raise exc("No contents found in the FEAT directory.") subdir = os.path.join(tmp_dir, rootpaths[0]) feat_dir = subdir if len(rootpaths) is 1 and os.path.isdir( subdir) else tmp_dir except: raise exc("Unable to unzip the FEAT directory: \n{0}.".format( get_traceback())) try: fslnidm = FSLtoNIDMExporter(feat_dir=feat_dir, version="0.2.0") fslnidm.parse() export_dir = fslnidm.export() except: raise exc("Unable to parse the FEAT directory: \n{0}.".format( get_traceback())) if not os.path.exists(export_dir): raise exc("Unable find nidm export of FEAT directory.") try: if existing_dir is not None: dname = os.path.basename(feat_dir) suffix = '.nidm.zip' if dname.endswith( 'feat') else '.feat.nidm.zip' destname = dname + suffix else: destname = request.FILES['file'].name.replace( 'feat.zip', 'feat.nidm.zip') destpath = os.path.join(tmp_dir, destname) nidm_zip = zipfile.ZipFile(destpath, 'w', zipfile.ZIP_DEFLATED) rootlen = len(feat_dir) + 1 for root, dirs, files in os.walk(export_dir): for dfile in files: filenm = os.path.join(root, dfile) nidm_zip.write(filenm, filenm[rootlen:]) nidm_zip.close() fh = open(destpath, 'r') request.FILES['file'] = InMemoryUploadedFile(ContentFile(fh.read()), "file", fh.name.split('/')[-1], "application/zip", os.path.getsize(destpath), "utf-8") except: raise exc( "Unable to convert NIDM results for NeuroVault: \n{0}".format( get_traceback())) else: return populate_nidm_results(request, collection) finally: shutil.rmtree(tmp_dir)
def save(self): im = Image.open(self.document) #opens a particular image output = BytesIO() #file is written into memory im = im.resize((self.width, self.height)) if self.flip == 'horizon': im = im.transpose(Image.FLIP_LEFT_RIGHT) elif self.flip == 'vertical': im = im.transpose(Image.FLIP_TOP_BOTTOM) elif self.flip == 'NONE': pass if self.rotate == 'clock': im = im.rotate(270) elif self.rotate == 'anti': im = im.rotate(90) elif self.rotate == 'NONE': pass if self.blur == 'y': im = im.filter(ImageFilter.BLUR) elif self.blur == 'n': pass if self.effect == 1: im = im.convert('RGB') r, g, b = im.split() im = Image.merge('RGB', (r, g, b)) elif self.effect == 2: im = im.convert('RGB') r, g, b = im.split() im = Image.merge('RGB', (b, g, r)) elif self.effect == 3: im = im.convert('RGB') r, g, b = im.split() im = Image.merge('RGB', (g, r, b)) elif self.effect == 4: width, height = im.size for i in range(width): for j in range(height): r, g, b = im.getpixel((i,j)) c = int(round((r+g+b)/3)) im.putpixel((i,j),(c,c,c)) elif self.effect == 5: im = im.convert('RGB') r, g, b = im.split() im = Image.merge('RGB', (r, b, g)) elif self.effect == 6: im = im.filter(ImageFilter.FIND_EDGES) elif self.effect == 7: im = ImageOps.invert(im) elif self.effect == 8: width, height = im.size for i in range(width): for j in range(height): r, g, b = im.getpixel((i,j)) c = int((round(r+g+b)/3)) R, G, B = c+100, c+100, c im.putpixel((i, j), (R, G, B)) im.save(output, format='JPEG', quality=100) # saving the image into the file in memory output.seek(0) self.document = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.document.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None) try: this = Document.objects.get(id=self.id) if this.document == self.document: self.document = this.document else: this.document.delete(save=False) except: pass # when new image super(Document, self).save()
def pdf_file(): bytes = io.BytesIO(b'%PDF-1.1\n' b'%\xc2\xa5\xc2\xb1\xc3\xab\n' b'\n' b'1 0 obj\n' b' << /Type /Catalog\n' b' /Pages 2 0 R\n' b' >>\n' b'endobj\n' b'\n' b'2 0 obj\n' b' << /Type /Pages\n' b' /Kids [3 0 R]\n' b' /Count 1\n' b' /MediaBox [0 0 300 144]\n' b' >>\n' b'endobj\n' b'\n' b'3 0 obj\n' b' << /Type /Page\n' b' /Parent 2 0 R\n' b' /Resources\n' b' << /Font\n' b' << /F1\n' b' << /Type /Font\n' b' /Subtype /Type1\n' b' /BaseFont /Times-Roman\n' b' >>\n' b' >>\n' b' >>\n' b' /Contents 4 0 R\n' b' >>\n' b'endobj\n' b'\n' b'4 0 obj\n' b' << /Length 55 >>\n' b'stream\n' b' BT\n' b' /F1 18 Tf\n' b' 0 0 Td\n' b' (Hello World) Tj\n' b' ET\n' b'endstream\n' b'endobj\n' b'\n' b'xref\n' b'0 5\n' b'0000000000 65535 f \n' b'0000000018 00000 n \n' b'0000000077 00000 n \n' b'0000000178 00000 n \n' b'0000000457 00000 n \n' b'trailer\n' b' << /Root 1 0 R\n' b' /Size 5\n' b' >>\n' b'startxref\n' b'565\n' b'%%EOF\n') return InMemoryUploadedFile(bytes, None, 'minimal.pdf', 'application/pdf', None, None)
class Document(models.Model, object): # all details comming about a particular picture uploaded # get saved in this table user = models.ForeignKey(User) status = models.CharField(max_length=7, choices=choice1, default="PUBLIC") width = models.IntegerField(blank=True, default=500, help_text="Enter positive value ") height = models.IntegerField(blank=True, default=500, help_text="Enter positive value ") flip = models.CharField(max_length=17, choices=choice3, default="NONE") rotate = models.CharField(max_length=15, choices=choice4, default='NONE') blur = models.CharField(max_length=5, choices=choice5, default='n') effect = models.IntegerField(choices=choice6, default=1) document = models.ImageField(upload_to=get_file_name) uploaded_at = models.DateTimeField(auto_now_add=True) like_or_not = models.IntegerField(default=0) like_user = models.ManyToManyField(User, related_name='hello', blank=True) def __str__(self): return self.user.username def __unicode__(self): # gives a common name to objects return self.document def get_absolute_url(self): return reverse('model_form_upload', kwargs={'pk': self.pk}) def save(self): im = Image.open(self.document) #opens a particular image output = BytesIO() #file is written into memory im = im.resize((self.width, self.height)) if self.flip == 'horizon': im = im.transpose(Image.FLIP_LEFT_RIGHT) elif self.flip == 'vertical': im = im.transpose(Image.FLIP_TOP_BOTTOM) elif self.flip == 'NONE': pass if self.rotate == 'clock': im = im.rotate(270) elif self.rotate == 'anti': im = im.rotate(90) elif self.rotate == 'NONE': pass if self.blur == 'y': im = im.filter(ImageFilter.BLUR) elif self.blur == 'n': pass if self.effect == 1: im = im.convert('RGB') r, g, b = im.split() im = Image.merge('RGB', (r, g, b)) elif self.effect == 2: im = im.convert('RGB') r, g, b = im.split() im = Image.merge('RGB', (b, g, r)) elif self.effect == 3: im = im.convert('RGB') r, g, b = im.split() im = Image.merge('RGB', (g, r, b)) elif self.effect == 4: width, height = im.size for i in range(width): for j in range(height): r, g, b = im.getpixel((i,j)) c = int(round((r+g+b)/3)) im.putpixel((i,j),(c,c,c)) elif self.effect == 5: im = im.convert('RGB') r, g, b = im.split() im = Image.merge('RGB', (r, b, g)) elif self.effect == 6: im = im.filter(ImageFilter.FIND_EDGES) elif self.effect == 7: im = ImageOps.invert(im) elif self.effect == 8: width, height = im.size for i in range(width): for j in range(height): r, g, b = im.getpixel((i,j)) c = int((round(r+g+b)/3)) R, G, B = c+100, c+100, c im.putpixel((i, j), (R, G, B)) im.save(output, format='JPEG', quality=100) # saving the image into the file in memory output.seek(0) self.document = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.document.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None) try: this = Document.objects.get(id=self.id) if this.document == self.document: self.document = this.document else: this.document.delete(save=False) except: pass # when new image super(Document, self).save()
def test_2_works(self): self.client.force_login(self.user) response = self.get(reverse('admin:music_publisher_work_changelist', )) self.assertEqual(response.status_code, 200) response = self.get(reverse('admin:music_publisher_writer_add'), re_post={ 'last_name': 'Lošija', 'ipi_name': 'X', 'ipi_base': '1000000000' }) self.assertEqual(response.status_code, 200) self.assertIn('Name contains invalid', response.content.decode()) self.assertIn('Value must be numeric.', response.content.decode()) self.assertIn('I-NNNNNNNNN-C format', response.content.decode()) response = self.get(reverse('admin:music_publisher_writer_add'), re_post={ 'first_name': 'VERY', 'last_name': 'COOL', 'ipi_name': '100', 'ipi_base': 'I-123456789-0' }) self.assertEqual(response.status_code, 200) self.assertIn('Not a valid IPI name', response.content.decode()) self.assertIn('Not valid:', response.content.decode()) response = self.get(reverse('admin:music_publisher_writer_add'), re_post={ 'first_name': 'VERY', 'last_name': 'COOL', 'ipi_name': '199', 'ipi_base': 'I-123456789-3' }) self.assertEqual(response.status_code, 302) writer = Writer.objects.all().first() self.assertFalse(writer._can_be_controlled) response = self.get(reverse('admin:music_publisher_writer_change', args=(writer.id, )), re_post={'pr_society': '052'}) self.assertEqual(response.status_code, 302) writer = Writer.objects.all().first() response = self.get(reverse('admin:music_publisher_writer_add'), re_post={ 'first_name': 'YANKEE', 'last_name': 'DOODLE', 'generally_controlled': 1, }) self.assertEqual(response.status_code, 200) self.assertIn('Unsufficient data for a', response.content.decode()) self.assertIn('This field is required.', response.content.decode()) response = self.get(reverse('admin:music_publisher_writer_add'), re_post={ 'first_name': 'YANKEE', 'last_name': 'DOODLE', 'ipi_name': '297', 'pr_society': '010', 'saan': 'DREAM', 'publisher_fee': '100' }) self.assertEqual(response.status_code, 200) self.assertIn('Only for a general agreemen', response.content.decode()) response = self.get(reverse('admin:music_publisher_writer_add'), re_post={ 'first_name': 'YANKEE', 'last_name': 'DOODLE', 'ipi_name': '297', 'pr_society': '010', 'generally_controlled': 1, 'saan': 'DREAM', 'publisher_fee': '100' }) self.assertEqual(response.status_code, 302) writer2 = Writer.objects.filter(pr_society='010').first() response = self.get(reverse('admin:music_publisher_writer_add'), re_post={ 'last_name': 'THIRD', 'ipi_name': '395', 'pr_society': '010', }) self.assertEqual(response.status_code, 302) writer3 = Writer.objects.filter(last_name='THIRD').first() response = self.get(reverse('admin:music_publisher_writer_add'), re_post={ 'last_name': 'OTHER', }) self.assertEqual(response.status_code, 302) writer4 = Writer.objects.filter(last_name='OTHER').first() response = self.get(reverse('admin:music_publisher_writer_changelist')) self.assertTrue(writer._can_be_controlled) response = self.get(reverse('admin:music_publisher_albumcd_add'), re_post={ 'album_title': 'VERY COOL', 'ean': '199', }) self.assertEqual(response.status_code, 200) self.assertIn('does not match EAN13 format', response.content.decode()) response = self.get(reverse('admin:music_publisher_albumcd_add'), re_post={ 'ean': '1234567890123', }) self.assertEqual(response.status_code, 200) self.assertIn('Invalid EAN.', response.content.decode()) self.assertIn('Required if Album Title ', response.content.decode()) response = self.get(reverse('admin:music_publisher_albumcd_add'), re_post={ 'cd_identifier': 'C00L', 'ean': '1234567890123', }) self.assertEqual(response.status_code, 200) self.assertIn('Required if EAN or release ', response.content.decode()) response = self.get(reverse('admin:music_publisher_albumcd_add'), re_post={ 'album_title': 'VERY COOL', }) self.assertEqual(response.status_code, 302) albumcd = AlbumCD.objects.all().first() self.assertEqual(str(albumcd), 'VERY COOL') response = self.get(reverse('admin:music_publisher_albumcd_change', args=(albumcd.id, )), re_post={ 'cd_identifier': 'C00L', 'release_date': '2018-01-01', 'ean': '4006381333931', }) self.assertEqual(response.status_code, 302) albumcd = AlbumCD.objects.all().first() response = self.get( reverse('admin:music_publisher_albumcd_changelist')) self.assertEqual(response.status_code, 200) self.assertEqual(str(albumcd), 'VERY COOL (C00L)') response = self.get(reverse('admin:music_publisher_artist_add'), re_post={ 'first_name': 'VERY', 'last_name': 'VERY COOL', 'isni': '1234567890123', }) self.assertEqual(response.status_code, 200) response = self.get(reverse('admin:music_publisher_artist_add'), re_post={ 'last_name': 'VERY COOL', 'isni': '12345678SD23', }) self.assertEqual(response.status_code, 200) response = self.get(reverse('admin:music_publisher_artist_add', ), re_post={ 'first_name': 'VERY', 'last_name': 'VERY COOL', 'isni': '1X', }) self.assertEqual(response.status_code, 302) artist = Artist.objects.all().first() response = self.get(reverse('admin:music_publisher_artist_changelist')) self.assertEqual(response.status_code, 200) response = self.get(reverse('admin:music_publisher_work_add'), re_post={ 'title': 'LOŠ NASLOV', 'iswc': 'ADC', 'writerinwork_set-0-writer': writer.id, 'writerinwork_set-0-capacity': 'XX', 'writerinwork_set-0-relative_share': '100', 'writerinwork_set-0-controlled': '1', 'writerinwork_set-0-saan': '1LJ4V4', 'writerinwork_set-0-publisher_fee': '25', }) self.assertEqual(response.status_code, 200) self.assertIn('Title contains invalid', response.content.decode()) self.assertIn('match TNNNNNNNNNC', response.content.decode()) response = self.get(reverse('admin:music_publisher_work_add'), re_post={ 'title': 'GOOD TITLE', 'iswc': 'T1234567893', 'writerinwork_set-0-writer': writer.id, 'writerinwork_set-0-capacity': 'CA', 'writerinwork_set-0-relative_share': '50', 'writerinwork_set-0-controlled': '', 'writerinwork_set-0-saan': '', 'writerinwork_set-0-publisher_fee': '', 'writerinwork_set-1-writer': writer.id, 'writerinwork_set-1-capacity': 'CA', 'writerinwork_set-1-relative_share': '50', 'writerinwork_set-1-controlled': '', 'writerinwork_set-1-saan': '', 'writerinwork_set-1-publisher_fee': '', 'firstrecording-TOTAL_FORMS': 1, 'firstrecording-0-album_cd': albumcd.id, 'firstrecording-0-isrc': 'USX1X12345', }) self.assertEqual(response.status_code, 200) self.assertIn('must be controlled', response.content.decode()) self.assertIn('not match ISRC', response.content.decode()) response = self.get(reverse('admin:music_publisher_work_add'), re_post={ 'title': 'GOOD TITLE', 'iswc': 'T1234567894', 'alternatetitle_set-TOTAL_FORMS': 1, 'alternatetitle_set-0-title': 'BETTER TITLE', 'writerinwork_set-TOTAL_FORMS': 5, 'writerinwork_set-0-writer': writer.id, 'writerinwork_set-0-capacity': 'CA', 'writerinwork_set-0-relative_share': '25', 'writerinwork_set-0-controlled': '1', 'writerinwork_set-0-saan': '1LJ4V4', 'writerinwork_set-0-publisher_fee': '25', 'writerinwork_set-1-writer': writer2.id, 'writerinwork_set-1-capacity': 'CA', 'writerinwork_set-1-relative_share': '11.66', 'writerinwork_set-1-controlled': '1', 'writerinwork_set-2-writer': writer3.id, 'writerinwork_set-2-capacity': 'A ', 'writerinwork_set-2-relative_share': '33.33', 'writerinwork_set-2-controlled': '1', 'writerinwork_set-2-saan': '1LJ4V4', 'writerinwork_set-2-publisher_fee': '25', 'writerinwork_set-3-writer': writer.id, 'writerinwork_set-3-capacity': 'CA', 'writerinwork_set-3-relative_share': '25', 'writerinwork_set-4-writer': writer3.id, 'writerinwork_set-4-relative_share': '5', 'firstrecording-TOTAL_FORMS': 1, 'firstrecording-0-album_cd': albumcd.id, 'firstrecording-0-artist': artist.id, 'firstrecording-0-isrc': 'USX1X1234567', 'firstrecording-0-duration': '01:23', 'firstrecording-0-release_date': '2018-01-31', }) self.assertEqual(response.status_code, 302) work = Work.objects.all().first() settings.MUSIC_PUBLISHER_SETTINGS['allow_multiple_ops'] = False response = self.get(reverse('admin:music_publisher_work_add'), re_post={ 'title': 'ANOTHER TITLE', 'writerinwork_set-TOTAL_FORMS': 2, 'writerinwork_set-0-writer': writer.id, 'writerinwork_set-0-capacity': 'CA', 'writerinwork_set-0-relative_share': '50', 'writerinwork_set-0-controlled': '1', 'writerinwork_set-0-saan': '1LJ4V4', 'writerinwork_set-0-publisher_fee': '25', 'writerinwork_set-1-writer': writer.id, 'writerinwork_set-1-capacity': 'CA', 'writerinwork_set-1-relative_share': '50', }) self.assertEqual(response.status_code, 200) settings.MUSIC_PUBLISHER_SETTINGS['allow_multiple_ops'] = True response = self.get(reverse('admin:music_publisher_work_add'), re_post={ 'title': 'ANOTHER TITLE', 'writerinwork_set-TOTAL_FORMS': 4, 'writerinwork_set-0-writer': writer.id, 'writerinwork_set-0-capacity': 'CA', 'writerinwork_set-0-relative_share': '25', 'writerinwork_set-0-controlled': '1', 'writerinwork_set-0-saan': '1LJ4V4', 'writerinwork_set-0-publisher_fee': '25', 'writerinwork_set-1-writer': writer.id, 'writerinwork_set-1-capacity': 'CA', 'writerinwork_set-1-relative_share': '25', 'writerinwork_set-2-writer': writer3.id, 'writerinwork_set-2-relative_share': '25', 'writerinwork_set-3-relative_share': '25', 'artistinwork_set-TOTAL_FORMS': 1, 'artistinwork_set-0-artist': artist.id, }) self.assertEqual(response.status_code, 302) work2 = Work.objects.filter(title='ANOTHER TITLE').first() response = self.get(reverse('admin:music_publisher_work_add'), re_post={ 'title': 'MODIFICATION1', 'original_title': 'ORIGINAL', 'writerinwork_set-TOTAL_FORMS': 4, 'writerinwork_set-0-writer': writer.id, 'writerinwork_set-0-capacity': 'CA', 'writerinwork_set-0-relative_share': '25', 'writerinwork_set-0-controlled': '1', 'writerinwork_set-0-saan': '1LJ4V4', 'writerinwork_set-0-publisher_fee': '25', 'writerinwork_set-1-writer': writer.id, 'writerinwork_set-1-capacity': 'CA', 'writerinwork_set-1-relative_share': '25', 'writerinwork_set-2-writer': writer3.id, 'writerinwork_set-2-relative_share': '25', 'writerinwork_set-3-relative_share': '25', 'artistinwork_set-TOTAL_FORMS': 1, 'artistinwork_set-0-artist': artist.id, }) self.assertEqual(response.status_code, 200) self.assertIn('one writer must be Arranger', response.content.decode()) response = self.get(reverse('admin:music_publisher_work_add'), re_post={ 'title': 'MODIFICATION2', 'original_title': 'ORIGINAL', 'writerinwork_set-TOTAL_FORMS': 4, 'writerinwork_set-0-writer': writer.id, 'writerinwork_set-0-capacity': 'CA', 'writerinwork_set-0-relative_share': '25', 'writerinwork_set-0-controlled': '1', 'writerinwork_set-0-saan': '1LJ4V4', 'writerinwork_set-0-publisher_fee': '25', 'writerinwork_set-1-writer': writer.id, 'writerinwork_set-1-capacity': 'AR', 'writerinwork_set-1-relative_share': '25', 'writerinwork_set-2-writer': writer3.id, 'writerinwork_set-2-relative_share': '25', 'writerinwork_set-3-relative_share': '25', 'artistinwork_set-TOTAL_FORMS': 1, 'artistinwork_set-0-artist': artist.id, }) self.assertEqual(response.status_code, 200) self.assertIn('same as in controlled', response.content.decode()) response = self.get(reverse('admin:music_publisher_work_add'), re_post={ 'title': 'MODIFICATION', 'original_title': 'ORIGINAL', 'writerinwork_set-TOTAL_FORMS': 4, 'writerinwork_set-0-writer': writer.id, 'writerinwork_set-0-capacity': 'AR', 'writerinwork_set-0-relative_share': '25', 'writerinwork_set-0-controlled': '1', 'writerinwork_set-0-saan': '1LJ4V4', 'writerinwork_set-0-publisher_fee': '25', 'writerinwork_set-1-writer': writer.id, 'writerinwork_set-1-capacity': 'AR', 'writerinwork_set-1-relative_share': '25', 'writerinwork_set-2-writer': writer3.id, 'writerinwork_set-2-relative_share': '25', 'writerinwork_set-2-capacity': 'CA', 'writerinwork_set-3-relative_share': '25', 'artistinwork_set-TOTAL_FORMS': 1, 'artistinwork_set-0-artist': artist.id, }) self.assertEqual(response.status_code, 302) work3 = Work.objects.filter(title='MODIFICATION').first() response = self.get(reverse('admin:music_publisher_work_add'), re_post={ 'title': 'NO COMPOSER TITLE', 'writerinwork_set-0-writer': writer.id, 'writerinwork_set-0-capacity': 'A ', 'writerinwork_set-0-relative_share': '100', 'writerinwork_set-0-controlled': '1', 'writerinwork_set-0-saan': '1LJ4V4', 'writerinwork_set-0-publisher_fee': '25', }) self.assertEqual(response.status_code, 200) response = self.get(reverse('admin:music_publisher_work_add'), re_post={ 'title': 'OVER 100 PERCENT', 'writerinwork_set-0-writer': writer.id, 'writerinwork_set-0-capacity': 'CA', 'writerinwork_set-0-relative_share': '101', 'writerinwork_set-0-controlled': '1', 'writerinwork_set-0-saan': '1LJ4V4', 'writerinwork_set-0-publisher_fee': '25', }) self.assertEqual(response.status_code, 200) response = self.get(reverse('admin:music_publisher_work_add'), re_post={ 'title': 'ORIGINAL WITH AN ARRANGER', 'writerinwork_set-TOTAL_FORMS': 2, 'writerinwork_set-0-writer': writer.id, 'writerinwork_set-0-capacity': 'CA', 'writerinwork_set-0-relative_share': '0', 'writerinwork_set-1-writer': writer2.id, 'writerinwork_set-1-capacity': 'AR', 'writerinwork_set-1-relative_share': '100', 'writerinwork_set-1-controlled': '1', }) self.assertEqual(response.status_code, 200) self.assertIn('Not allowed in original', response.content.decode()) response = self.get(reverse('admin:music_publisher_work_changelist')) response = self.get( reverse('admin:music_publisher_work_change', args=(work.id, ))) PREFIX = settings.MUSIC_PUBLISHER_SETTINGS['work_id_prefix'] settings.MUSIC_PUBLISHER_SETTINGS['work_id_prefix'] = '' response = self.get(reverse('admin:music_publisher_cwrexport_add'), re_post={ 'nwr_rev': 'NWR', 'works': [work.id, work2.id, work3.id] }) settings.MUSIC_PUBLISHER_SETTINGS['work_id_prefix'] = PREFIX cwr_export = CWRExport.objects.all().first() self.assertEqual(cwr_export.cwr[86:], CWR_CONTENT[86:]) response = self.get(reverse('admin:music_publisher_cwrexport_add'), re_post={ 'nwr_rev': 'REV', 'works': [work.id, work2.id] }) response = self.get(reverse('admin:music_publisher_cwrexport_change', args=(cwr_export.id, )), re_post={ 'nwr_rev': 'NWR', 'works': [work.id, work2.id] }) response = self.get('{}?download=1'.format( reverse('admin:music_publisher_work_change', args=(cwr_export.id, )))) self.assertEqual(response.status_code, 200) response = self.client.post( reverse('admin:music_publisher_work_changelist'), data={ 'action': 'create_cwr', 'select_across': 1, 'index': 0, '_selected_action': work.id }) response = self.get( reverse('admin:music_publisher_cwrexport_changelist')) self.assertEqual(response.status_code, 200) response = self.get( reverse('admin:music_publisher_cwrexport_change', args=(cwr_export.id, ))) self.assertEqual(response.status_code, 200) response = self.client.get( reverse('admin:music_publisher_cwrexport_change', args=(cwr_export.id, )) + '?download=true', ) self.assertEqual(response.status_code, 200) response = self.client.get( reverse('admin:music_publisher_cwrexport_change', args=(cwr_export.id, )) + '?preview=true', ) self.assertEqual(response.status_code, 200) response = self.get( reverse('admin:music_publisher_work_changelist', ) + '?has_iswc=N&has_rec=Y') self.assertEqual(response.status_code, 200) self.get( reverse('admin:music_publisher_work_changelist', ) + '?has_iswc=Y&has_rec=N&q=01') self.assertEqual(response.status_code, 200) response = self.get( reverse('admin:music_publisher_artist_add') + '?_popup=1') self.assertEqual(response.status_code, 200) response = self.get( reverse('admin:music_publisher_albumcd_add') + '?_popup=1') self.assertEqual(response.status_code, 200) response = self.get( reverse('admin:music_publisher_work_add') + '?_popup=1') self.assertEqual(response.status_code, 200) mock = StringIO() mock.write(ACK_CONTENT) mock.seek(0) mockfile = InMemoryUploadedFile(mock, 'acknowledgement_file', 'CW180001000_FOO.V21', 'text', 0, None) response = self.get(reverse('admin:music_publisher_ackimport_add'), re_post={'acknowledgement_file': mockfile}) self.assertEqual(response.status_code, 302) ackimport = ACKImport.objects.first() # open and repost mock.seek(0) mockfile = InMemoryUploadedFile(mock, 'acknowledgement_file', 'CW180001000_FOO.V21', 'text', 0, None) response = self.get(reverse('admin:music_publisher_ackimport_change', args=(ackimport.id, )), re_post={'acknowledgement_file': mockfile}) self.assertEqual(response.status_code, 302) # second pass, same thing mock.seek(0) mockfile = InMemoryUploadedFile(mock, 'acknowledgement_file', 'CW180001000_FOO.V21', 'text', 0, None) response = self.get(reverse('admin:music_publisher_ackimport_add'), re_post={'acknowledgement_file': mockfile}) self.assertEqual(response.status_code, 302) # incorrect filename mock.seek(0) mockfile = InMemoryUploadedFile(mock, 'acknowledgement_file', 'CW180001000_FOO.V22', 'text', 0, None) response = self.get(reverse('admin:music_publisher_ackimport_add'), re_post={'acknowledgement_file': mockfile}) self.assertEqual(response.status_code, 200) # incorrect header mock.seek(3) mockfile = InMemoryUploadedFile(mock, 'acknowledgement_file', 'CW180001000_FOO.V21', 'text', 0, None) response = self.get(reverse('admin:music_publisher_ackimport_add'), re_post={'acknowledgement_file': mockfile}) self.assertEqual(response.status_code, 200) # Removing needed data from controlled writer response = self.get(reverse('admin:music_publisher_writer_change', args=(writer.id, )), re_post={'pr_society': ''}) self.assertEqual(response.status_code, 200) self.assertIn('controlled in at least', response.content.decode()) response = self.get(reverse('admin:music_publisher_work_change', args=(work.id, )), re_post={ 'title': 'GOOD TITLE', 'iswc': 'T1234567894', 'alternatetitle_set-TOTAL_FORMS': 1, 'alternatetitle_set-0-title': 'BETTER TITLE', 'writerinwork_set-TOTAL_FORMS': 2, 'writerinwork_set-0-writer': '', 'writerinwork_set-0-capacity': 'CA', 'writerinwork_set-0-relative_share': '50', 'writerinwork_set-0-controlled': '1', 'writerinwork_set-0-saan': '1LJ4V4', 'writerinwork_set-0-publisher_fee': '25', 'writerinwork_set-1-writer': writer4.id, 'writerinwork_set-1-capacity': 'CA', 'writerinwork_set-1-relative_share': '50', 'writerinwork_set-1-controlled': '1', 'firstrecording-TOTAL_FORMS': 1, 'firstrecording-0-album_cd': albumcd.id, 'firstrecording-0-artist': artist.id, 'firstrecording-0-isrc': 'USX1X1234567', 'firstrecording-0-duration': '01:23', 'firstrecording-0-release_date': '2018-01-31', }) self.assertEqual(response.status_code, 200) self.assertIn('Must be set for', response.content.decode()) response = self.get(reverse('admin:music_publisher_work_change', args=(work.id, )), re_post={ 'title': 'GOOD TITLE', 'iswc': 'T1234567894', 'alternatetitle_set-TOTAL_FORMS': 1, 'alternatetitle_set-0-title': 'BETTER TITLE', 'writerinwork_set-TOTAL_FORMS': 3, 'writerinwork_set-0-writer': writer.id, 'writerinwork_set-0-capacity': 'CA', 'writerinwork_set-0-relative_share': '50', 'writerinwork_set-0-controlled': '1', 'writerinwork_set-0-saan': '1LJ4V4', 'writerinwork_set-0-publisher_fee': '25', 'writerinwork_set-1-writer': writer2.id, 'writerinwork_set-1-capacity': 'CA', 'writerinwork_set-1-relative_share': '25', 'writerinwork_set-1-controlled': '', 'writerinwork_set-2-writer': writer4.id, 'writerinwork_set-2-saan': '1LJ4V4', 'writerinwork_set-2-publisher_fee': '25', 'firstrecording-TOTAL_FORMS': 1, 'firstrecording-0-album_cd': albumcd.id, 'firstrecording-0-artist': artist.id, 'firstrecording-0-isrc': 'USX1X1234567', 'firstrecording-0-duration': '01:23', 'firstrecording-0-release_date': '2018-01-31', }) self.assertEqual(response.status_code, 200) self.assertIn('Must be set for', response.content.decode()) # JSON must be at the end, so the export is complete response = self.client.post( reverse('admin:music_publisher_work_changelist'), data={ 'action': 'create_normalized_json', 'select_across': 1, 'index': 0, '_selected_action': work.id }) response = self.client.post( reverse('admin:music_publisher_work_changelist'), data={ 'action': 'create_json', 'select_across': 1, 'index': 0, '_selected_action': work.id }) self.assertEqual(str(WorkAcknowledgement.objects.first()), 'RA')
def post(self, request, *args, **kwargs): self.object = self.get_object() if not self.object.auth_user_id == request.user.id: return HttpResponse( '<div align="center"><h1>You are not the author of this brab</h1><br>...therefore you may not edit it!</div>' ) brabform = BrabForm(data=request.POST, instance=self.object, prefix="B") if brabform.is_valid(): brabform.instance.auth_user_id = request.user.id tags = brabform.cleaned_data['tags'] tags = self.parse_tags(tags) category = brabform.cleaned_data['category'] brab = brabform.save(commit=False) brab.save() tag_count = self.add_tag_records(tags, request.user.id, brab.pk) category_count = self.add_category_records(category, request.user.id, brab.pk) picture_form = PictureForm(data=request.POST, prefix="P", files=request.FILES) picture_string = picture_form.data['P-new_picture'] # This POST variable will only be filled if client browser supports awesomecropper plugin # because then the HTML5 canvas content will be posted, and not file read from the disk number_of_turns = int(picture_form.data['P-rotate']) if picture_string: file_to_add = CreateInMemoryUploadedFileFromBase64EncodedImage( picture_string, "P-picture", number_of_turns) if file_to_add: request.FILES.appendlist("P-picture", file_to_add) picture_form = PictureForm(data=request.POST, prefix="P", files=request.FILES) else: try: image_file_name = request.FILES[u'P-picture'].name new_image_file_present = True except: new_image_file_present = False if new_image_file_present: image_file_extension = image_file_name.split(".")[-1] content_type = request.FILES[u'P-picture'].content_type new_file_name = md5(str( localtime())).hexdigest() + image_file_extension if number_of_turns == 0: request.FILES[u'P-picture'].name = new_file_name else: rotated_file = RotateImage(request.FILES["P-picture"], number_of_turns, image_file_extension) if rotated_file: in_memory_uploaded_file = InMemoryUploadedFile( rotated_file, "P-picture", new_file_name, content_type, rotated_file.size, None) request.FILES[ "P-picture"] = in_memory_uploaded_file picture_form = PictureForm(data=request.POST, prefix="P", files=request.FILES) if picture_form.is_valid(): if self.object.pictures_set.count(): picture_title = picture_form.cleaned_data['title'].title() title_counter = 0 temp_title = picture_title while self.object.pictures_set.filter( title__exact=temp_title): title_counter = title_counter + 1 temp_title = picture_title + ' ' + str( title_counter).zfill(3) picture_form.instance.title = temp_title if not self.object.pictures_set.count(): # This is the first picture we are adding to a brab picture_form.instance.main = 1 # Fill picture.brab_id with pk of the current brab picture_form.instance.brab_id = self.object.pk picture_form.instance.visible = 1 picture_form.save() new_picture_pk = picture_form.instance.id else: new_picture_pk = None for key in request.POST: if key.startswith('rotate_') and not (request.POST[key] == "0"): picture_record_id = re.sub(r"\D", "", key) number_of_turns = int(request.POST[key]) picture_to_rotate = Pictures.objects.get( id=picture_record_id) RotateImageFromS3(picture_to_rotate.picture.name, number_of_turns) if key.startswith('delete_') and request.POST[key] == 'on': picture_record_id = re.sub(r"\D", "", key) Pictures.objects.filter(id=picture_record_id).update( deleted=1) if key.startswith('makemain_') and request.POST[key] == 'on': if self.object.pictures_set.count(): for picture in self.object.pictures_set.all(): picture.main = 0 picture.save() picture_record_id = re.sub(r"\D", "", key) if not picture_record_id: picture_record_id = new_picture_pk Pictures.objects.filter(id=picture_record_id).update( main=1) if key.startswith('hide_') and request.POST[key] == 'on': picture_record_id = re.sub(r"\D", "", key) if not picture_record_id: picture_record_id = new_picture_pk Pictures.objects.filter(id=picture_record_id).update( visible=0) if key.startswith('show_') and request.POST[key] == 'on': picture_record_id = re.sub(r"\D", "", key) Pictures.objects.filter(id=picture_record_id).update( visible=1) return HttpResponseRedirect(brab.get_absolute_url()) else: # Find what categories and tags is currently edited brab marked with so that # appropriate fields would appear pre-filled in the template selected_categories = Category_to_brab.objects.filter( brab_id=self.object.pk) categories = [] if selected_categories: for category_instance in selected_categories: categories.append(category_instance.category_id) selected_tags = Tag_to_brab.objects.filter(brab_id=self.object.pk) tags = '' tag_count = 0 if selected_tags: for tag_instance in selected_tags: if tag_count: tags = tags + ', ' tags = tags + tag_instance.tag.tag tag_count = tag_count + 1 # brabform = BrabForm(instance=self.object, initial={'category':categories, 'tags':tags}, prefix="B") picture_form = PictureForm(prefix="P") # self.object = None context = self.get_context_data(object=self.object, brabform=brabform, P_form=picture_form) return self.render_to_response(context)
def update_chapter(request): if request.method == 'POST': t = request.POST.get('type', '') i = request.POST.get('id', '') chapter = Chapter.objects.get(id=i) if not chapter: return work = chapter.work if t == 'update': d = {} queue = ChapterQueue.objects.filter( target=work.work_target, comic_number=work.work_num, chapter_number=chapter.reg_no, is_checked=False) if queue: d['success'] = False d['message'] = u'이미 등록된 큐가 있습니다.' else: queue = ChapterQueue.objects.create( target=work.work_target, user=request.user, comic_number=work.work_num, chapter_number=chapter.reg_no, checked_at=datetime.now() ) d['success'] = True d['message'] = u'큐에 등록되었습니다.' return HttpResponse(json.dumps(d), content_type='application/json') elif t == 'public': chapter.public = not chapter.public chapter.save() d = { 'message': (u'공개 설정되었습니다.' if chapter.public else u'비공개 설정되었습니다.'), 'public': chapter.public, } return HttpResponse(json.dumps(d), content_type='application/json') elif t == 'thumbnail': image = request.FILES.get('image', '') d = { 'success': False, 'message': '', } try: io = StringIO.StringIO() for chunk in image.chunks(): io.write(chunk) io.seek(0) im = PIL_Image.open(io) im.thumbnail((210, 90), PIL_Image.ANTIALIAS) if chapter.thumbnail: im.save(chapter.thumbnail.path, 'JPEG') else: tmp = StringIO.StringIO() im.save(tmp, 'JPEG') tmp_file = InMemoryUploadedFile( tmp, None, 'foo.jpg', 'image/jpeg', tmp.len, None) chapter.thumbnail = tmp_file chapter.save() except Exception, e: d['message'] = str(e) else: d['success'] = True return HttpResponse(json.dumps(d), content_type='application/json') elif t == 'comment': comment = request.POST.get('comment', '') d = {'success': False, 'message': ''} if comment: chapter.description = comment chapter.save() d = {'success': True} return HttpResponse(json.dumps(d), content_type='application/json')
def handle_twitter_message(mid: str, psid, message, user): text: str = message.get("text") attachment: dict = message.get("attachment") if text is not None: platform: ConversationPlatform = ConversationPlatform.exists( ConversationPlatform.TWITTER, psid) if not platform: kc_user = django_keycloak_auth.users.get_or_create_user( federated_provider="twitter", federated_user_id=user.get("id"), federated_user_name=user.get("screen_name"), first_name=user.get("name"), ) if kc_user: django_keycloak_auth.users.link_roles_to_user( kc_user.get("id"), ["customer"]) user_id = kc_user.get("id") platform = ConversationPlatform.create( ConversationPlatform.TWITTER, psid, customer_user_id=user_id) conversation = platform.conversation if not conversation.conversation_user_id: kc_user = django_keycloak_auth.users.get_or_create_user( federated_provider="twitter", federated_user_id=user.get("id"), federated_user_name=user.get("screen_name"), first_name=user.get("name"), ) if kc_user: django_keycloak_auth.users.link_roles_to_user( kc_user.get("id"), ["customer"]) conversation.update_user_id(kc_user.get("id")) if conversation.conversation_user_id: django_keycloak_auth.users.link_federated_identity_if_not_exists( str(conversation.conversation_user_id), federated_provider="twitter", federated_user_id=user.get("id"), federated_user_name=user.get("screen_name"), ) django_keycloak_auth.users.update_user(str( conversation.conversation_user_id), first_name=user.get("name")) if not Message.message_exits(platform, mid): message_m: Message = Message( platform=platform, platform_message_id=mid, text=html.conditional_escape(text.strip()), direction=Message.FROM_CUSTOMER, state=Message.DELIVERED, ) platform.is_typing = False platform.save() if attachment: if attachment["type"] == "media": creds = views.get_creds() url: str = attachment["media"]["media_url_https"] indices: typing.Tuple = attachment["media"]["indices"] message_m.text = (text[:indices[0]] + text[indices[1]:]).strip() media_r = requests.get(url, auth=creds) if media_r.status_code == 200: orig_file_name = os.path.basename( urllib.parse.urlparse(url).path) fs = DefaultStorage() file_name = fs.save(orig_file_name, BytesIO(media_r.content)) message_m.image = fs.base_url + file_name message_m.save() handle_mark_twitter_message_read.delay(psid, mid) operator_interface.tasks.process_message.delay(message_m.id) file_name = os.path.basename( urllib.parse.urlparse(user["profile_image_url_https"]).path) r = requests.get(user["profile_image_url_https"]) if r.status_code == 200: if not conversation.conversation_pic: conversation.conversation_pic.save( file_name, InMemoryUploadedFile( file=BytesIO(r.content), size=len(r.content), charset=r.encoding, content_type=r.headers.get("content-type"), field_name=file_name, name=file_name, ), ) django_keycloak_auth.users.update_user( str(conversation.conversation_user_id), profile_picture=conversation.conversation_pic.url, ) conversation.save()
g = goods.objects.all() for i in g: i.qrcode.delete() g = goods.objects.filter(idbitrix__isnull=False, status=True).exclude( idbitrix__exact='') #товары только с idbitrix, исключаем пустые for i in g: print "MAKE QRCODE ID %s" % i.idbitrix qr = qrcode.QRCode( version=None, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=100, border=1, ) #url = 'http://babah24.ru/katalog/detail.php?ELEMENT_ID=%s' % i.idbitrix url = 'http://babah24.ru/qr/%s' % i.idbitrix qr.add_data(url) qr.make(fit=True) #img = qr.make_image(fill_color="#FF6600", back_color="white") img = qr.make_image(fill_color="white", back_color="black") #img = qr.make_image(fill_color="black", back_color="white") buffer = StringIO.StringIO() img.save(buffer) filename = '%s.png' % id_generator() filebuffer = InMemoryUploadedFile(buffer, None, filename, 'image/png', buffer.len, None) i.qrcode.save(filename, filebuffer)
def AJAX_Add_New_Link(request): from enterlink.media_functions import getYouTubeIdIfPresent # Get the POST variables pageSlug = request.POST['pageSlug'] option = request.POST['group1'] citeHTML = request.POST['citeHTML'] URLComment = request.POST['nl_linkcomment'] # Make sure an empty description was not provided placeholderPresent = any(placeholder in URLComment for placeholder in PLACEHOLDER_LIST) if (placeholderPresent or URLComment.strip() == "" or URLComment is None or URLComment == "<br data-mce-bogus=\"1\">"): return HttpResponse("ERROR_NO_DESCRIPTION") else: pass # Get and format the UTC timestamp timestamp = datetime.datetime.utcnow() timestamp = pytz.utc.localize(timestamp).strftime( '%m/%d/%Y %I:%M:%S %p %Z') # Get the article object from the URL slug provided cleanedParamList = getTheArticleObject(pageSlug) pageSlug = cleanedParamList[0] articleObject = cleanedParamList[1] # Parse all the current citations for the article. # This will be used later for things such as finding duplicates and getting the citation number theSoup = BeautifulSoup(citeHTML, "html5lib") resultDictionary = {} parseTinyMCE_Citations(theSoup, resultDictionary) # Set up a blank dictionary for the new link newLinkDict = { "url": None, "thumb": None, "description": URLComment, "category": "NONE", "integer": None, "isSocial": False, "attr": None, "timestamp": timestamp, "mime": None, "attribution_url": None } # Create a list of all current citations citationList, urlList = [], [] try: for citation in resultDictionary["CITATION_OBJECTS"]: citationList.append(int(citation["integer"])) urlList.append(citation["url"]) except: pass # Calculate and set the citation number for the new link if len(citationList) == 0: citationInteger = 1 else: try: citationInteger = max(citationList) + 1 except: citationInteger = None newLinkDict["integer"] = citationInteger # Check if the new link is a file if option == 'id_file': # Get and set some variables theFile = request.FILES['file'] # Add the file to the Amazon S3 bucket and get some information about it resultPack = addMediaImage(request=request, pageID=pageSlug, theFile=theFile, fileComment=URLComment, PLACEHOLDER_LIST=PLACEHOLDER_LIST, inputMime="EMPTY") # Update the new link dictionary with information about the file newLinkDict["url"] = resultPack["url"] newLinkDict["thumb"] = resultPack["thumb"] newLinkDict["mime"] = resultPack["mime"] newLinkDict["category"] = linkCategorizer(resultPack["url"], resultPack["mime"]) # Check for duplicate links if dupeLinkDetector(newLinkDict["url"], urlList): return HttpResponse("ERROR_ALREADY_EXISTS") # Decide where to put the new link. If it is an image, video, or YouTube link, put it in the media gallery. # Otherwise, put it in the normal citation list. if newLinkDict["category"] == "NONE": newLinkHTMLBlock = render_to_string( 'enterlink/ajax_link_singlet.html', {'theLink': newLinkDict}) return JsonResponse({ "type": "NORMAL", "htmlblock": newLinkHTMLBlock }) else: newLinkHTMLBlock = render_to_string( 'enterlink/ajax_media_gallery_singlet.html', {'theLink': newLinkDict}) return JsonResponse({ "type": "MEDIA", "htmlblock": newLinkHTMLBlock }) # Check if the new link is a URL elif option == 'id_linkurl': # Get the URL and check if it is a Wikipedia link. if request.POST['linkurl']: theURL = request.POST['linkurl'] if ('wikipedia.org' in theURL): return HttpResponse("ERROR_WIKIPEDIA_LINK") else: pass else: return HttpResponse("ERROR_NO_URL") # Check for a duplicate link if dupeLinkDetector(theURL, urlList): return HttpResponse("ERROR_ALREADY_EXISTS") # Update the new link JSON data newLinkDict["url"] = theURL newLinkDict["isSocial"] = profileLinkTester(theURL)["isProfileLink"] # Check if the URL is a link to a media object isMedia = False try: # Ping the URL to see get the data and response headers mediaTest = requests.get(theURL, headers=REQUEST_HEADER, timeout=6, verify=False, stream=True) # See if the response header indicates it is a media item. If so, set isMedia to True listOfMedias = ["video", "image", "audio"] for mediaItem in listOfMedias: mediaName = u"%s/" % mediaItem if mediaName in mediaTest.headers['Content-Type']: isMedia = True break # Check for YouTube youtubeID = getYouTubeIdIfPresent(theURL) if youtubeID: isMedia = True # Analyze and process the URL if it is a media file if isMedia: # Process depending on media type if youtubeID: newLinkDict[ "thumb"] = "https://i.ytimg.com/vi/%s/hqdefault.jpg" % youtubeID newLinkDict["mime"] = "youtube" newLinkDict["category"] = "YOUTUBE" else: # Create an empty string buffer and fill it with the media file data streamObject = StringIO.StringIO() streamObject.write( mediaTest.raw.read(decode_content=False)) # Create a file in memory from the media file theFile = InMemoryUploadedFile( streamObject, None, theURL.split("?")[0].split("/")[-1], mediaTest.headers['Content-Type'], streamObject.len, None) # Add the media file to the Amazon S3 bucket and analyze the media file resultPack = addMediaImage( request=request, pageID=pageSlug, theFile=theFile, fileComment=URLComment, PLACEHOLDER_LIST=PLACEHOLDER_LIST, inputMime=mediaTest.headers['Content-Type']) # Update the new link dictionary with info about the file newLinkDict["thumb"] = resultPack["thumb"] newLinkDict["mime"] = resultPack["mime"] newLinkDict["category"] = linkCategorizer( resultPack["url"], resultPack["mime"]) # Render the new media object as an HTML block newLinkHTMLBlock = render_to_string( 'enterlink/ajax_media_gallery_singlet.html', {'theLink': newLinkDict}) return JsonResponse({ "type": "MEDIA", "htmlblock": newLinkHTMLBlock }) except Exception as e: print(str(e)) print( "Is not media, or timeout. Considering link as normal url...") # Find the thumbnail for the new link web page, if it has one from the og:image, schema, etc. theThumbURL = fetchMetaThumbnail(request, theURL, articleObject.slug, articleObject.ipfs_hash_current[:10]) newLinkDict["thumb"] = theThumbURL # Render the new link as an HTML block newLinkHTMLBlock = render_to_string('enterlink/ajax_link_singlet.html', {'theLink': newLinkDict}) return JsonResponse({"type": "NORMAL", "htmlblock": newLinkHTMLBlock})