本文整理汇总了Python中django.core.files.uploadedfile.InMemoryUploadedFile类的典型用法代码示例。如果您正苦于以下问题:Python InMemoryUploadedFile类的具体用法?Python InMemoryUploadedFile怎么用?Python InMemoryUploadedFile使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了InMemoryUploadedFile类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _update_image
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
示例2: get_shp_from_zip
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
示例3: create_thumbnail
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
示例4: resize_image
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
示例5: create_thumbnail
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)
示例6: get_temporary_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
示例7: create_thumbnail
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)
示例8: test_create_event_from_dict_with_all_fields
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
示例9: test_create_event_with_image
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'[email protected]',
'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'[email protected]'
}
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
示例10: save
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)
示例11: get_temporary_xml_file
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
示例12: get_file
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
示例13: test_create_event_with_image
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"[email protected]",
"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"[email protected]",
}
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
示例14: test_parse
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)
示例15: get_temporary_text_file
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