예제 #1
0
def baked_image_from_abi(abi):
    image_url = abi.badge_instance.get('image')
    if image_url is not None:
        try:
            image = requests.get(image_url)

            unbake(image)
        except:
            pass
        else:
            return image

    try:
        image_url = abi.badge.get('image')
        unbaked_image = ContentFile(
            requests.get(image_url)._content, "unbaked_image.png"
        )

        unbaked_image.open()
        baked_image = bake(
            unbaked_image, json.dumps(dict(abi.badge_instance), indent=2)
        )
    except requests.exceptions.SSLError as e:
        raise ValidationError("SSL failure retrieving image " + image_url)
    except Exception as e:
        raise e
    else:
        return baked_image
예제 #2
0
def bake_badge_instance(badge_instance, badge_class_image_url):
    try:
        unbaked_image = ContentFile(
            requests.get(badge_class_image_url)._content, "unbaked_image.png")
        unbaked_image.open()
        baked_image = bake(unbaked_image, json.dumps(badge_instance, indent=2))
    except requests.exceptions.RequestException as e:
        raise ValidationError("Error retrieving image {}: {}".format(
            badge_class_image_url, e.message))
    return baked_image
예제 #3
0
def bake_badge_instance(badge_instance, badge_class_image_url):
    try:
        unbaked_image = ContentFile(
            requests.get(badge_class_image_url)._content, "unbaked_image.png")
        unbaked_image.open()
        baked_image = bake(unbaked_image, json.dumps(badge_instance, indent=2))
    except requests.exceptions.RequestException as e:
        raise ValidationError(
            "Error retrieving image {}: {}".format(
                badge_class_image_url, e.message))
    return baked_image
예제 #4
0
 def handle(self, *args, **options):
     a = Article()
     aList = a.getAll()
     for i in aList:
         if i.htmlSource == None:
             r = requests.get(i.url)
             srcData = r.text.encode('utf-8')
             srcFile = ContentFile(
                 srcData)  # srcData is the contents of the local file
             srcFile.open()
             i.htmlSource.save(name='%s.html' % i.title, content=srcFile)
             print 'added source code to article %s' % i.url
예제 #5
0
def bake(imageFile, assertion_json_string):
    reader = png.Reader(file=imageFile)

    filename = '%s.png' % hashlib.md5(str(assertion_json_string)).hexdigest()

    newfile = ContentFile("", name=filename)
    newfile.open()
    chunkheader = 'openbadges\x00\x00\x00\x00\x00'
    badge_chunk = ('iTXt', bytes(chunkheader + assertion_json_string))
    png.write_chunks(newfile, baked_chunks(reader.chunks(), badge_chunk))
    newfile.close()
    return newfile
예제 #6
0
def edit_arquivo(request, id):
    usuario = Usuario.objects.get(email=request.session['email'])
    arquivo = Arquivo.objects.get(id=id)
    if request.method == 'GET':
        file = arquivo.arquivo
        file.open(mode='rb')
        content = file.readlines()
        file.close()
        return render_to_response('edit_file.html', {
            'usuario': usuario,
            'arquivo': arquivo,
            'content': content,
            'usuarios': Usuario.objects.all()
        },
                                  context_instance=RequestContext(request))
    elif request.method == 'POST':
        myfile = ContentFile(request.POST['content'])
        nome_arquivo = request.POST['nome']
        tipo_arquivo = request.POST['tipo']
        if 'pasta' in request.POST:
            pasta_arquivo = Pasta.objects.get(id=request.POST['pasta'])
        else:
            pasta_arquivo = None
        try:
            if nome_arquivo != arquivo.nome:
                arq_temp = Arquivo.objects.get(nome=nome_arquivo)
                messages.error(request, 'Ja existe arquivo com este nome')
                return redirect('/app')
            else:
                arq_temp = Arquivo.objects.get(id=nome_arquivo.id)

        except:
            arquivo.arquivo.save(
                str(nome_arquivo) + '.' + tipo_arquivo, myfile)
            arquivo.nome = nome_arquivo
            arquivo.pasta = pasta_arquivo
            arquivo.tipo = tipo_arquivo
            arquivo.save()
            myfile.open(mode='rb')
            content = myfile.readlines()
            myfile.close()
            messages.success(request, 'Alterado com sucesso')
            return render_to_response('edit_file.html', {
                'arquivo': arquivo,
                'content': content,
                'usuarios': Usuario.objects.all()
            },
                                      context_instance=RequestContext(request))
예제 #7
0
    def _create(self, obj):
        dst = self.get_full_path(obj)
        isfile = os.path.isfile(dst)

        size = 0
        if (isfile):
            size = os.path.getsize(dst)

        if (self.is_model):
            self.view.object = obj
            ctx = self.view.get_context_data()
        else:
            ctx = self.view.get_context_data(**obj)
        tr = self.view.render_to_response(ctx)

        # Above only caches data, resolve
        tr = tr.render()

        # Gets the data itself
        #! still bytes
        #! where stripped?
        cf = ContentFile(tr.content, name=None)
        generated_size = cf.size
        if ((generated_size != size) or self.overwrite):
            with open(dst, 'wb') as fd:
                fd.writelines(cf.open())
            return dst
        return None
    def save(self, name, content, max_length=None, suggested_name=""):
        LOG.debug(f"Save {name}")

        if type(content) is bytes:
            content = ContentFile(content, name=name)

        if not hasattr(content, "chunks"):
            content = DjangoFile(content, name)

        if name is None:
            name = content.name

        if not suggested_name:
            suggested_name = getattr(content, "suggested_name", "")

        available_name = self.get_available_name(name, max_length=max_length)
        if available_name != name:
            LOG.debug(f"..renamed to {available_name}")

        dbfile, _ = DBFile.objects.select_for_update().update_or_create(
            name=available_name,
            defaults=dict(suggested_name=suggested_name),
        )

        with content.open("rb") as file:
            dbfile.write(file.read())

        return available_name
예제 #9
0
def bake(imageFile, assertion_json_string):
    """
    Embeds a serialized representation of a badge instance in a PNG image file.
    """
    reader = png.Reader(file=imageFile)

    output_filename = '%s.png' % hashlib.md5(str(assertion_json_string)).hexdigest()

    newfile = ContentFile("", name=output_filename)
    newfile.open()
    chunkheader = 'openbadges\x00\x00\x00\x00\x00'
    badge_chunk = ('iTXt', bytes(chunkheader + assertion_json_string))
    png.write_chunks(newfile, baked_chunks(reader.chunks(), badge_chunk))

    newfile.close()
    return newfile
예제 #10
0
def bake(imageFile, assertion_json_string):
    """
    Embeds a serialized representation of a badge instance in a PNG image file.
    """
    reader = png.Reader(file=imageFile)

    output_filename = "%s.png" % hashlib.md5(str(assertion_json_string)).hexdigest()

    newfile = ContentFile("", name=output_filename)
    newfile.open()
    chunkheader = "openbadges\x00\x00\x00\x00\x00"
    badge_chunk = ("iTXt", bytes(chunkheader + assertion_json_string))
    png.write_chunks(newfile, baked_chunks(reader.chunks(), badge_chunk))

    newfile.close()
    return newfile
예제 #11
0
def edit_arquivo(request, id):
    arquivo = Arquivo.objects.get(id=id)
    if request.method == 'GET':
        file = arquivo.arquivo
        file.open(mode='rb') 
        content = file.readlines()
        file.close()
        return render_to_response('view_file.html', {'arquivo':arquivo, 'content': content}, context_instance=RequestContext(request))
    elif request.method == 'POST':
        myfile = ContentFile(request.POST['content'])
        arquivo.arquivo.save(str(arquivo.nome)+'.'+arquivo.tipo, myfile)
        arquivo.save()
        myfile.open(mode='rb') 
        content = myfile.readlines()
        myfile.close()
        messages.success(request, 'Alterado com sucesso')
        return render_to_response('view_file.html', {'arquivo':arquivo, 'content': content}, context_instance=RequestContext(request))
예제 #12
0
 def test_size_changing_after_writing(self):
     """ContentFile.size changes after a write()."""
     f = ContentFile('')
     self.assertEqual(f.size, 0)
     f.write('Test ')
     f.write('string')
     self.assertEqual(f.size, 11)
     with f.open() as fh:
         self.assertEqual(fh.read(), 'Test string')
예제 #13
0
파일: tests.py 프로젝트: ArcTanSusan/django
 def test_size_changing_after_writing(self):
     """ContentFile.size changes after a write()."""
     f = ContentFile('')
     self.assertEqual(f.size, 0)
     f.write('Test ')
     f.write('string')
     self.assertEqual(f.size, 11)
     with f.open() as fh:
         self.assertEqual(fh.read(), 'Test string')
예제 #14
0
def edit_arquivo(request, id):
    usuario = Usuario.objects.get(email=request.session['email'])
    arquivo = Arquivo.objects.get(id=id)
    if request.method == 'GET':
        file = arquivo.arquivo
        file.open(mode='rb')
        content = file.readlines()
        file.close()
        return render_to_response('edit_file.html', {'usuario': usuario, 'arquivo': arquivo, 'content': content,
                                                     'usuarios': Usuario.objects.all()},
                                  context_instance=RequestContext(request))
    elif request.method == 'POST':
        myfile = ContentFile(request.POST['content'])
        nome_arquivo = request.POST['nome']
        tipo_arquivo = request.POST['tipo']
        if 'pasta' in request.POST:
            pasta_arquivo = Pasta.objects.get(id=request.POST['pasta'])
        else:
            pasta_arquivo = None
        try:
            if nome_arquivo != arquivo.nome:
                arq_temp = Arquivo.objects.get(nome=nome_arquivo)
                messages.error(request, 'Ja existe arquivo com este nome')
                return redirect('/app')
            else:
                arq_temp = Arquivo.objects.get(id=nome_arquivo.id)

        except:
            arquivo.arquivo.save(str(nome_arquivo) + '.' + tipo_arquivo, myfile)
            arquivo.nome = nome_arquivo
            arquivo.pasta = pasta_arquivo
            arquivo.tipo = tipo_arquivo
            arquivo.save()
            myfile.open(mode='rb')
            content = myfile.readlines()
            myfile.close()
            messages.success(request, 'Alterado com sucesso')
            return render_to_response('edit_file.html', {'arquivo': arquivo, 'content': content,
                                                         'usuarios': Usuario.objects.all()},
                                      context_instance=RequestContext(request))
예제 #15
0
    def _save(self, name, content, write_mode, mute=True):
        """
        Given the name of the file and the content (django File object or its
        subclasses) overwrite the file if it exists

        If the incoming stream was a file, it is closed when the method returns
        """

        # Create a content file if the incoming data is not that
        if not hasattr(content, 'open'):
            content = ContentFile(content)

        content.open()
        if content.size <= self.CHUNK_SIZE:
            self.client.files_upload(content.read(),
                                     self._full_path(name),
                                     write_mode,
                                     mute=mute)
        else:
            self._chunked_upload(content, self._full_path, write_mode, mute)

        content.close()
        return name
예제 #16
0
 def test_open_resets_file_to_start_and_returns_context_manager(self):
     file = ContentFile(b'content')
     with file.open() as f:
         self.assertEqual(f.read(), b'content')
     with file.open() as f:
         self.assertEqual(f.read(), b'content')
예제 #17
0
파일: tests.py 프로젝트: LouisAmon/django
 def test_open_resets_file_to_start_and_returns_context_manager(self):
     file = ContentFile(b'content')
     with file.open() as f:
         self.assertEqual(f.read(), b'content')
     with file.open() as f:
         self.assertEqual(f.read(), b'content')