def save(self): """ Save the image to the cache if provided and not cached yet. """ if self.cache and not self.is_cached: image_str = BytesIO() self.pil.save(image_str, ext_to_format(self.cached_name)) self.cache.set(self.cached_name, image_str.getvalue()) image_str.close()
def render(self): """ Renders the file content """ if self.is_cached: return self.cache.get(self.cached_name) else: image_str = BytesIO() self.pil.save(image_str, ext_to_format(self.cached_name)) return image_str.getvalue()
def render(path: str, params: dict): template = get_template(path) html = template.render(params) response = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), response) if not pdf.err: return HttpResponse(response.getvalue(), content_type='application/pdf') else: return HttpResponse("Error Rendering PDF", status=400) @staticmethod def test()
def send_beacon(beacon): # Compress Payload out = io.BytesIO() with gzip.GzipFile(fileobj=out, mode='w') as f: json_str = json.dumps(beacon) json_bytes = json_str.encode('utf-8') f.write(json_bytes) if args.verbose: print('beacon: {}'.format(beacon)) r = requests.post( sendBeaconUrl, headers={ 'Content-Type': 'application/json', 'Accept': 'application/json', 'Content-Encoding': 'gzip' }, data=out.getvalue() ) print('resp code: {}'.format(r.status_code)) if args.verbose: print('send url: {}'.format(sendBeaconUrl)) print('resp headers: {}'.format(r.headers))
def test01_no_links(self): xml = run_resync( ['--resourcelist', 'http://example.org/t', 'tests/testdata/dir1']) rl = ResourceList() rl.parse(fh=io.BytesIO(xml)) self.assertEqual(len(rl), 2) self.assertEqual(rl.link('describedby'), None)
def fig2base64(fig, format='png'): """ Parameters ---------- fig : matplotlib.fig.Figure format : str Eg. png, jpg Returns ------- """ try: import BytesIO as io except ImportError: # from io import StringIO as StringIO import io import base64 bytes_io = io.BytesIO() fig.savefig(bytes_io, format=format) bytes_io.seek(0) s = bytes_io.read() res = base64.b64encode(s) return res
def __init__(self, request, preamble): preamble.headers['Vary'] = preamble.headers.get('Vary', '') + ',Accept-Encoding' self._accepted = 'gzip' in request.headers.get('Accept-Encoding', '').replace(' ','').split(',') if self._accepted: self._value = BytesIO() self._file = GzipFile(mode='wb', fileobj=self._value) preamble.headers['Content-Encoding'] = preamble.headers.get('Content-Encoding', '') + ',gzip'
def as_xml(self): """XML representation of the error to be used in HTTP response. This XML format follows the IIIF Image API v1.0 specification, see <http://iiif.io/api/image/1.0/#error> """ # Build tree spacing = ("\n" if (self.pretty_xml) else "") root = Element('error', {'xmlns': I3F_NS}) root.text = spacing e_parameter = Element('parameter', {}) e_parameter.text = self.parameter e_parameter.tail = spacing root.append(e_parameter) if (self.text): e_text = Element('text', {}) e_text.text = self.text e_text.tail = spacing root.append(e_text) # Write out as XML document to return tree = ElementTree(root) xml_buf = io.BytesIO() if (sys.version_info < (2, 7)): tree.write(xml_buf, encoding='UTF-8') else: tree.write(xml_buf, encoding='UTF-8', xml_declaration=True, method='xml') return (xml_buf.getvalue().decode('utf-8'))
def download_image_from_url_to_s3(url: str): ''' url에서 이미지를 stream으로 memory에 올린 후에 해당 메모리를 s3 버킷에 업로드 - s3 upload -> boto3 ''' res = requests.get(url, stream=True) # validate res -> 200 with open('filename', 'w') as f: f.write(fileobj) fileobj = BytesIO() fileobj.write(res.content) Cat.objects.create(image) img = PImage.open(StringIO(res.content)) return img
def load_verify_locations(self, cafile=None, capath=None, cadata=None): # TODO factor out common code if cafile is not None: cafile = cafile.encode('utf-8') if capath is not None: capath = capath.encode('utf-8') self._ctx.load_verify_locations(cafile, capath) if cadata is not None: self._ctx.load_verify_locations(BytesIO(cadata))
def render(self): """ Save the image to the cache if not cached yet. """ if settings.SIMPLETHUMB_CACHE_ENABLED: cached_image = self.cached if cached_image: return cached_image self.process_image() # Store the image data in cache image_str = BytesIO() self.pil.save(image_str, self.image_format, **self.save_params) image_data = image_str.getvalue() if settings.SIMPLETHUMB_CACHE_ENABLED: image_cache.set(self.cache_key, image_data) image_str.close() return image_data
def test03_capability_list_links(self): xml = run_resync([ '--write-capabilitylist=resourcelist=rl,changedump=cd', '--describedby-link=a', '--sourcedescription-link=b', '--capabilitylist-link=c' ]) # will be ignored capl = CapabilityList() capl.parse(fh=io.BytesIO(xml)) self.assertEqual(len(capl), 2) self.assertNotEqual(capl.link('describedby'), None) self.assertEqual(capl.link('describedby')['href'], 'a') self.assertNotEqual(capl.link('up'), None) self.assertEqual(capl.link('up')['href'], 'b')
class _GzipEncoder(object): def __init__(self, request, preamble): preamble.headers['Vary'] = preamble.headers.get('Vary', '') + ',Accept-Encoding' self._accepted = 'gzip' in request.headers.get('Accept-Encoding', '').replace(' ','').split(',') if self._accepted: self._value = BytesIO() self._file = GzipFile(mode='wb', fileobj=self._value) preamble.headers['Content-Encoding'] = preamble.headers.get('Content-Encoding', '') + ',gzip' def encode(self, data): if self._accepted: self._file.write(data) self._file.flush() data = self._value.getvalue() self._value.truncate(0) self._value.seek(0) return data def finish(self, data): if self._accepted: data = self.encode(data) self._file.close() return data
def __init__(self, path, cache=None, cached_name=None, *args, **kwargs): self.path = path self.is_external = path.startswith(('http://', 'https://')) if self.is_external: response = requests.get(path) self.pil = PilImage.open(BytesIO(response.content)) else: self.pil = PilImage.open(path) self.cache = cache self.cached_name = cached_name # force RGB if self.pil.mode not in ('L', 'RGB', 'LA', 'RGBA'): self.pil = self.pil.convert('RGB')
def send_beacon(beacon): # Compress Payload out = io.BytesIO() with gzip.GzipFile(fileobj=out, mode='w') as f: json_str = json.dumps(beacon) json_bytes = json_str.encode('utf-8') f.write(json_bytes) r = requests.post(sendBeaconUrl, headers={ 'Content-Type': 'application/json', 'Accept': 'application/json', 'Content-Encoding': 'gzip' }, data=out.getvalue())
def test02_resource_list_links(self): xml = run_resync([ '--write-resourcelist', '--describedby-link=a', '--sourcedescription-link=b', # will be ignored '--capabilitylist-link=c', 'http://example.org/t', 'tests/testdata/dir1' ]) rl = ResourceList() rl.parse(fh=io.BytesIO(xml)) self.assertEqual(len(rl), 2) self.assertNotEqual(rl.link('describedby'), None) self.assertEqual(rl.link('describedby')['href'], 'a') self.assertNotEqual(rl.link('up'), None) self.assertEqual(rl.link('up')['href'], 'c')
def send_beacon(beacon): out = io.BytesIO() with gzip.GzipFile(fileobj=out, mode='w') as f: json_str = json.dumps(beacon) json_bytes = json_str.encode('utf-8') f.write(json_bytes) print('beacon: {}'.format(beacon)) # validate beacon before sending (optional) r = requests.post(iot['validateBeaconUrl'], headers={ 'Content-Type': 'application/json', 'Content-Length': str(len(json_str)), 'Accept': 'application/json', 'Content-Encoding': 'gzip', }, data=out.getvalue()) print('validate url: {}'.format(iot['validateBeaconUrl'])) if r.status_code != 200: print('validate beacons failed. Check for beacon data format') print('resp code: {}'.format(r.status_code)) print('resp headers: {}'.format(r.headers)) print('resp content: {}\n'.format(r.content)) return else: print('validate beacons passed') # send beacon if validation is successful r = requests.post(iot['sendBeaconUrl'], headers={ 'Content-Type': 'application/json', 'Content-Length': str(len(json_str)), 'Accept': 'application/json', 'Content-Encoding': 'gzip', }, data=out.getvalue()) print('send url: {}'.format(iot['sendBeaconUrl'])) print('resp code: {}'.format(r.status_code)) print('resp headers: {}'.format(r.headers)) print('resp content: {}\n'.format(r.content))
def get_duration(url): """ 返回音频时长 :param url: 绝对路径 :return: """ try: if url: with urllib.request.urlopen(url) as response: data = response.read() f = BytesIO(data) info = MPEGInfo(f) duration = math.ceil(info.length) f.close() else: duration = 0 return duration except Exception as e: logging.error(e) return 0
def make_image(self, data): imgio = io.BytesIO(data) img = Image.open(imgio) return img