本文整理汇总了Python中django.utils.six.BytesIO.seek方法的典型用法代码示例。如果您正苦于以下问题:Python BytesIO.seek方法的具体用法?Python BytesIO.seek怎么用?Python BytesIO.seek使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.utils.six.BytesIO
的用法示例。
在下文中一共展示了BytesIO.seek方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_write_dump
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import seek [as 别名]
def test_write_dump(self):
dump_file = BytesIO()
connector = SqliteConnector()
connector._write_dump(dump_file)
dump_file.seek(0)
for line in dump_file:
self.assertTrue(line.strip().endswith(b';'))
示例2: test_comment_file_upload_tmp_file
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import seek [as 别名]
def test_comment_file_upload_tmp_file(self):
"""
Check (tmp) upload files are checked
"""
utils.login(self)
file = BytesIO(
b'%PDF-1.0\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj 2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1'
b'>>endobj 3 0 obj<</Type/Page/MediaBox[0 0 3 3]>>endobj\nxref\n0 4\n0000000000 65535 f\n000000'
b'0010 00000 n\n0000000053 00000 n\n0000000102 00000 n\ntrailer<</Size 4/Root 1 0 R>>\nstartxre'
b'f\n149\n%EOF\n')
files = {
'file': SimpleUploadedFile(
'file_large.pdf', file.read(), content_type='application/pdf'),}
response = self.client.post(
reverse('spirit:comment:file-upload-ajax'),
HTTP_X_REQUESTED_WITH='XMLHttpRequest',
data=files)
res = json.loads(response.content.decode('utf-8'))
file_url = os.path.join(
settings.MEDIA_URL, 'spirit', 'files', str(self.user.pk), "fadcb2389bb2b69b46bc54185de0ae91.pdf"
).replace("\\", "/")
self.assertEqual(res['url'], file_url)
file_path = os.path.join(
settings.MEDIA_ROOT, 'spirit', 'files', str(self.user.pk), "fadcb2389bb2b69b46bc54185de0ae91.pdf"
)
with open(file_path, 'rb') as fh:
file.seek(0)
self.assertEqual(fh.read(), file.read())
shutil.rmtree(settings.MEDIA_ROOT) # cleanup
示例3: test_logslice_api
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import seek [as 别名]
def test_logslice_api(test_repository, webapp, activate_responses, logname,
line_range, gzipped, num_loads):
job = Job.objects.create(repository=test_repository,
guid="12345", project_specific_id=1)
fake_log_url = 'http://www.fakelog.com/log.gz'
JobLog.objects.create(job=job, name=logname,
url=fake_log_url, status=JobLog.PARSED)
lines = ['cheezburger %s' % i for i in range(10)]
# set up a file response
text = "\n".join(lines) + '\n'
content = BytesIO()
if gzipped:
with gzip.GzipFile('none', 'w', fileobj=content) as gz:
gz.write(text)
else:
content.write(text)
content.seek(0)
responses.add(responses.GET, fake_log_url,
body=content.read(),
content_type="text/plain;charset=utf-8", status=200)
# now test it
for i in range(num_loads):
resp = webapp.get(reverse('logslice-list',
kwargs={"project": test_repository.name}) +
'?start_line={}&end_line={}&job_id=1'.format(line_range[0],
line_range[1]))
assert resp.json == [{'index': i + line_range[0], 'text': l + '\n'} for (i, l) in
enumerate(lines[line_range[0]:line_range[1]])]
示例4: create_dump
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import seek [as 别名]
def create_dump(self):
path = self.connection.settings_dict['NAME']
dump = BytesIO()
with open(path, 'rb') as db_file:
copyfileobj(db_file, dump)
dump.seek(0)
return dump
示例5: _process_raster
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import seek [as 别名]
def _process_raster(image, extension):
"""
Processing of raster graphic image.
"""
# File needs to be uploaded and saved temporarily in
# the memory for additional processing using PIL.
thumb_io = BytesIO()
preped_image = scale_and_crop(image, **MARKDOWNX_IMAGE_MAX_SIZE)
preped_image.save(thumb_io, extension)
thumb_io.seek(0, SEEK_END)
return thumb_io
示例6: _read
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import seek [as 别名]
def _read(self, name):
memory_file = BytesIO()
try:
pwd = self._connection.pwd()
self._connection.cwd(os.path.dirname(name))
self._connection.retrbinary("RETR " + os.path.basename(name), memory_file.write)
self._connection.cwd(pwd)
memory_file.seek(0)
return memory_file
except ftplib.all_errors:
raise FTPStorageException("Error reading file %s" % name)
示例7: _compress_content
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import seek [as 别名]
def _compress_content(self, content):
"""Gzip a given string content."""
zbuf = BytesIO()
zfile = GzipFile(mode='wb', compresslevel=6, fileobj=zbuf)
try:
zfile.write(force_bytes(content.read()))
finally:
zfile.close()
zbuf.seek(0)
content.file = zbuf
content.seek(0)
return content
示例8: test_strips_underscore_headers
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import seek [as 别名]
def test_strips_underscore_headers(self):
"""WSGIRequestHandler ignores headers containing underscores.
This follows the lead of nginx and Apache 2.4, and is to avoid
ambiguity between dashes and underscores in mapping to WSGI environ,
which can have security implications.
"""
def test_app(environ, start_response):
"""A WSGI app that just reflects its HTTP environ."""
start_response('200 OK', [])
http_environ_items = sorted(
'%s:%s' % (k, v) for k, v in environ.items()
if k.startswith('HTTP_')
)
yield (','.join(http_environ_items)).encode('utf-8')
rfile = BytesIO()
rfile.write("GET / HTTP/1.0\r\n")
rfile.write("Some-Header: good\r\n")
rfile.write("Some_Header: bad\r\n")
rfile.write("Other_Header: bad\r\n")
rfile.seek(0)
# WSGIRequestHandler closes the output file; we need to make this a
# no-op so we can still read its contents.
class UnclosableBytesIO(BytesIO):
def close(self):
pass
wfile = UnclosableBytesIO()
def makefile(mode, *a, **kw):
if mode == 'rb':
return rfile
elif mode == 'wb':
return wfile
request = Stub(makefile=makefile)
server = Stub(base_environ={}, get_app=lambda: test_app)
# We don't need to check stderr, but we don't want it in test output
old_stderr = sys.stderr
sys.stderr = StringIO()
try:
# instantiating a handler runs the request as side effect
WSGIRequestHandler(request, '192.168.0.2', server)
finally:
sys.stderr = old_stderr
wfile.seek(0)
body = list(wfile.readlines())[-1]
self.assertEqual(body, 'HTTP_SOME_HEADER:good')
示例9: _compress_content
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import seek [as 别名]
def _compress_content(self, content):
"""Gzip a given string content."""
zbuf = BytesIO()
zfile = GzipFile(mode='wb', compresslevel=6, fileobj=zbuf)
try:
zfile.write(force_bytes(content.read()))
finally:
zfile.close()
zbuf.seek(0)
# Boto 2 returned the InMemoryUploadedFile with the file pointer replaced,
# but Boto 3 seems to have issues with that. No need for fp.name in Boto3
# so just returning the BytesIO directly
return zbuf
示例10: render
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import seek [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
示例11: create_image
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import seek [as 别名]
def create_image(storage, filename, size=(100, 100), image_mode='RGB', image_format='PNG'):
"""
Generate a test image, returning the filename that it was saved as.
If ``storage`` is ``None``, the BytesIO containing the image data
will be passed instead.
"""
data = BytesIO()
Image.new(image_mode, size).save(data, image_format)
data.seek(0)
if not storage:
return data
image_file = ContentFile(data.read())
return storage.save(filename, image_file)
示例12: save
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import seek [as 别名]
def save(self, commit=True):
img = scale_and_crop(self.files['image'], **MARKDOWNX_IMAGE_MAX_SIZE)
thumb_io = BytesIO()
img.save(thumb_io, self.files['image'].content_type.split('/')[-1].upper())
file_name = str(self.files['image'])
thumb_io.seek(0, os.SEEK_END)
img = InMemoryUploadedFile(thumb_io, None, file_name, self.files['image'].content_type, thumb_io.tell(), None)
unique_file_name = self.get_unique_file_name(file_name)
full_path = os.path.join(MARKDOWNX_MEDIA_PATH, unique_file_name)
default_storage.save(full_path, img)
return default_storage.url(full_path)
示例13: _compress_content
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import seek [as 别名]
def _compress_content(self, content):
"""Gzip a given string content."""
zbuf = BytesIO()
# The GZIP header has a modification time attribute (see http://www.zlib.org/rfc-gzip.html)
# This means each time a file is compressed it changes even if the other contents don't change
# For S3 this defeats detection of changes using MD5 sums on gzipped files
# Fixing the mtime at 0.0 at compression time avoids this problem
zfile = GzipFile(mode='wb', compresslevel=6, fileobj=zbuf, mtime=0.0)
try:
zfile.write(force_bytes(content.read()))
finally:
zfile.close()
zbuf.seek(0)
content.seek(0)
return zbuf
示例14: _compress_content
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import seek [as 别名]
def _compress_content(self, content):
"""Gzip a given string content."""
content.seek(0)
zbuf = BytesIO()
# The GZIP header has a modification time attribute (see http://www.zlib.org/rfc-gzip.html)
# This means each time a file is compressed it changes even if the other contents don't change
# For S3 this defeats detection of changes using MD5 sums on gzipped files
# Fixing the mtime at 0.0 at compression time avoids this problem
zfile = GzipFile(mode='wb', compresslevel=6, fileobj=zbuf, mtime=0.0)
try:
zfile.write(force_bytes(content.read()))
finally:
zfile.close()
zbuf.seek(0)
# Boto 2 returned the InMemoryUploadedFile with the file pointer replaced,
# but Boto 3 seems to have issues with that. No need for fp.name in Boto3
# so just returning the BytesIO directly
return zbuf
示例15: downloadSheetPage
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import seek [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