Python django.utils.six.BytesIO() Examples
The following are 12
code examples of django.utils.six.BytesIO().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.utils.six
, or try the search function
.
Example #1
Source File: utils.py From django-rest-messaging with ISC License | 7 votes |
def parse_json_response(json): """ parse the json response """ rendered = JSONRenderer().render(json) stream = BytesIO(rendered) return JSONParser().parse(stream)
Example #2
Source File: request.py From Dailyfresh-B2C with Apache License 2.0 | 6 votes |
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)
Example #3
Source File: request.py From esdc-ce with Apache License 2.0 | 6 votes |
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)
Example #4
Source File: views.py From ran-django-template with GNU General Public License v3.0 | 5 votes |
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
Example #5
Source File: message.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
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()
Example #6
Source File: utils.py From opencraft with GNU Affero General Public License v3.0 | 5 votes |
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 #####################################################################
Example #7
Source File: rendering.py From django-easy-pdf with MIT License | 5 votes |
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()
Example #8
Source File: fields.py From esdc-ce with Apache License 2.0 | 5 votes |
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
Example #9
Source File: views.py From Face-Recognition-System with MIT License | 5 votes |
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
Example #10
Source File: sftpstorage.py From webterminal with GNU General Public License v3.0 | 5 votes |
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
Example #11
Source File: sftpstorage.py From webterminal with GNU General Public License v3.0 | 5 votes |
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
Example #12
Source File: api.py From cadasta-platform with GNU Affero General Public License v3.0 | 4 votes |
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 )