本文整理汇总了Python中django.utils.six.BytesIO.close方法的典型用法代码示例。如果您正苦于以下问题:Python BytesIO.close方法的具体用法?Python BytesIO.close怎么用?Python BytesIO.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.utils.six.BytesIO
的用法示例。
在下文中一共展示了BytesIO.close方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: SFTPStorageFile
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import close [as 别名]
class SFTPStorageFile(File):
def __init__(self, name, storage, mode):
self._name = name
self._storage = storage
self._mode = mode
self._is_dirty = False
self.file = BytesIO()
self._is_read = False
@property
def size(self):
if not hasattr(self, '_size'):
self._size = self._storage.size(self._name)
return self._size
def read(self, num_bytes=None):
if not self._is_read:
self.file = self._storage._read(self._name)
self._is_read = True
return self.file.read(num_bytes)
def write(self, content):
if 'w' not in self._mode:
raise AttributeError("File was opened for read-only access.")
self.file = BytesIO(content)
self._is_dirty = True
self._is_read = True
def close(self):
if self._is_dirty:
self._storage._save(self._name, self)
self.file.close()
示例2: render
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import close [as 别名]
def render(data, width, height, force=True, padding=None, overlays=(), overlay_sources=(),
overlay_tints=(), overlay_sizes=None, overlay_positions=None, mask=None, mask_source=None,
center=".5,.5", format=IMAGE_DEFAULT_FORMAT, quality=IMAGE_DEFAULT_QUALITY, fill=None, background=None,
tint=None, pre_rotation=None, post_rotation=None, crop=True, grayscale=False):
"""
Rescale the given image, optionally cropping it to make sure the result image has the specified width and height.
"""
if not isinstance(data, six.string_types):
input_file = BytesIO(data)
else:
input_file = StringIO(data)
img = pil.open(input_file)
if img.mode != "RGBA":
img = img.convert("RGBA")
if width is None:
width = img.size[0]
if height is None:
height = img.size[1]
img = do_rotate(img, pre_rotation)
if crop:
img = resizeCrop(img, width, height, center, force)
else:
img = resizeScale(img, width, height, force)
if grayscale:
img = do_grayscale(img)
do_tint(img, tint)
img = do_fill(img, fill, width, height)
img = do_background(img, background)
do_mask(img, mask, mask_source)
img = do_overlays(img, overlays, overlay_tints, overlay_sources, overlay_sizes, overlay_positions)
img = do_padding(img, padding)
img = do_rotate(img, post_rotation)
tmp = BytesIO()
if not format.upper() in ALPHA_FORMATS:
img = img.convert("RGB")
img.save(tmp, format, quality=quality)
tmp.seek(0)
output_data = tmp.getvalue()
input_file.close()
tmp.close()
return output_data
示例3: downloadSheetPage
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import close [as 别名]
def downloadSheetPage(request, pk):
""" View for dowloading a sheet """
student = getStudent(request.user)
sheet = getSheetInstance(pk) # Get the file
# Check if the user can have access to it (if he is part of the lesson)
if sheet.lesson not in student.classroom.lessons.all():
raise PermissionDenied()
files = sheet.fileSet
if len(files) == 1:
uploadedFile = files[0]
contentType = uploadedFile.contentType
fileName = sheet.name + uploadedFile.extension
data = uploadedFile.file
response = HttpResponse(data.read(), content_type=contentType)
response['Content-Disposition'] = 'attachment; filename="{}"'.format(fileName)
data.close()
else:
contentType = 'application/zip'
fileName = sheet.name + '.zip'
zipStream = BytesIO()
zipFile = ZipFile(zipStream, 'w')
for uploadedFile in files:
filePath = join(settings.MEDIA_ROOT, uploadedFile.file.name)
archiveName = uploadedFile.file.name.replace('sheets/', '').replace('-point-', '.')
zipFile.write(filePath, archiveName)
zipFile.close()
zipStream.seek(0)
response = HttpResponse(zipStream, content_type=contentType)
response['Content-Disposition'] = 'attachment; filename="{}"'.format(fileName)
zipStream.close()
return response
示例4: FTPStorageFile
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import close [as 别名]
class FTPStorageFile(File):
def __init__(self, name, storage, mode):
self.name = name
self._storage = storage
self._mode = mode
self._is_dirty = False
self.file = BytesIO()
self._is_read = False
@property
def size(self):
if not hasattr(self, "_size"):
self._size = self._storage.size(self.name)
return self._size
def readlines(self):
if not self._is_read:
self._storage._start_connection()
self.file = self._storage._read(self.name)
self._is_read = True
return self.file.readlines()
def read(self, num_bytes=None):
if not self._is_read:
self._storage._start_connection()
self.file = self._storage._read(self.name)
self._is_read = True
return self.file.read(num_bytes)
def write(self, content):
if "w" not in self._mode:
raise AttributeError("File was opened for read-only access.")
self.file = BytesIO(content)
self._is_dirty = True
self._is_read = True
def close(self):
if self._is_dirty:
self._storage._start_connection()
self._storage._put_file(self.name, self)
self._storage.disconnect()
self.file.close()
示例5: CouchDBFile
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import close [as 别名]
class CouchDBFile(File):
"""
CouchDBFile - a Django File-like class for CouchDB documents.
"""
def __init__(self, name, storage, mode):
self._name = name
self._storage = storage
self._mode = mode
self._is_dirty = False
try:
self._doc = self._storage.get_document(name)
tmp, ext = os.path.split(name)
if ext:
filename = "content." + ext
else:
filename = "content"
attachment = self._storage.db.get_attachment(self._doc, filename=filename)
self.file = BytesIO(attachment)
except couchdb.client.ResourceNotFound:
if 'r' in self._mode:
raise ValueError("The file cannot be reopened.")
else:
self.file = BytesIO()
self._is_dirty = True
@property
def size(self):
return self._doc['size']
def write(self, content):
if 'w' not in self._mode:
raise AttributeError("File was opened for read-only access.")
self.file = BytesIO(content)
self._is_dirty = True
def close(self):
if self._is_dirty:
self._storage._put_file(self._name, self.file.getvalue())
self.file.close()
示例6: LibCloudFile
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import close [as 别名]
class LibCloudFile(File):
"""File inherited class for libcloud storage objects read and write"""
def __init__(self, name, storage, mode):
self.name = name
self._storage = storage
self._mode = mode
self._is_dirty = False
self._file = None
def _get_file(self):
if self._file is None:
data = self._storage._read(self.name)
self._file = BytesIO(data)
return self._file
def _set_file(self, value):
self._file = value
file = property(_get_file, _set_file)
@property
def size(self):
if not hasattr(self, '_size'):
self._size = self._storage.size(self.name)
return self._size
def read(self, num_bytes=None):
return self.file.read(num_bytes)
def write(self, content):
if 'w' not in self._mode:
raise AttributeError("File was opened for read-only access.")
self.file = BytesIO(content)
self._is_dirty = True
def close(self):
if self._is_dirty:
self._storage._save(self.name, self.file)
self.file.close()
示例7: list
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import close [as 别名]
def list(self, request, project):
"""
GET method implementation for log slicer
Receives a line range and job_id and returns those lines
"""
job_id = request.query_params.get("job_id")
log_name = request.query_params.get("name")
if log_name:
log_names = [log_name]
else:
log_names = ["buildbot_text", "builds-4h"]
format = 'json' if log_name == 'mozlog_json' else 'text'
file = None
start_line = request.query_params.get("start_line")
end_line = request.query_params.get("end_line")
if not start_line or not end_line:
return Response("``start_line`` and ``end_line`` parameters are both required", 400)
try:
start_line = abs(int(start_line))
end_line = abs(int(end_line))
except ValueError:
return Response("parameters could not be converted to integers", 400)
if start_line >= end_line:
return Response("``end_line`` must be larger than ``start_line``", 400)
try:
job = Job.objects.get(repository__name=project,
project_specific_id=job_id)
except Job.DoesNotExist:
return Response("Job does not exist", 404)
try:
url = JobLog.objects.filter(
job=job, name__in=log_names)[0:1].values_list('url',
flat=True)[0]
except JobLog.DoesNotExist:
return Response("Job log does not exist", 404)
try:
file = filesystem.get(url)
if not file:
r = make_request(url)
try:
file = gzip.GzipFile(fileobj=BytesIO(r.content))
# read 16 bytes, just to make sure the file is gzipped
file.read(16)
file.seek(0)
filesystem.set(url, file.fileobj)
except IOError:
# file is not gzipped, but we should still store / read
# it as such, to save space
file = BytesIO(r.content)
gz_file_content = BytesIO()
with gzip.GzipFile('none', 'w', fileobj=gz_file_content) as gz:
gz.write(r.content)
filesystem.set(url, gz_file_content)
else:
file = gzip.GzipFile(fileobj=file)
lines = []
for i, line in enumerate(file):
if i < start_line:
continue
elif i >= end_line:
break
if format == 'json':
lines.append({"data": json.loads(line), "index": i})
else:
lines.append({"text": line, "index": i})
return Response(lines)
finally:
if file:
file.close()