Beispiel #1
0
    def format_pdf_report(self, filename, as_response):
        from reportlab.pdfgen.canvas import Canvas
        sio = BytesIO()
        c = Canvas(sio)
        c.save()

        if as_response:
            response = HttpResponse(sio.getvalue(), content_type="application/pdf")
            response["Content-Disposition"] = "attachment; filename=%s" % filename
            return response
        else:
            return sio.getvalue()
 def post(self, request):
     src = request.body.decode('utf-8')
     # 检测用户上传文件是否为图片
     if src[9:14] != 'image':
         return JsonResponse({"msg": "fail"})
     # 定位文件所包含base64编码信息的位置并进行解码转换存入内存文件
     res = src.find('base64,')
     result_src = src[res + len('base64,'):]
     f = BytesIO()
     data = base64.b64decode(result_src)
     f.write(data)
     img = InMemoryUploadedFile(f, None, "image", len(data), None, None)
     # 将文件上传至云服务器
     leancloud.init('tiM1T9UGqwf6QTyXkn9kcL9z-gzGzoHsz',
                    '1GzzyA6uv4l8JNGd6etu5V5o')
     execute = leancloud.File('image', img)
     execute.save()
     result_qrcode = qrcode.make(execute.url)
     buf = BytesIO()
     result_qrcode.save(buf)
     img_stream = buf.getvalue()
     result_img = base64.b64encode(img_stream)
     return JsonResponse({
         "msg": "success",
         "image": bytes.decode(result_img, 'utf-8')
     })
Beispiel #3
0
    def test_document_version_download_user_view(self):
        self.login(
            username=TEST_USER_USERNAME, password=TEST_USER_PASSWORD
        )

        self.assertEqual(Document.objects.count(), 1)

        response = self.post(
            'documents:document_version_download', args=(
                self.document.latest_version.pk,
            )
        )

        self.assertEqual(response.status_code, 302)

        self.role.permissions.add(
            permission_document_download.stored_permission
        )

        response = self.post(
            'documents:document_version_download', args=(
                self.document.latest_version.pk,
            )
        )

        self.assertEqual(response.status_code, 200)

        buf = BytesIO()
        buf.write(response.content)

        self.assertEqual(
            HASH_FUNCTION(buf.getvalue()), TEST_SMALL_DOCUMENT_CHECKSUM
        )

        del(buf)
def package_foirequest(foirequest):
    zfile_obj = BytesIO()
    with override(settings.LANGUAGE_CODE):
        zfile = zipfile.ZipFile(zfile_obj, 'w')
        last_date = None
        date_count = 1
        for message in foirequest.messages:
            current_date = message.timestamp.date()
            date_prefix = current_date.isoformat()
            if current_date == last_date:
                date_count += 1
            else:
                date_count = 1
            date_prefix += '_%d' % date_count
            last_date = current_date

            att_queryset = message.foiattachment_set.filter(
                is_redacted=False,
                is_converted=False
            )
            if message.is_response:
                filename = '%s_%s.txt' % (date_prefix, ugettext('publicbody'))
            else:
                filename = '%s_%s.txt' % (date_prefix, ugettext('requester'))

            zfile.writestr(filename, message.get_formated(att_queryset).encode('utf-8'))

            for attachment in att_queryset:
                if not attachment.file:
                    continue
                filename = '%s-%s' % (date_prefix, attachment.name)
                zfile.write(attachment.file.path, arcname=filename)
        zfile.close()
    return zfile_obj.getvalue()
def get_ssr_qrcode(request, node_id):
    '''返回节点配置信息的ssr二维码'''

    # 获取用户对象
    ss_user = request.user.ss_user
    user = request.user
    # 获取节点对象
    node = Node.objects.get(node_id=node_id)
    # 加入节点信息等级判断
    if user.level < node.level:
        return HttpResponse('哟小伙子,可以啊!但是投机取巧是不对的哦!')

    # 符合ssr qrcode schema最后需要特殊处理的密码部分
    ssr_password = base64.b64encode(bytes(ss_user.password,
                                          'utf8')).decode('ascii')
    ssr_code = '{}:{}:{}:{}:{}:{}'.format(node.server, ss_user.port,
                                          ss_user.protocol, ss_user.method,
                                          ss_user.obfs, ssr_password)
    # 将信息编码
    ssr_pass = base64.b64encode(bytes(ssr_code, 'utf8')).decode('ascii')
    # 生成ss二维码
    ssr_img = qrcode.make('ssr://{}'.format(ssr_pass))
    buf = BytesIO()
    ssr_img.save(buf)
    image_stream = buf.getvalue()
    # 构造图片reponse
    response = HttpResponse(image_stream, content_type="image/png")
    return response
Beispiel #6
0
def homepage(request):
    """
    返回hfs系统登陆后的主界面
    :param request: WSGI对象,GET
    :return: 渲染后的index.html
    """
    err_info = []
    if not validate_identity(request):
        return HttpResponseRedirect('/filescube/authentication/')
    else:
        request.session['access_list'] = table_access.get_access_list_by_id(request.session['username'])
    try:
        path = request.session['root_dir']
        if key_checker.check_if_have_this_key(request.POST, 'path'):
            data_dir = path + request.POST['path']
        else:
            data_dir = path
        if request.method == 'POST':
            if 'qr-code' in request.POST:
                print('-------生成二维码-----')
                url = 'http://' + request.POST['downloadurl']
                # url = request.get_host() + "/index/?download_filename=" + filename +"&download_path=" + data_dir
                img = qrcode.make(url)
                buf = BytesIO()
                img.save(buf)
                image_stream = buf.getvalue()
                response = HttpResponse(image_stream, content_type="image/png")
                return response

        return render(request, 'FilesCube/index.html', locals())
    except Exception as error:
        print(error)
        return render(request, 'FilesCube/index.html', locals())
Beispiel #7
0
def checkface(request):
    try:
        files = request.FILES.get("file")
        type_image = files.name.split('.')[-1]
        filename = "./upload/" + hashlib.sha3_384(
            files.name.encode()).hexdigest() + f".{type_image}"
        with open(filename, "ab+") as fp:
            fp.write(files.read())
        img = BytesIO()
        image = face_recognition.load_image_file(filename)
        locations = face_recognition.face_locations(img=image)
        result_image = Image.fromarray(image)
        for pos in locations:
            d = ImageDraw.Draw(result_image, 'RGBA')
            d.rectangle((pos[3], pos[0], pos[1], pos[2]))
        result_image.save(img, 'png')

        return JsonResponse({
            "status":
            0,
            "filename":
            files.name,
            "face_count":
            len(locations),
            "resultImg_base":
            str(base64.b64encode(img.getvalue()).decode())
        })
    except:
        return JsonResponse({"status": 1, "message": "重试一下吧. 你的照片有问题哦."})
Beispiel #8
0
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()
Beispiel #9
0
 def generate_qrcode(self, data):
     img = qrcode.make(data)
     buf = BytesIO()
     img.save(buf)
     image_stream = buf.getvalue()
     response = HttpResponse(image_stream, content_type="image/png")
     return response
Beispiel #10
0
def printer_label(sample):
    """Generate the PDF of a sample for the label printer.

    :param sample: the sample the label of which should be generated

    :type sample: `samples.models.Sample`

    :return:
      the PDF as a byte stream

    :rtype: str
    """
    output = BytesIO()
    text = sample.name
    c = canvas.Canvas(output, pagesize=(width, height))
    c.setAuthor("JuliaBase samples database")
    c.setTitle(text)
    c.setSubject("Label of {0} for the label printer".format(text))
    try:
        print_line(c, 0, fontsize, text)
    except ExcessException:
        first, second = best_split(text)
        print_line(c, height / 2, fontsize_half, first, force=True)
        print_line(c, 0, fontsize_half, second, force=True)
    c.drawImage(ImageReader("http://chart.googleapis.com/chart?chs=116x116&cht=qr&chl={0}&chld=H|1".format(sample.id)),
                width - height, 0, height, height)
    c.showPage()
    c.save()
    return output.getvalue()
Beispiel #11
0
def package_foirequest(foirequest):
    zfile_obj = BytesIO()
    with override(settings.LANGUAGE_CODE):
        zfile = zipfile.ZipFile(zfile_obj, 'w')
        last_date = None
        date_count = 1
        for message in foirequest.messages:
            current_date = message.timestamp.date()
            date_prefix = current_date.isoformat()
            if current_date == last_date:
                date_count += 1
            else:
                date_count = 1
            date_prefix += '_%d' % date_count
            last_date = current_date

            att_queryset = message.foiattachment_set.filter(is_redacted=False,
                                                            is_converted=False)
            if message.is_response:
                filename = '%s_%s.txt' % (date_prefix, ugettext('publicbody'))
            else:
                filename = '%s_%s.txt' % (date_prefix, ugettext('requester'))

            zfile.writestr(filename,
                           message.get_formated(att_queryset).encode('utf-8'))

            for attachment in att_queryset:
                if not attachment.file:
                    continue
                filename = '%s-%s' % (date_prefix, attachment.name)
                zfile.write(attachment.file.path, arcname=filename)
        zfile.close()
    return zfile_obj.getvalue()
Beispiel #12
0
    def test_document_download_user_view(self):
        # TODO: Skip this test's file descriptor check until it gets migrate
        # SingleObjectDownloadView CBV

        self.login(username=TEST_USER_USERNAME, password=TEST_USER_PASSWORD)

        self.assertEqual(Document.objects.count(), 1)

        response = self.post('documents:document_download',
                             args=(self.document.pk, ))

        self.assertEqual(response.status_code, 302)

        self.role.permissions.add(
            permission_document_download.stored_permission)

        response = self.post('documents:document_download',
                             args=(self.document.pk, ))

        self.assertEqual(response.status_code, 200)

        buf = BytesIO()
        buf.write(response.content)

        self.assertEqual(HASH_FUNCTION(buf.getvalue()),
                         TEST_SMALL_DOCUMENT_CHECKSUM)

        del (buf)
def generate_qrcode(request, data):
    (out, prikey) = RSA_EncryptStr(data)
    img = qrcode.make(b64encode(out).decode('utf-8'))
    buf = BytesIO()
    img.save(buf)
    image_stream = buf.getvalue()
    response = HttpResponse(image_stream, content_type="image/png")
    return response
Beispiel #14
0
def gen_qrcode(data):
    img = qrcode.make(data)

    buf = BytesIO()
    img.save(buf)
    image_stream = buf.getvalue()

    return image_stream
def newqrcode(request, equipment_id):
    information = models.Equipment.objects.get(id=equipment_id)
    i = qrcode.make(information)
    buf = BytesIO()
    i.save(buf)
    image_stream = buf.getvalue()
    response = HttpResponse(image_stream, content_type='image/png')
    return response
Beispiel #16
0
def index(request):
    img = qrcode.make(str("http://weixin.qq.com/r/_S3r8_nEbbQSra2Q93jr"))
    buf = BytesIO()
    img.save(buf)
    image_stream = buf.getvalue()
    response = HttpResponse(image_stream, content_type="image/png")
    #return render(request,'mytest/index.html')
    return response
Beispiel #17
0
def generate_qrcode(request):  # 在线生成二维码
    img = qrcode.make('https://www.baidu.com/')  # 这里指定为百度的二维码
    # img = qrcode.make(data)
    buf = BytesIO()
    img.save(buf)
    image_stream = buf.getvalue()
    response = HttpResponse(image_stream, content_type="image/png")
    return response
Beispiel #18
0
def qrcode_(request):
    #test为二维码中的内容
    text = request.GET.get('text')
    img = qrcode.make(text)
    # 常见二进制内存对象,存储图片
    buf = BytesIO()
    img.save(buf)
    return HttpResponse(buf.getvalue())
def verify_code(request):
    '''随机验证码'''
    # 1.创建画面对象
    # 定义变量,用于画面的背景色、宽、高
    bgcolor = (255, 255, 255)
    width = 200
    height = 45

    im = Image.new('RGB', (width, height), bgcolor)
    # 2.创建画笔对象
    draw = ImageDraw.Draw(im)
    # 3.调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), random.randrange(0, 255),
                random.randrange(0, 255))
        draw.point(xy, fill=fill)
    # 调用画笔的point()函数绘制6条干扰线
    for i in range(6):
        x1 = int(random.randrange(0, width))
        y1 = int(random.randrange(0, height))
        x2 = int(random.randrange(0, width))
        y2 = int(random.randrange(0, height))
        fill = (random.randrange(0, 255), random.randrange(0, 255),
                random.randrange(0, 255))
        draw.line([(x1, y1), (x2, y2)], fill=fill, width=2)

    # 4.定义验证码的备选值
    str1 = 'ABCD123EFGHIJK456klmnopqrstuvwsyzLMNOPQRS789TUVWXYZ0abcdefghij'
    # 随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    # 构造字体对象,ubuntu的字体路径为“/usr/share/fonts/truetype/freefont”
    # 构造字体类型和大小
    font = ImageFont.truetype('FreeMono.ttf', random.randrange(23, 40))
    # 绘制4个字
    draw.text((15, 10), rand_str[0], font=font, fill=random.randrange(0, 255))
    draw.text((65, 10), rand_str[1], font=font, fill=random.randrange(0, 255))
    draw.text((120, 10), rand_str[2], font=font, fill=random.randrange(0, 255))
    draw.text((175, 10), rand_str[3], font=font, fill=random.randrange(0, 255))
    # 5.释放画笔
    del draw
    # 6.存入session,用于做进一步验证
    request.session['verifycode'] = rand_str

    # 内存文件操作(python2)
    # import cStringIO
    # buf = cStringIO.StringIO()

    # 内存文件操作(python3)
    from io import BytesIO
    buf = BytesIO()
    print(buf)
    # 7.将图片保存在内存中,文件类型为png
    im.save(buf, 'png')
    # 8.将内存中的图片数据返回给客户端,MIME类型为图片png
    return HttpResponse(buf.getvalue(), 'image/png')
Beispiel #20
0
 def test_cmd_output(self):
     """ test command output"""
     output = BytesIO()
     errout = BytesIO()
     call_command('modscount',
                  stdout=output,
                  stderr=errout)
     for model in get_models():
         err_str = 'error: There are {} objects in {} model'.format(
             model.objects.count(),
             model.__name__
         )
         out_str = 'There are {} objects in {} model'.format(
             model.objects.count(),
             model.__name__
         )
         self.assertIn(err_str, errout.getvalue())
         self.assertIn(out_str, output.getvalue())
Beispiel #21
0
 def render(self, path, params):
     template = get_template(path)
     html = template.render(params)
     response = BytesIO()
     pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), response, encoding="UTF-8")
     if not pdf.err:
         return HttpResponse(response.getvalue(), content_type='application/pdf')
     else:
         return HttpResponse("Error Rendering PDF", status=400)
         
Beispiel #22
0
def get_qrcode(request, content):
    '''返回字符串编码后的二维码图片'''
    # 加入节点信息等级判断
    ss_img = qrcode.make(content)
    buf = BytesIO()
    ss_img.save(buf)
    image_stream = buf.getvalue()
    # 构造图片reponse
    response = HttpResponse(image_stream, content_type="image/png")
    return response
Beispiel #23
0
def genrate_qrcode(request, data):
    import qrcode
    img = qrcode.make(data)
    from django.utils.six import BytesIO
    buf = BytesIO()
    img.save(buf)
    imge_stream = buf.getvalue()

    response = HttpResponse(imge_stream, content_type='image/png')
    return response
Beispiel #24
0
    def format_xls_report(self, filename, as_response):
        import xlwt
        workbook = xlwt.Workbook("UTF-8")
        sheet = workbook.add_sheet("Koodit")
        y = 0
        for fields in self.get_fields_iterator():
            for x, val in enumerate(fields):
                sheet.write(y, x, val)
            y += 1

        sio = BytesIO()
        workbook.save(sio)

        if as_response:
            response = HttpResponse(sio.getvalue(), content_type="application/vnd.ms-excel")
            response["Content-Disposition"] = "attachment; filename=%s" % filename
            return response
        else:
            return sio.getvalue()
Beispiel #25
0
def generate_qrcode(request, *args, **kwargs):
    data = request.GET.get('data', '')
    img = qrcode.make(data)

    buf = BytesIO()
    img.save(buf)
    image_stream = buf.getvalue()

    response = HttpResponse(image_stream, content_type="image/png")
    return response
Beispiel #26
0
def generate_qrcode(request):
    website = request.POST.get('website')
    if (len(website) != 0):
        img = qrcode.make(str(website))
        buf = BytesIO()
        img.save(buf)
        image_stream = buf.getvalue()
        response = HttpResponse(image_stream, content_type="image/png")
        return response
    return HttpResponse(u"网址不能为空!")
Beispiel #27
0
def get_qrcode(request, content):
    '''返回字符串编码后的二维码图片'''
    # 加入节点信息等级判断
    ss_img = qrcode.make(content)
    buf = BytesIO()
    ss_img.save(buf)
    image_stream = buf.getvalue()
    # 构造图片reponse
    response = HttpResponse(image_stream, content_type="image/png")
    return response
Beispiel #28
0
def createQrcode(request):
    content = request.POST.get("content")
    qr_img = qrcode.make(content)

    buf = BytesIO()
    qr_img.save(buf)
    qr_image_stream = buf.getvalue()

    response = HttpResponse(qr_image_stream,content_type="image/png")
    return response
Beispiel #29
0
def qr_amount(request, amount, detail):
    email = request.user.email
    data = f'email:{email}?amount={amount}?detail={detail}'
    img = qrcode.make(data, image_factory=PymagingImage)
    Buf = BytesIO()
    img.save(Buf)
    image_stream = Buf.getvalue()
    response = HttpResponse(image_stream, content_type='image/jpg')
    response['Content-Disposition'] = 'inline; filename="qr.jpg"'
    return response
Beispiel #30
0
def makeit(request):
    if request.method == "GET":
        text_one = request.GET.get('whoiam', u"我们是谁!")
        text_two = request.GET.get('name', u"甲方!")
        text_three = request.GET.get('whatwewant', u'我们要什么!')
        text_four = request.GET.get('idontknow', u'不知道!')
        text_five = request.GET.get('when', u'什么时候要!')
        text_six = request.GET.get('now', u'现在!')
        if text_one.strip() == "":
            text_one = u"我们是谁!"
        if text_two.strip() == "":
            text_two = u"甲方!"
        if text_three.strip() == "":
            text_three = u'我们要什么!'
        if text_four.strip() == "":
            text_four = u'不知道!'
        if text_five.strip() == "":
            text_five = u'什么时候要!'
        if text_six.strip() == "":
            text_six = u'现在!'
        one = 30
        two = 330
        three = 620
        base = Image.open("base.png")
        font = ImageFont.truetype('font.ttf', 40)
        d = ImageDraw.Draw(base)
        d.text((100 - len(text_one) * 10, one),
               text_one,
               font=font,
               fill=(0, 0, 0))
        d.text((400 - len(text_two) * 10, one),
               text_two,
               font=font,
               fill=(0, 0, 0))
        d.text((100 - len(text_three) * 10, two),
               text_three,
               font=font,
               fill=(0, 0, 0))
        d.text((400 - len(text_four) * 10, two),
               text_four,
               font=font,
               fill=(0, 0, 0))
        d.text((100 - len(text_five) * 10, three),
               text_five,
               font=font,
               fill=(0, 0, 0))
        d.text((400 - len(text_six) * 10, three),
               text_six,
               font=font,
               fill=(0, 0, 0))
        buf = BytesIO()
        base.save(buf, format="png")
        image_stream = buf.getvalue()
        response = HttpResponse(base64.b64encode(image_stream))
        return response
def build_xlsx_response(wb, title="report"):
    title = generate_filename(title, '.xlsx')
    myfile = BytesIO()
    myfile.write(save_virtual_workbook(wb))
    response = HttpResponse(
        myfile.getvalue(),
        content_type=
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = 'attachment; filename=%s' % title
    response['Content-Length'] = myfile.tell()
    return response
Beispiel #32
0
def test_printing(one_per_page):
    from lippukala.printing import OrderPrinter
    printer = OrderPrinter()
    printer.ONE_TICKET_PER_PAGE = one_per_page
    for x in xrange(3):
        order = _create_test_order()
        printer.process_order(order)

    outf = BytesIO()
    outf.write(printer.finish())
    assert outf.getvalue().startswith(b"%PDF")
Beispiel #33
0
    def test_document_version_download(self):
        with open(TEST_SMALL_DOCUMENT_PATH) as file_object:
            document = self.document_type.new_document(file_object=File(file_object))

        response = self.client.get(reverse("rest_api:documentversion-download", args=(document.latest_version.pk,)))
        buf = BytesIO()
        buf.write(response.content)

        self.assertEqual(HASH_FUNCTION(buf.getvalue()), TEST_SMALL_DOCUMENT_CHECKSUM)

        del (buf)
Beispiel #34
0
    def resize_image(self, data, size):
        """ Resizes the given image to fit inside a box of the given size. """
        from machina.core.compat import PILImage as Image
        image = Image.open(BytesIO(data))

        # Resize!
        image.thumbnail(size, Image.ANTIALIAS)

        string = BytesIO()
        image.save(string, format='PNG')
        return string.getvalue()
Beispiel #35
0
    def resize_image(self, data, size):
        """ Resizes the given image to fit inside a box of the given size. """
        from machina.core.compat import PILImage as Image
        image = Image.open(BytesIO(data))

        # Resize!
        image.thumbnail(size, Image.ANTIALIAS)

        string = BytesIO()
        image.save(string, format='PNG')
        return string.getvalue()
 def post(self, request):
     text = request.POST['content']
     text = text.encode('utf8')
     img = qrcode.make(text)
     buf = BytesIO()
     img.save(buf)
     img_stream = buf.getvalue()
     result_img = base64.b64encode(img_stream)
     return JsonResponse({
         "msg": "测试成功",
         "image": bytes.decode(result_img, 'utf-8')
     })
Beispiel #37
0
def make_mc_qrcode(request):
    dt = request.GET.dict()
    url = f"http://{LOCAL_HOST}:8000/meetingCheck/?"
    url = url_change(url, dt)
    qr = qrcode.QRCode(box_size=12, border=2)
    qr.add_data(url)
    qr.make(fit=True)
    img = qr.make_image()
    buf = BytesIO()
    img.save(buf)
    img_stream = buf.getvalue()
    return HttpResponse(img_stream, content_type="image/jpg")
Beispiel #38
0
def getQrcode(request, v=None):
    '''
    根据请求的值返回二维码
    '''
    img = qrcode.make(v)

    buf = BytesIO()
    img.save(buf)
    image_stream = buf.getvalue()

    response = HttpResponse(image_stream, content_type="image/png")
    return response
Beispiel #39
0
def user_login(request):
    full_path = request.get_full_path()
    if 'code' in full_path:
        code = request.GET.get('code')
        user_data = wechat_api(code)
        nickname = user_data['nickname']
        union_id = user_data['union_id']
        head_img = user_data['head_img']

        user = User.objects.filter(union_id=union_id).first()
        status = request.GET.get('status')

        if user:
            if user.name and user.hotel_name:
                return redirect('/customer_profile/{0}/'.format(user.id))
            else:
                return redirect('/customer/save_message/')
        else:

            event = Event.objects.all().first()
            user = User.objects.create(union_id=union_id,
                                       head_img=head_img,
                                       status=0,
                                       event=event)
            request.session['uid'] = user.id
            qr = qrcode.make(
                'https://pinkslash.metatype.cn/wechat_login/?status=sendcredits_{0}_{1}'
                .format(user.id, event.id))
            buf = BytesIO()
            qr.save(buf)
            qr_data = buf.getvalue()
            buf.write(qr_data)
            qr_img = InMemoryUploadedFile(file=buf,
                                          field_name=None,
                                          name='user.png',
                                          content_type='image/png',
                                          size=len(qr_data),
                                          charset=None)
            _user = User.objects.get(id=user.id)
            _user.qrcode = qr_img
            _user.save()

            return redirect('/customer/save_message/')

    else:
        redirect_uri = 'https://pinkslash.metatype.cn' + full_path
        get_code_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc7594d7d49e0235f&redirect_uri=" + \
                       redirect_uri + "&response_type=code&scope=snsapi_userinfo"
        return redirect(get_code_url)

    return HttpResponse("xixi")
Beispiel #40
0
def render(data, width, height, force=True, padding=None, overlays=(), overlay_sources=(),
           overlay_tints=(), overlay_sizes=None, overlay_positions=None, mask=None, mask_source=None,
           center=".5,.5", format=IMAGE_DEFAULT_FORMAT, quality=IMAGE_DEFAULT_QUALITY, fill=None, background=None,
           tint=None, pre_rotation=None, post_rotation=None, crop=True, grayscale=False):
    """
    Rescale the given image, optionally cropping it to make sure the result image has the specified width and height.
    """

    if not isinstance(data, six.string_types):
        input_file = BytesIO(data)
    else:
        input_file = StringIO(data)

    img = pil.open(input_file)
    if img.mode != "RGBA":
        img = img.convert("RGBA")

    if width is None:
        width = img.size[0]
    if height is None:
        height = img.size[1]

    img = do_rotate(img, pre_rotation)

    if crop:
        img = resizeCrop(img, width, height, center, force)
    else:
        img = resizeScale(img, width, height, force)

    if grayscale:
        img = do_grayscale(img)
    do_tint(img, tint)
    img = do_fill(img, fill, width, height)
    img = do_background(img, background)
    do_mask(img, mask, mask_source)
    img = do_overlays(img, overlays, overlay_tints, overlay_sources, overlay_sizes, overlay_positions)
    img = do_padding(img, padding)
    img = do_rotate(img, post_rotation)

    tmp = BytesIO()

    if not format.upper() in ALPHA_FORMATS:
        img = img.convert("RGB")

    img.save(tmp, format, quality=quality)
    tmp.seek(0)
    output_data = tmp.getvalue()
    input_file.close()
    tmp.close()

    return output_data
Beispiel #41
0
def pay(request, oid):
    # 查询到这个订单信息
    order = OrderInfo.objects.get(oid=oid)
    # 修改支付信息
    order.oIsPay = True
    # 将对象保存到数据库中
    order.save()
    # 根据收到的订单号构造二维码
    img = qrcode.make('订单号\n         ' + oid + '\n       ' +
                      '谢谢你来到天天水果购物,祝你生活愉快!')

    buf = BytesIO()
    img.save(buf)
    image_stream = buf.getvalue()
    # 构造上下文
    context = {
        'order': order,
        'img': image_stream,
    }
    #,付帐后,统计销量
    # 查询发货单,统计销量信息
    all = OrderDetailInfo.objects.all().filter(isTrue=False)
    # 遍历
    for a in all:
        # 查询销量表中是否已有此数据,如果则是增加信息,若没有则添加进去
        sale_number = sales.objects.filter(goods=a.goods)
        # 数据库中有此信息
        if len(sale_number) == 1:
            # 销量加上去
            sale1 = sale_number[0]
            sale1.count += a.count
            # 算出此部分销售额
            price1 = a.price * a.count
            sale1.totalprice += price1
            sale1.save()
            a.isTrue = True
            a.save()
        # 数据库中没有此信息
        else:
            sale = sales()
            sale.goods = a.goods
            sale.count = a.count
            # 计算销售额
            price2 = a.count * a.price
            sale.totalprice = price2
            sale.save()
            a.isTrue = True
            a.save()
    # return render(request,'df_order/pay.html',context)
    response = HttpResponse(image_stream, content_type="image/png")
    return response
Beispiel #42
0
def create_verify_code(request):
    """使用Pillow包生成验证码图片"""

    # 引入随机函数模块
    import random
    # 定义变量,用于画面的背景色、宽、高
    bgcolor = (random.randrange(20, 100), random.randrange(20,
                                                           100), 255)  # RGB

    width = 100
    height = 25
    # 创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    # 创建画笔对象
    draw = ImageDraw.Draw(im)

    # 调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)

    # 定义验证码的备选值
    str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'

    # 随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]

    # 构造字体对象,ubuntu的字体路径为“/usr/share/fonts/truetype/freefont”
    font = ImageFont.truetype('FreeMono.ttf', 23)
    # 构造字体颜色
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))

    # 绘制4个字
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)

    # 释放画笔
    del draw
    # 存入session,用于做进一步验证
    request.session['verifycode'] = rand_str
    # 内存文件操作
    buf = BytesIO()
    # 将图片保存在内存中,文件类型为png
    im.save(buf, 'png')
    # 将内存中的图片数据返回给客户端,MIME类型为图片png
    return HttpResponse(buf.getvalue(), 'image/png')
Beispiel #43
0
def generate_thumb(img, thumb_size, extension, image_size=None):
    img.seek(0)  # see http://code.djangoproject.com/ticket/8222 for details
    image = Image.open(img)

    # Convert to RGB if necessary
    if image.mode not in ("L", "RGB", "RGBA"):
        image = image.convert("RGB")
    # get size
    thumb_w, thumb_h = thumb_size
    if not thumb_h:
        if not image_size:
            image_size = image.size
        xsize, ysize = image_size
        thumb_h = float(thumb_w) / xsize * ysize
    elif not thumb_w:
        if not image_size:
            image_size = image.size
        xsize, ysize = image_size
        thumb_w = float(thumb_h) / ysize * xsize
    # If you want to generate a square thumbnail
    if thumb_w == thumb_h:
        # quad
        if not image_size:
            image_size = image.size
        xsize, ysize = image_size
        # get minimum size
        minsize = min(xsize, ysize)
        # largest square possible in the image
        xnewsize = (xsize - minsize) / 2
        ynewsize = (ysize - minsize) / 2
        # crop it
        image2 = image.crop((xnewsize, ynewsize, xsize - xnewsize, ysize - ynewsize))
        # load is necessary after crop
        image2.load()
        # thumbnail of the cropped image (with ANTIALIAS to make it look better)
        image2.thumbnail((thumb_w, thumb_h), Image.ANTIALIAS)
    else:
        # not quad
        image2 = image
        image2.thumbnail((thumb_w, thumb_h), Image.ANTIALIAS)

    io = BytesIO()
    # PNG and GIF are the same, JPG is JPEG
    if extension.upper() == "JPG":
        extension = "JPEG"
    image2.save(io, extension)
    return ContentFile(io.getvalue()), (thumb_w, thumb_h)
Beispiel #44
0
def generate_totp_config_svg(device, issuer, label):
    params = {
        'secret': b32encode(device.bin_key).decode('utf-8'),
        'algorithm': 'SHA1',
        'digits': device.digits,
        'period': device.step,
        'issuer': issuer,
    }

    otpauth_url = 'otpauth://totp/{label}?{query}'.format(
        label=quote(label),
        query=urlencode(params),
    )

    img = qrcode.make(otpauth_url, image_factory=SvgPathImage)
    io = BytesIO()
    img.save(io)
    return io.getvalue()
Beispiel #45
0
def get_test_image_data(size=(32, 32), color=(250, 250, 210), format="JPEG"):
    """
    Get binary image data with the given specs.

    :param size: Size tuple
    :type size: tuple[int, int]
    :param color: RGB color triple
    :type color: tuple[int, int, int]
    :param format: PIL image format specifier
    :type format: str
    :return: Binary data
    :rtype: bytes
    """
    img = Image.new(mode="RGB", size=size)
    img.paste(color)
    sio = BytesIO()
    img.save(sio, format=format, quality=75)
    return sio.getvalue()
    def parse_attachment(self, message_part):
        content_disposition = message_part.get("Content-Disposition", None)
        if content_disposition:
            dispo_type, dispo_dict = self.parse_dispositions(content_disposition)
            if dispo_type == "attachment" or (dispo_type == 'inline' and
                    'filename' in dispo_dict):
                content_type = message_part.get("Content-Type", None)
                file_data = message_part.get_payload(decode=True)
                if file_data is None:
                    payloads = message_part.get_payload()
                    file_data = '\n\n'.join([p.as_string() for p in payloads])
                    try:
                        file_data = file_data.encode('utf-8')
                    except:
                        pass

                attachment = BytesIO(file_data)
                attachment.content_type = message_part.get_content_type()
                attachment.size = len(file_data)
                attachment.name = None
                attachment.create_date = None
                attachment.mod_date = None
                attachment.read_date = None
                if "filename" in dispo_dict:
                    attachment.name = dispo_dict['filename']
                if content_type:
                    _, content_dict = self.parse_dispositions(content_type)
                    if 'name' in content_dict:
                        attachment.name = content_dict['name']
                if attachment.name is None and content_type == 'message/rfc822':
                    p = Parser()
                    msgobj = p.parse(BytesIO(attachment.getvalue()))
                    subject = self.parse_header_field(msgobj['Subject'])
                    if subject:
                        attachment.name = '%s.eml' % subject[:45]
                if "create-date" in dispo_dict:
                    attachment.create_date = dispo_dict['create-date']  # TODO: datetime
                if "modification-date" in dispo_dict:
                    attachment.mod_date = dispo_dict['modification-date']  # TODO: datetime
                if "read-date" in dispo_dict:
                    attachment.read_date = dispo_dict['read-date']  # TODO: datetime
                return attachment
        return None
Beispiel #47
0
def get_ss_qrcode(request, node_id):
    '''返回节点配置信息的ss二维码'''

    # 获取用户对象
    ss_user = request.user.ss_user
    user = request.user
    # 获取节点对象
    node = Node.objects.get(node_id=node_id)
    # 加入节点信息等级判断
    if user.level < node.level:
        return HttpResponse('哟小伙子,可以啊!但是投机取巧是不对的哦!')
    ss_link = node.get_ss_link(ss_user)
    ss_img = qrcode.make(ss_link)
    buf = BytesIO()
    ss_img.save(buf)
    image_stream = buf.getvalue()
    # 构造图片reponse
    response = HttpResponse(image_stream, content_type="image/png")
    return response
Beispiel #48
0
class CouchDBFile(File):
    """
    CouchDBFile - a Django File-like class for CouchDB documents.
    """

    def __init__(self, name, storage, mode):
        self._name = name
        self._storage = storage
        self._mode = mode
        self._is_dirty = False

        try:
            self._doc = self._storage.get_document(name)

            tmp, ext = os.path.split(name)
            if ext:
                filename = "content." + ext
            else:
                filename = "content"
            attachment = self._storage.db.get_attachment(self._doc, filename=filename)
            self.file = BytesIO(attachment)
        except couchdb.client.ResourceNotFound:
            if 'r' in self._mode:
                raise ValueError("The file cannot be reopened.")
            else:
                self.file = BytesIO()
                self._is_dirty = True

    @property
    def size(self):
        return self._doc['size']

    def write(self, content):
        if 'w' not in self._mode:
            raise AttributeError("File was opened for read-only access.")
        self.file = BytesIO(content)
        self._is_dirty = True

    def close(self):
        if self._is_dirty:
            self._storage._put_file(self._name, self.file.getvalue())
        self.file.close()
Beispiel #49
0
def get_file_hash(storage, path):
    """
    Create md5 hash from file contents.
    """
    contents = storage.open(path).read()
    file_hash = hashlib.md5(contents).hexdigest()

    # Check if content should be gzipped and hash gzipped content
    content_type = mimetypes.guess_type(path)[0] or 'application/octet-stream'
    if settings.is_gzipped and content_type in settings.gzip_content_types:
        cache_key = get_cache_key('gzip_hash_%s' % file_hash)
        file_hash = cache.get(cache_key, False)
        if file_hash is False:
            buffer = BytesIO()
            zf = gzip.GzipFile(
                mode='wb', compresslevel=6, fileobj=buffer, mtime=0.0)
            zf.write(force_bytes(contents))
            zf.close()
            file_hash = hashlib.md5(buffer.getvalue()).hexdigest()
            cache.set(cache_key, file_hash)

    return '"%s"' % file_hash
Beispiel #50
0
def gen_face_pay_qrcode(request):
    '''生成当面付的二维码'''
    try:
        # 从seesion中获取订单的二维码
        url = request.session.get('code_url', '')
        # 生成支付宝申请记录
        record = PayRequest.objects.create(username=request.user,
                                           info_code=request.session['out_trade_no'],
                                           amount=request.session['amount'],)
        # 删除sessions信息
        del request.session['code_url']
        del request.session['amount']
        # 生成ss二维码
        img = qrcode.make(url)
        buf = BytesIO()
        img.save(buf)
        image_stream = buf.getvalue()
        # 构造图片reponse
        response = HttpResponse(image_stream, content_type="image/png")
        return response
    except:
        return HttpResponse('wrong request')
Beispiel #51
0
 def parse_attachment(self, message_part):
     content_disposition = message_part.get("Content-Disposition", None)
     if content_disposition:
         dispo_type, dispo_dict = self.parse_dispositions(content_disposition)
         if dispo_type == "attachment" or (dispo_type == "inline" and "filename" in dispo_dict):
             content_type = message_part.get("Content-Type", None)
             file_data = message_part.get_payload(decode=True)
             if file_data is None:
                 payloads = message_part.get_payload()
                 file_data = "\n\n".join([p.as_string() for p in payloads]).encode("utf-8")
             attachment = BytesIO(file_data)
             attachment.content_type = message_part.get_content_type()
             attachment.size = len(file_data)
             attachment.name = None
             attachment.create_date = None
             attachment.mod_date = None
             attachment.read_date = None
             if "filename" in dispo_dict:
                 attachment.name = dispo_dict["filename"]
             if content_type:
                 _, content_dict = self.parse_dispositions(content_type)
                 if "name" in content_dict:
                     attachment.name = content_dict["name"]
             if attachment.name is None and content_type == "message/rfc822":
                 p = Parser()
                 msgobj = p.parse(BytesIO(attachment.getvalue()))
                 subject = self.parse_header_field(msgobj["Subject"])
                 if subject:
                     attachment.name = "%s.eml" % subject[:45]
             if "create-date" in dispo_dict:
                 attachment.create_date = dispo_dict["create-date"]  # TODO: datetime
             if "modification-date" in dispo_dict:
                 attachment.mod_date = dispo_dict["modification-date"]  # TODO: datetime
             if "read-date" in dispo_dict:
                 attachment.read_date = dispo_dict["read-date"]  # TODO: datetime
             return attachment
     return None
Beispiel #52
0
    def _process_image(self):
        """
        Preprocess the uploaded image file, if required.

        This may transcode the image to a JPEG or PNG if it's not either to begin with.

        :raises InvalidImage: Exception raised if the uploaded file is not valid.
        """
        if not self.image:  # No image set - we can't do this right now
            return

        if self.image_format:  # Assume that if image_format is set, no further processing is required
            return

        try:
            img = Image.open(self.image)
            img.load()
        except Exception as exc:
            raise InvalidImage("Image %s not valid (%s)" % (self.image, exc)) from exc

        if img.format not in ("JPEG", "PNG"):  # Needs transcoding.
            if self.type in ("map", "ground_plan"):
                target_format = "PNG"
                save_kwargs = {}
            else:
                target_format = "JPEG"
                save_kwargs = {"quality": 75, "progressive": True}
            image_bio = BytesIO()
            img.save(image_bio, format=target_format, **save_kwargs)
            self.image = ContentFile(
                image_bio.getvalue(),
                name=os.path.splitext(self.image.name)[0] + ".%s" % target_format.lower()
            )
            self.image_format = target_format
        else:  # All good -- keep the file as-is.
            self.image_format = img.format
Beispiel #53
0
class OrderPrinter(object):
    PAGE_WIDTH = 21.0 * cm
    PAGE_HEIGHT = 29.7 * cm
    PAGE_MARGIN_Y = 20 * mm
    PAGE_MARGIN_X = 18 * mm
    TEXT_Y = 80 * mm

    INTRA_TICKET_X_MARGIN = 12 * mm
    INTERTICKET_MARGIN = 0.5 * cm
    TICKET_HEIGHT = 3 * cm

    ONE_TICKET_PER_PAGE = False

    def __init__(self, print_logo_path=PRINT_LOGO_PATH, print_logo_size_cm=PRINT_LOGO_SIZE_CM):
        self.output = BytesIO()
        self.canvas = Canvas(self.output, pagesize=(self.PAGE_WIDTH, self.PAGE_HEIGHT))
        self.n_orders = 0
        self.print_logo_path = print_logo_path
        self.print_logo_size_cm = print_logo_size_cm

    def finish(self):
        self.canvas.save()
        return self.output.getvalue()

    def _align_draw_y(self, draw_y):
        resolution_cm = 0.5
        return int(draw_y / cm / resolution_cm) * resolution_cm * cm

    def get_heading_texts(self, order, n_orders):
        return [
            (("Viitenumero: %s" % order.reference_number) if order.reference_number else None),
            "Tilausaika: %s" % order.created_on.strftime("%d.%m.%Y klo %H:%M"),
        ]

    def get_free_text(self, order):
        return order.free_text.strip()

    def _prime_new_order(self, order):
        canvas = self.canvas

        if self.n_orders > 0:
            canvas.showPage()
        self.n_orders += 1

        # Draw address
        y0 = self.PAGE_HEIGHT - 40 * mm
        x0 = 18 * mm

        if 0:
            canvas.setStrokeColor("silver")
            canvas.rect(x0, y0 - 35 * mm, 94 * mm, 35 * mm)

        canvas.setFillColor("black")
        font_size = 13
        leading = font_size * 1.3
        draw_multiline(
            canvas, x0 + 2 * mm, y0 - (1 * mm), font_size, leading,
            order.address_text.splitlines()
        )

        canvas.setFillColor("black")
        font_size = 11
        leading = font_size * 1.3

        draw_multiline(
            canvas, 115 * mm, y0 - (1 * mm), font_size, leading,
            self.get_heading_texts(order, self.n_orders)
        )

        if self.print_logo_path:
            image_width, image_height = [n * cm for n in self.print_logo_size_cm]
            canvas.drawImage(
                self.print_logo_path,
                115 * mm, y0 + 1 * mm,
                image_width, image_height,
            )

        y = 297 * mm - self.TEXT_Y
        canvas.line(self.PAGE_MARGIN_X, y, self.PAGE_WIDTH - self.PAGE_MARGIN_X, y)
        y -= 3 * mm
        font_size = 11.5
        leading = font_size * 1.4
        y = draw_multiline(canvas, 18 * mm, y, font_size, leading, self.get_free_text(order).splitlines())
        y -= 6 * mm
        canvas.line(self.PAGE_MARGIN_X, y, self.PAGE_WIDTH - self.PAGE_MARGIN_X, y)

        self.draw_y = self._align_draw_y(y - self.INTERTICKET_MARGIN)

    def process_order(self, order):
        if self.ONE_TICKET_PER_PAGE:
            for index, code in enumerate(order.code_set.order_by("literate_code", "code")):
                self._prime_new_order(order)
                self._print_code(index, order, code)
        else:
            self._prime_new_order(order)
            for index, code in enumerate(order.code_set.order_by("literate_code", "code")):
                self._print_code(index, order, code)

    def _print_code(self, index, order, code):

        if self.draw_y - self.TICKET_HEIGHT < max(self.INTERTICKET_MARGIN, self.PAGE_MARGIN_Y):
            self.canvas.showPage()
            self.canvas.setFont("Helvetica", 9, 8)

            page_id_text = "Sivu %d" % self.canvas._pageNumber
            if order.reference_number:
                page_id_text += " - Viitenumero: %s" % order.reference_number
            self.canvas.drawString(self.PAGE_MARGIN_X, self.PAGE_HEIGHT - self.PAGE_MARGIN_Y, page_id_text)
            self.draw_y = self._align_draw_y(self.PAGE_HEIGHT - self.PAGE_MARGIN_Y - 10 * mm)

        ticket_width = self.PAGE_WIDTH - 2 * self.PAGE_MARGIN_X

        with save_state(self.canvas):
            self.canvas.translate(self.PAGE_MARGIN_X, self.draw_y - self.TICKET_HEIGHT)

            self.canvas.roundRect(0, 0, ticket_width, self.TICKET_HEIGHT, 0.15 * cm)

            linear_barcode_width = self.PAGE_WIDTH * 0.5
            barcode_height = 0.5 * self.TICKET_HEIGHT
            linear_barcode = createBarcodeDrawing(
                "Standard39",
                checksum=False,  # Seems to be extraneous (using Android's Barcode reader app),
                quiet=False,  # We'll deal with these ourselves
                value=code.full_code,
                width=linear_barcode_width,
                height=barcode_height
            )

            barcode_bottom_y = self.TICKET_HEIGHT - 3 * mm - barcode_height
            draw_on_pdf(linear_barcode, self.canvas, self.INTRA_TICKET_X_MARGIN, barcode_bottom_y)
            qr_barcode_size = self.TICKET_HEIGHT - 6 * mm
            qr_barcode = createBarcodeDrawing(
                "QR",
                value=code.full_code,
                barBorder=0,  # We'll deal with these ourselves
                width=qr_barcode_size,
                height=qr_barcode_size
            )

            draw_on_pdf(qr_barcode, self.canvas, ticket_width - self.INTRA_TICKET_X_MARGIN - qr_barcode_size, 3 * mm)

            y = draw_multiline(
                self.canvas, self.INTRA_TICKET_X_MARGIN, 11 * mm, 9, 12,
                [
                    u"%s \u2014 %s" % (code.product_text, code.full_code),
                    code.literate_code
                ]
            )

        self.draw_y -= (self.INTERTICKET_MARGIN + self.TICKET_HEIGHT)
class TestMediaIoBaseDownload(unittest.TestCase):

  def setUp(self):
    http = HttpMock(datafile('zoo.json'), {'status': '200'})
    zoo = build('zoo', 'v1', http=http)
    self.request = zoo.animals().get_media(name='Lion')
    self.fd = BytesIO()

  def test_media_io_base_download(self):
    self.request.http = HttpMockSequence([
      ({'status': '200',
        'content-range': '0-2/5'}, b'123'),
      ({'status': '200',
        'content-range': '3-4/5'}, b'45'),
    ])
    self.assertEqual(True, self.request.http.follow_redirects)

    download = MediaIoBaseDownload(
        fd=self.fd, request=self.request, chunksize=3)

    self.assertEqual(self.fd, download._fd)
    self.assertEqual(3, download._chunksize)
    self.assertEqual(0, download._progress)
    self.assertEqual(None, download._total_size)
    self.assertEqual(False, download._done)
    self.assertEqual(self.request.uri, download._uri)

    status, done = download.next_chunk()

    self.assertEqual(self.fd.getvalue(), b'123')
    self.assertEqual(False, done)
    self.assertEqual(3, download._progress)
    self.assertEqual(5, download._total_size)
    self.assertEqual(3, status.resumable_progress)

    status, done = download.next_chunk()

    self.assertEqual(self.fd.getvalue(), b'12345')
    self.assertEqual(True, done)
    self.assertEqual(5, download._progress)
    self.assertEqual(5, download._total_size)

  def test_media_io_base_download_handle_redirects(self):
    self.request.http = HttpMockSequence([
      ({'status': '200',
        'content-location': 'https://secure.example.net/lion'}, b''),
      ({'status': '200',
        'content-range': '0-2/5'}, b'abc'),
    ])

    download = MediaIoBaseDownload(
        fd=self.fd, request=self.request, chunksize=3)

    status, done = download.next_chunk()

    self.assertEqual('https://secure.example.net/lion', download._uri)

  def test_media_io_base_download_handle_4xx(self):
    self.request.http = HttpMockSequence([
      ({'status': '400'}, ''),
    ])

    download = MediaIoBaseDownload(
        fd=self.fd, request=self.request, chunksize=3)

    try:
      status, done = download.next_chunk()
      self.fail('Should raise an exception')
    except HttpError:
      pass

    # Even after raising an exception we can pick up where we left off.
    self.request.http = HttpMockSequence([
      ({'status': '200',
        'content-range': '0-2/5'}, b'123'),
    ])

    status, done = download.next_chunk()

    self.assertEqual(self.fd.getvalue(), b'123')

  def test_media_io_base_download_retries_5xx(self):
    self.request.http = HttpMockSequence([
      ({'status': '500'}, ''),
      ({'status': '500'}, ''),
      ({'status': '500'}, ''),
      ({'status': '200',
        'content-range': '0-2/5'}, b'123'),
      ({'status': '503'}, ''),
      ({'status': '503'}, ''),
      ({'status': '503'}, ''),
      ({'status': '200',
        'content-range': '3-4/5'}, b'45'),
    ])

    download = MediaIoBaseDownload(
        fd=self.fd, request=self.request, chunksize=3)

    self.assertEqual(self.fd, download._fd)
    self.assertEqual(3, download._chunksize)
    self.assertEqual(0, download._progress)
    self.assertEqual(None, download._total_size)
    self.assertEqual(False, download._done)
    self.assertEqual(self.request.uri, download._uri)

    # Set time.sleep and random.random stubs.
    sleeptimes = []
    download._sleep = lambda x: sleeptimes.append(x)
    download._rand = lambda: 10

    status, done = download.next_chunk(num_retries=3)

    # Check for exponential backoff using the rand function above.
    self.assertEqual([20, 40, 80], sleeptimes)

    self.assertEqual(self.fd.getvalue(), b'123')
    self.assertEqual(False, done)
    self.assertEqual(3, download._progress)
    self.assertEqual(5, download._total_size)
    self.assertEqual(3, status.resumable_progress)

    # Reset time.sleep stub.
    del sleeptimes[0:len(sleeptimes)]

    status, done = download.next_chunk(num_retries=3)

    # Check for exponential backoff using the rand function above.
    self.assertEqual([20, 40, 80], sleeptimes)

    self.assertEqual(self.fd.getvalue(), b'12345')
    self.assertEqual(True, done)
    self.assertEqual(5, download._progress)
    self.assertEqual(5, download._total_size)