本文整理汇总了Python中django.utils.six.BytesIO类的典型用法代码示例。如果您正苦于以下问题:Python BytesIO类的具体用法?Python BytesIO怎么用?Python BytesIO使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了BytesIO类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: printer_label
def printer_label(sample):
"""Generate the PDF of a sample for the label printer.
:param sample: the sample the label of which should be generated
:type sample: `samples.models.Sample`
:return:
the PDF as a byte stream
:rtype: str
"""
output = BytesIO()
text = sample.name
c = canvas.Canvas(output, pagesize=(width, height))
c.setAuthor("JuliaBase samples database")
c.setTitle(text)
c.setSubject("Label of {0} for the label printer".format(text))
try:
print_line(c, 0, fontsize, text)
except ExcessException:
first, second = best_split(text)
print_line(c, height / 2, fontsize_half, first, force=True)
print_line(c, 0, fontsize_half, second, force=True)
c.drawImage(ImageReader("http://chart.googleapis.com/chart?chs=116x116&cht=qr&chl={0}&chld=H|1".format(sample.id)),
width - height, 0, height, height)
c.showPage()
c.save()
return output.getvalue()
示例2: html_to_pdf
def html_to_pdf(content, encoding="utf-8",
link_callback=fetch_resources, **kwargs):
"""
Converts html ``content`` into PDF document.
:param unicode content: html content
:returns: PDF content
:rtype: :class:`bytes`
:raises: :exc:`~easy_pdf.exceptions.PDFRenderingError`
"""
src = BytesIO(content.encode(encoding))
dest = BytesIO()
pdf = pisa.pisaDocument(src, dest, encoding=encoding,
link_callback=link_callback, **kwargs)
if pdf.err:
logger.error("Error rendering PDF document")
for entry in pdf.log:
if entry[0] == xhtml2pdf.default.PML_ERROR:
logger_x2p.error("line %s, msg: %s, fragment: %s", entry[1], entry[2], entry[3])
raise PDFRenderingError("Errors rendering PDF", content=content, log=pdf.log)
if pdf.warn:
for entry in pdf.log:
if entry[0] == xhtml2pdf.default.PML_WARNING:
logger_x2p.warning("line %s, msg: %s, fragment: %s", entry[1], entry[2], entry[3])
return dest.getvalue()
示例3: test_document_version_download_user_view
def test_document_version_download_user_view(self):
self.login(
username=TEST_USER_USERNAME, password=TEST_USER_PASSWORD
)
self.assertEqual(Document.objects.count(), 1)
response = self.post(
'documents:document_version_download', args=(
self.document.latest_version.pk,
)
)
self.assertEqual(response.status_code, 302)
self.role.permissions.add(
permission_document_download.stored_permission
)
response = self.post(
'documents:document_version_download', args=(
self.document.latest_version.pk,
)
)
self.assertEqual(response.status_code, 200)
buf = BytesIO()
buf.write(response.content)
self.assertEqual(
HASH_FUNCTION(buf.getvalue()), TEST_SMALL_DOCUMENT_CHECKSUM
)
del(buf)
示例4: package_foirequest
def package_foirequest(foirequest):
zfile_obj = BytesIO()
with override(settings.LANGUAGE_CODE):
zfile = zipfile.ZipFile(zfile_obj, 'w')
last_date = None
date_count = 1
for message in foirequest.messages:
current_date = message.timestamp.date()
date_prefix = current_date.isoformat()
if current_date == last_date:
date_count += 1
else:
date_count = 1
date_prefix += '_%d' % date_count
last_date = current_date
att_queryset = message.foiattachment_set.filter(
is_redacted=False,
is_converted=False
)
if message.is_response:
filename = '%s_%s.txt' % (date_prefix, ugettext('publicbody'))
else:
filename = '%s_%s.txt' % (date_prefix, ugettext('requester'))
zfile.writestr(filename, message.get_formated(att_queryset).encode('utf-8'))
for attachment in att_queryset:
if not attachment.file:
continue
filename = '%s-%s' % (date_prefix, attachment.name)
zfile.write(attachment.file.path, arcname=filename)
zfile.close()
return zfile_obj.getvalue()
示例5: test_comment_image_upload
def test_comment_image_upload(self):
"""
comment image upload
"""
utils.login(self)
img = BytesIO(
b'GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00'
b'\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;')
files = {'image': SimpleUploadedFile(
'image.gif', img.read(), content_type='image/gif'), }
response = self.client.post(
reverse('spirit:comment:image-upload-ajax'),
HTTP_X_REQUESTED_WITH='XMLHttpRequest',
data=files)
res = json.loads(response.content.decode('utf-8'))
image_url = os.path.join(
settings.MEDIA_URL, 'spirit', 'images', str(self.user.pk),
"bf21c3043d749d5598366c26e7e4ab44.gif"
).replace("\\", "/")
self.assertEqual(res['url'], image_url)
image_path = os.path.join(
settings.MEDIA_ROOT, 'spirit', 'images', str(self.user.pk),
"bf21c3043d749d5598366c26e7e4ab44.gif"
)
self.assertTrue(os.path.isfile(image_path))
shutil.rmtree(settings.MEDIA_ROOT) # cleanup
示例6: test_write_dump
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';'))
示例7: test_comment_file_upload_unique
def test_comment_file_upload_unique(self):
user_files_parts = ('spirit', 'files', str(self.user.pk))
user_files_base = os.path.join(*user_files_parts)
user_media = os.path.join(settings.MEDIA_ROOT, user_files_base)
self.assertFalse(os.path.isdir(user_media))
utils.login(self)
pdf = 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')
file_name = 'foo.pdf'
file = SimpleUploadedFile(
file_name, pdf.read(), content_type='application/pdf')
response = self.client.post(
reverse('spirit:comment:file-upload-ajax'),
HTTP_X_REQUESTED_WITH='XMLHttpRequest',
data={'file': file})
res = json.loads(response.content.decode('utf-8'))
self.assertTrue(os.path.isdir(user_media))
url_parts = res['url'].split('/')
self.assertEqual(
url_parts[:-2],
(settings.MEDIA_URL + '/'.join(user_files_parts)).split('/'))
self.assertEqual(len(url_parts[-2]), 32) # uuid
self.assertEqual(url_parts[-1], file_name)
self.assertEqual(len(os.listdir(user_media)), 1)
self.assertTrue(os.path.join(
user_media, os.listdir(user_media)[0], file_name))
shutil.rmtree(settings.MEDIA_ROOT) # cleanup
示例8: test_comment_image_upload
def test_comment_image_upload(self):
"""
Image upload
"""
content = (
b"GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00"
b"\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;"
)
img = BytesIO(content)
files = {"image": SimpleUploadedFile("image.gif", img.read(), content_type="image/gif")}
form = CommentImageForm(user=self.user, data={}, files=files)
self.assertTrue(form.is_valid())
image = form.save()
self.assertEqual(image.name, "bf21c3043d749d5598366c26e7e4ab44.gif")
image_url = os.path.join(settings.MEDIA_URL, "spirit", "images", str(self.user.pk), image.name).replace(
"\\", "/"
)
self.assertEqual(image.url, image_url)
image_path = os.path.join(settings.MEDIA_ROOT, "spirit", "images", str(self.user.pk), image.name)
self.assertTrue(os.path.isfile(image_path))
with open(image_path, "rb") as fh:
self.assertEqual(fh.read(), content)
os.remove(image_path)
示例9: test_comment_file_upload_unique_no_duplication
def test_comment_file_upload_unique_no_duplication(self):
utils.login(self)
pdf = 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')
file_name = 'foo.pdf'
file = SimpleUploadedFile(
file_name, pdf.read(), content_type='application/pdf')
response = self.client.post(
reverse('spirit:comment:file-upload-ajax'),
HTTP_X_REQUESTED_WITH='XMLHttpRequest',
data={'file': file})
res = json.loads(response.content.decode('utf-8'))
first_url = res['url']
utils.cache_clear()
file.seek(0)
response = self.client.post(
reverse('spirit:comment:file-upload-ajax'),
HTTP_X_REQUESTED_WITH='XMLHttpRequest',
data={'file': file})
res = json.loads(response.content.decode('utf-8'))
second_url = res['url']
self.assertNotEqual(first_url, second_url)
示例10: test_comment_file_upload_tmp_file
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
示例11: test_comment_image_upload_unique_no_duplication
def test_comment_image_upload_unique_no_duplication(self):
utils.login(self)
img = BytesIO(
b'GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00'
b'\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;')
image_name = 'foo_image.gif'
file = SimpleUploadedFile(
image_name, img.read(), content_type='image/gif')
response = self.client.post(
reverse('spirit:comment:image-upload-ajax'),
HTTP_X_REQUESTED_WITH='XMLHttpRequest',
data={'image': file})
res = json.loads(response.content.decode('utf-8'))
first_url = res['url']
utils.cache_clear()
file.seek(0)
response = self.client.post(
reverse('spirit:comment:image-upload-ajax'),
HTTP_X_REQUESTED_WITH='XMLHttpRequest',
data={'image': file})
res = json.loads(response.content.decode('utf-8'))
second_url = res['url']
self.assertNotEqual(first_url, second_url)
示例12: test_comment_image_upload_unique
def test_comment_image_upload_unique(self):
user_images_parts = ('spirit', 'images', str(self.user.pk))
user_images_base = os.path.join(*user_images_parts)
user_media = os.path.join(settings.MEDIA_ROOT, user_images_base)
self.assertFalse(os.path.isdir(user_media))
utils.login(self)
img = BytesIO(
b'GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00'
b'\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;')
image_name = 'foo_image.gif'
file = SimpleUploadedFile(
image_name, img.read(), content_type='image/gif')
response = self.client.post(
reverse('spirit:comment:image-upload-ajax'),
HTTP_X_REQUESTED_WITH='XMLHttpRequest',
data={'image': file})
res = json.loads(response.content.decode('utf-8'))
self.assertTrue(os.path.isdir(user_media))
url_parts = res['url'].split('/')
self.assertEqual(
url_parts[:-2],
(settings.MEDIA_URL + '/'.join(user_images_parts)).split('/'))
self.assertEqual(len(url_parts[-2]), 32) # uuid
self.assertEqual(url_parts[-1], image_name)
self.assertEqual(len(os.listdir(user_media)), 1)
self.assertTrue(os.path.join(
user_media, os.listdir(user_media)[0], image_name))
shutil.rmtree(settings.MEDIA_ROOT) # cleanup
示例13: SFTPStorageFile
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()
示例14: create_dump
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
示例15: test_comment_image_upload_invalid
def test_comment_image_upload_invalid(self):
"""
Image upload, bad image
"""
img = BytesIO(b"bad\x00;")
files = {"image": SimpleUploadedFile("image.gif", img.read(), content_type="image/gif")}
form = CommentImageForm(data={}, files=files)
self.assertFalse(form.is_valid())