本文整理匯總了Python中django.utils.six.BytesIO方法的典型用法代碼示例。如果您正苦於以下問題:Python six.BytesIO方法的具體用法?Python six.BytesIO怎麽用?Python six.BytesIO使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.utils.six
的用法示例。
在下文中一共展示了six.BytesIO方法的11個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _load_stream
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import BytesIO [as 別名]
def _load_stream(self):
"""
Return the content body of the request, as a stream.
"""
meta = self._request.META
try:
content_length = int(
meta.get('CONTENT_LENGTH', meta.get('HTTP_CONTENT_LENGTH', 0))
)
except (ValueError, TypeError):
content_length = 0
if content_length == 0:
self._stream = None
elif not self._request._read_started:
self._stream = self._request
else:
self._stream = six.BytesIO(self.body)
示例2: _load_stream
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import BytesIO [as 別名]
def _load_stream(self):
"""
Return the content body of the request, as a stream.
"""
meta = self._request.META
try:
content_length = int(
meta.get('CONTENT_LENGTH', meta.get('HTTP_CONTENT_LENGTH', 0))
)
except (ValueError, TypeError):
content_length = 0
if content_length == 0:
self._stream = None
elif hasattr(self._request, 'read'):
self._stream = self._request
else:
self._stream = six.BytesIO(self.raw_post_data)
示例3: parse_json_response
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import BytesIO [as 別名]
def parse_json_response(json):
""" parse the json response """
rendered = JSONRenderer().render(json)
stream = BytesIO(rendered)
return JSONParser().parse(stream)
示例4: generate_qrcode
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import BytesIO [as 別名]
def generate_qrcode(request, data):
img = qrcode.make(data)
buf = BytesIO()
img.save(buf)
image_stream = buf.getvalue()
response = HttpResponse(image_stream, content_type="image/png")
return response
示例5: as_bytes
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import BytesIO [as 別名]
def as_bytes(self, unixfrom=False, linesep='\n'):
"""Return the entire formatted message as bytes.
Optional `unixfrom' when True, means include the Unix From_ envelope
header.
This overrides the default as_bytes() implementation to not mangle
lines that begin with 'From '. See bug #13433 for details.
"""
fp = six.BytesIO()
g = generator.BytesGenerator(fp, mangle_from_=False)
g.flatten(self, unixfrom=unixfrom, linesep=linesep)
return fp.getvalue()
示例6: create_image
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import BytesIO [as 別名]
def create_image(filename, size=(48, 48), image_mode='RGB', image_format='png'):
"""
Generate a test image, returning the filename that it was saved as.
"""
data = BytesIO()
Image.new(image_mode, size).save(data, image_format)
data.seek(0)
return data
# Classes #####################################################################
示例7: html_to_pdf
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import BytesIO [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()
示例8: from_native
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import BytesIO [as 別名]
def from_native(self, data):
"""
Checks that the file-upload field data contains a valid image (GIF, JPG,
PNG, possibly others -- whatever the Python Imaging Library supports).
"""
f = super(ImageField, self).from_native(data)
if f is None:
return None
from api.compat import Image
assert Image is not None, 'Either Pillow or PIL must be installed for ImageField support.'
# We need to get a file object for PIL. We might have a path or we might
# have to read the data into memory.
if hasattr(data, 'temporary_file_path'):
_file = data.temporary_file_path()
else:
if hasattr(data, 'read'):
_file = six.BytesIO(data.read())
else:
_file = six.BytesIO(data['content'])
try:
# load() could spot a truncated JPEG, but it loads the entire
# image in memory, which is a DoS vector. See #3848 and #18520.
# verify() must be called immediately after the constructor.
Image.open(_file).verify()
except ImportError:
# Under PyPy, it is possible to import PIL. However, the underlying
# _imaging C module isn't available, so an ImportError will be
# raised. Catch and re-raise.
raise
except Exception: # Python Imaging Library doesn't recognize it as an image
raise ValidationError(self.error_messages['invalid_image'])
if hasattr(f, 'seek') and callable(f.seek):
f.seek(0)
return f
示例9: __init__
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import BytesIO [as 別名]
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
示例10: write
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import BytesIO [as 別名]
def write(self, content):
if 'w' not in self._mode and 'a' not in self._mode:
raise AttributeError("File was opened for read-only access.")
try:
self.file = BytesIO(bytes(content,encoding = "utf8"))
except TypeError:
self.file = BytesIO(bytes(content))
self._is_dirty = True
self._is_read = True
示例11: create
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import BytesIO [as 別名]
def create(self, request, *args, **kwargs):
if request.method.upper() == 'HEAD':
return Response(headers=self.get_openrosa_headers(request),
status=status.HTTP_204_NO_CONTENT,)
try:
instance = ModelHelper().upload_submission_data(request)
except InvalidXMLSubmission as e:
logger.exception(str(e))
return self._sendErrorResponse(request, e,
status.HTTP_400_BAD_REQUEST)
except PermissionDenied as e:
return self._sendErrorResponse(request, e,
status.HTTP_403_FORBIDDEN)
# If an already existing XFormSummission is sent back
# don't create another.
if type(instance) == XFormSubmission:
return Response(
headers=self.get_openrosa_headers(request),
status=status.HTTP_201_CREATED,
content_type=self.DEFAULT_CONTENT_TYPE
)
instance, parties, locations, tenure_relationships = instance
serializer = XFormSubmissionSerializer(instance)
json = JSONRenderer().render(serializer.data)
stream = BytesIO(json)
data = JSONParser().parse(stream)
serializer = XFormSubmissionSerializer(data=data)
# Every possible error that would make the serializer not valid
# has already been checked for, so no failsafe is necessary.
if serializer.is_valid():
data = serializer.save()
data.parties.add(*parties)
data.spatial_units.add(*locations)
data.tenure_relationships.add(*tenure_relationships)
success_msg = _("Form was Successfully Received")
return self._formatMessageResponse(
request,
success_msg,
status.HTTP_201_CREATED
)