本文整理汇总了Python中django.utils.six.BytesIO.getvalue方法的典型用法代码示例。如果您正苦于以下问题:Python BytesIO.getvalue方法的具体用法?Python BytesIO.getvalue怎么用?Python BytesIO.getvalue使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.utils.six.BytesIO
的用法示例。
在下文中一共展示了BytesIO.getvalue方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: package_foirequest
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import getvalue [as 别名]
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()
示例2: html_to_pdf
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import getvalue [as 别名]
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: printer_label
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import getvalue [as 别名]
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()
示例4: test_document_version_download_user_view
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import getvalue [as 别名]
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)
示例5: test_cmd_output
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import getvalue [as 别名]
def test_cmd_output(self):
""" test command output"""
output = BytesIO()
errout = BytesIO()
call_command('modscount',
stdout=output,
stderr=errout)
for model in get_models():
err_str = 'error: There are {} objects in {} model'.format(
model.objects.count(),
model.__name__
)
out_str = 'There are {} objects in {} model'.format(
model.objects.count(),
model.__name__
)
self.assertIn(err_str, errout.getvalue())
self.assertIn(out_str, output.getvalue())
示例6: get_qrcode
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import getvalue [as 别名]
def get_qrcode(request, content):
'''返回字符串编码后的二维码图片'''
# 加入节点信息等级判断
ss_img = qrcode.make(content)
buf = BytesIO()
ss_img.save(buf)
image_stream = buf.getvalue()
# 构造图片reponse
response = HttpResponse(image_stream, content_type="image/png")
return response
示例7: resize_image
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import getvalue [as 别名]
def resize_image(self, data, size):
""" Resizes the given image to fit inside a box of the given size. """
from machina.core.compat import PILImage as Image
image = Image.open(BytesIO(data))
# Resize!
image.thumbnail(size, Image.ANTIALIAS)
string = BytesIO()
image.save(string, format='PNG')
return string.getvalue()
示例8: test_document_version_download
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import getvalue [as 别名]
def test_document_version_download(self):
with open(TEST_SMALL_DOCUMENT_PATH) as file_object:
document = self.document_type.new_document(file_object=File(file_object))
response = self.client.get(reverse("rest_api:documentversion-download", args=(document.latest_version.pk,)))
buf = BytesIO()
buf.write(response.content)
self.assertEqual(HASH_FUNCTION(buf.getvalue()), TEST_SMALL_DOCUMENT_CHECKSUM)
del (buf)
示例9: render
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import getvalue [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
示例10: generate_thumb
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import getvalue [as 别名]
def generate_thumb(img, thumb_size, extension, image_size=None):
img.seek(0) # see http://code.djangoproject.com/ticket/8222 for details
image = Image.open(img)
# Convert to RGB if necessary
if image.mode not in ("L", "RGB", "RGBA"):
image = image.convert("RGB")
# get size
thumb_w, thumb_h = thumb_size
if not thumb_h:
if not image_size:
image_size = image.size
xsize, ysize = image_size
thumb_h = float(thumb_w) / xsize * ysize
elif not thumb_w:
if not image_size:
image_size = image.size
xsize, ysize = image_size
thumb_w = float(thumb_h) / ysize * xsize
# If you want to generate a square thumbnail
if thumb_w == thumb_h:
# quad
if not image_size:
image_size = image.size
xsize, ysize = image_size
# get minimum size
minsize = min(xsize, ysize)
# largest square possible in the image
xnewsize = (xsize - minsize) / 2
ynewsize = (ysize - minsize) / 2
# crop it
image2 = image.crop((xnewsize, ynewsize, xsize - xnewsize, ysize - ynewsize))
# load is necessary after crop
image2.load()
# thumbnail of the cropped image (with ANTIALIAS to make it look better)
image2.thumbnail((thumb_w, thumb_h), Image.ANTIALIAS)
else:
# not quad
image2 = image
image2.thumbnail((thumb_w, thumb_h), Image.ANTIALIAS)
io = BytesIO()
# PNG and GIF are the same, JPG is JPEG
if extension.upper() == "JPG":
extension = "JPEG"
image2.save(io, extension)
return ContentFile(io.getvalue()), (thumb_w, thumb_h)
示例11: generate_totp_config_svg
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import getvalue [as 别名]
def generate_totp_config_svg(device, issuer, label):
params = {
'secret': b32encode(device.bin_key).decode('utf-8'),
'algorithm': 'SHA1',
'digits': device.digits,
'period': device.step,
'issuer': issuer,
}
otpauth_url = 'otpauth://totp/{label}?{query}'.format(
label=quote(label),
query=urlencode(params),
)
img = qrcode.make(otpauth_url, image_factory=SvgPathImage)
io = BytesIO()
img.save(io)
return io.getvalue()
示例12: get_test_image_data
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import getvalue [as 别名]
def get_test_image_data(size=(32, 32), color=(250, 250, 210), format="JPEG"):
"""
Get binary image data with the given specs.
:param size: Size tuple
:type size: tuple[int, int]
:param color: RGB color triple
:type color: tuple[int, int, int]
:param format: PIL image format specifier
:type format: str
:return: Binary data
:rtype: bytes
"""
img = Image.new(mode="RGB", size=size)
img.paste(color)
sio = BytesIO()
img.save(sio, format=format, quality=75)
return sio.getvalue()
示例13: get_ss_qrcode
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import getvalue [as 别名]
def get_ss_qrcode(request, node_id):
'''返回节点配置信息的ss二维码'''
# 获取用户对象
ss_user = request.user.ss_user
user = request.user
# 获取节点对象
node = Node.objects.get(node_id=node_id)
# 加入节点信息等级判断
if user.level < node.level:
return HttpResponse('哟小伙子,可以啊!但是投机取巧是不对的哦!')
ss_link = node.get_ss_link(ss_user)
ss_img = qrcode.make(ss_link)
buf = BytesIO()
ss_img.save(buf)
image_stream = buf.getvalue()
# 构造图片reponse
response = HttpResponse(image_stream, content_type="image/png")
return response
示例14: parse_attachment
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import getvalue [as 别名]
def parse_attachment(self, message_part):
content_disposition = message_part.get("Content-Disposition", None)
if content_disposition:
dispo_type, dispo_dict = self.parse_dispositions(content_disposition)
if dispo_type == "attachment" or (dispo_type == 'inline' and
'filename' in dispo_dict):
content_type = message_part.get("Content-Type", None)
file_data = message_part.get_payload(decode=True)
if file_data is None:
payloads = message_part.get_payload()
file_data = '\n\n'.join([p.as_string() for p in payloads])
try:
file_data = file_data.encode('utf-8')
except:
pass
attachment = BytesIO(file_data)
attachment.content_type = message_part.get_content_type()
attachment.size = len(file_data)
attachment.name = None
attachment.create_date = None
attachment.mod_date = None
attachment.read_date = None
if "filename" in dispo_dict:
attachment.name = dispo_dict['filename']
if content_type:
_, content_dict = self.parse_dispositions(content_type)
if 'name' in content_dict:
attachment.name = content_dict['name']
if attachment.name is None and content_type == 'message/rfc822':
p = Parser()
msgobj = p.parse(BytesIO(attachment.getvalue()))
subject = self.parse_header_field(msgobj['Subject'])
if subject:
attachment.name = '%s.eml' % subject[:45]
if "create-date" in dispo_dict:
attachment.create_date = dispo_dict['create-date'] # TODO: datetime
if "modification-date" in dispo_dict:
attachment.mod_date = dispo_dict['modification-date'] # TODO: datetime
if "read-date" in dispo_dict:
attachment.read_date = dispo_dict['read-date'] # TODO: datetime
return attachment
return None
示例15: CouchDBFile
# 需要导入模块: from django.utils.six import BytesIO [as 别名]
# 或者: from django.utils.six.BytesIO import getvalue [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()