本文整理汇总了Python中django.core.files.uploadedfile.UploadedFile.seek方法的典型用法代码示例。如果您正苦于以下问题:Python UploadedFile.seek方法的具体用法?Python UploadedFile.seek怎么用?Python UploadedFile.seek使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.core.files.uploadedfile.UploadedFile
的用法示例。
在下文中一共展示了UploadedFile.seek方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: document_validator
# 需要导入模块: from django.core.files.uploadedfile import UploadedFile [as 别名]
# 或者: from django.core.files.uploadedfile.UploadedFile import seek [as 别名]
def document_validator(filepath, ex_first_row, ex_first_col):
try:
with open(os.path.join(settings.MEDIA_ROOT, filepath), 'r') as f:
file = UploadedFile(f)
dialect = csv.Sniffer().sniff(file.readline(), delimiters=[';', ',', '\t'])
mimetype = magic.from_buffer(file.readline(), mime=True)
file.seek(0)
reader = csv.reader(file, dialect)
temp_list = []
for line in iter(reader):
if reader.line_num == 1:
# save first row
temp_list.append(line)
# save last row
temp_list.append(line)
print ex_first_row
if not ex_first_row:
print "Ciao"
# check char in first row and first col
if not ex_first_row and not float(temp_list[0][-1]):
print 'Hola'
raise ValueError
if not ex_first_col and not float(temp_list[-1][0]):
print 'Hello'
raise ValueError
ncol = (len(temp_list[0]) - 1) if ex_first_col else len(temp_list[0])
nrow = (reader.line_num - 1) if ex_first_col else reader.line_num
if nrow <= 2:
print 'Hey'
raise ValueError
is_cubic = True if (ncol == nrow) else False
return_value = {'is_valid': True, 'nrow': nrow, 'ncol': ncol, 'separator': dialect.delimiter,
'mimetype': mimetype, 'is_cubic': is_cubic}
except csv.Error:
print "Csv"
return_value = {'is_valid': False}
file = None
except Exception:
return_value = {'is_valid': False}
print "Exc"
file = None
except ValueError:
return_value = {'is_valid': False}
print "Value"
file = file
return return_value, file
示例2: smart_load_from_upload
# 需要导入模块: from django.core.files.uploadedfile import UploadedFile [as 别名]
# 或者: from django.core.files.uploadedfile.UploadedFile import seek [as 别名]
def smart_load_from_upload(classname: str, f: UploadedFile) -> BasePriceList:
'''
Attempt to intelligently load the given Django UploadedFile,
interpreting it as a price list for the given schedule class name.
If interpreting it under the preferred schedule results in either
a ValidationError or no valid rows, attempts will be made to
re-interpret the file under different schedules. The first found
that yields better interpretations of the data will be returned.
If no better matches are found, the original result or exception
(from interpreting the data under the preferred price list) will
be returned.
'''
original_error = None
pricelist: Optional[BasePriceList] = None
try:
pricelist = load_from_upload(classname, f)
except ValidationError as e:
original_error = e
if original_error or (pricelist and not pricelist.valid_rows):
# See if any of our other registered schedules can make better sense
# of it.
next_best_pricelist = None
for fallback, _ in CHOICES:
if fallback == classname:
continue
try:
f.seek(0)
next_best_pricelist = load_from_upload(fallback, f)
if next_best_pricelist.valid_rows:
pricelist = next_best_pricelist
break
except ValidationError as e:
pass
if pricelist is None:
default_error = ValidationError('Unrecognized price list!')
raise original_error or default_error
return pricelist
示例3: get_minecraft_avatar
# 需要导入模块: from django.core.files.uploadedfile import UploadedFile [as 别名]
# 或者: from django.core.files.uploadedfile.UploadedFile import seek [as 别名]
def get_minecraft_avatar(minecraft_user, geometry_string, force=True):
"""
This method uses the sorl-thumbnail cache backend to
prevent images from being downloaded every time.
It requires an username.
"""
avatar_file = UploadedFile(
file=StringIO(),
name='%s/%s.png' % (settings.MEDIA_ROOT, tokey(minecraft_user)))
try:
# Check if the avatar is cached
thumbnail = get_thumbnail(
avatar_file, '100x100', quality=100, format='PNG')
except IOError:
download_thumbnail = True
else:
is_dummy = not hasattr(thumbnail, 'storage')
if not is_dummy and not thumbnail.storage.exists(thumbnail.name):
# It seems we have the avatar on cache (kvstore)
# but it's not present on the storage
download_thumbnail = True
# Force remove thumbnail from kvstore
sorl_default.kvstore.delete(thumbnail)
# Log
logger.warning('Avatar cache mismatch: %s (resetting)' % (
minecraft_user,))
else:
logger.debug('Avatar fetched from cache: %s' % minecraft_user)
download_thumbnail = False
if download_thumbnail:
logger.debug('Downloading avatar: %s' % minecraft_user)
# Otherwise download avatar
thumbnail = None
try:
skin_bin = requests.get(
'http://s3.amazonaws.com/MinecraftSkins/%s.png' % (
minecraft_user
)
).content
except ConnectionError:
return None
try:
skin = Image.open(StringIO(skin_bin)).convert('RGBA')
except IOError:
# Image not found or some permission error with S3
if minecraft_user != 'char':
if not force:
return None
# Return default user avatar
return settings.STATIC_URL + settings.DEFAULT_USER_AVATAR
else:
face = skin.crop((8, 8, 16, 16))
accessories = skin.crop((40, 8, 48, 16))
r, g, b, a = accessories.split()
accessories = Image.merge('RGB', (r, g, b))
mask = Image.merge('L', (a,))
face.paste(accessories, (0, 0), mask)
avatar = face.resize((135, 135))
avatar.save(avatar_file, 'PNG')
avatar_file.seek(0)
# Save through sorl backend
thumbnail = get_thumbnail(avatar_file, '100x100',
quality=100, format='PNG')
# Use the cached file
return get_thumbnail(thumbnail, geometry_string,
quality=100, format='PNG').url