예제 #1
0
 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()
예제 #2
0
 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()
예제 #3
0
 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()
예제 #4
0
 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()
예제 #5
0
    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()
예제 #6
0
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)
예제 #8
0
파일: fileio.py 프로젝트: zorro430/JAQS
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
예제 #9
0
 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'
예제 #10
0
    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'))
예제 #11
0
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
예제 #12
0
 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))
예제 #13
0
    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
예제 #14
0
 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')
예제 #15
0
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
예제 #16
0
    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')
예제 #17
0
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())
예제 #18
0
 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')
예제 #19
0
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))
예제 #20
0
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
예제 #21
0
 def make_image(self, data):
     imgio = io.BytesIO(data)
     img = Image.open(imgio)
     return img