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