Python qrcode 模块,make() 实例源码

我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用qrcode.make()

项目:wifi-attendance    作者:elvinzeng    | 项目源码 | 文件源码
def get(self, request):
        host = request.META['HTTP_HOST']
        token = request.session.get("verification_token", str(uuid.uuid4()))

        verification_token = VerificationToken()
        verification_token.token = token
        verification_token.expire_time = datetime.datetime.now() + datetime.timedelta(minutes=1)
        verification_token.save()

        data = "http://" + host + "/authorize?token=" + token
        img = qrcode.make(data)
        buf = StringIO()
        img.save(buf)
        image_stream = buf.getvalue()
        response = HttpResponse(image_stream, content_type="image/png")
        return response
项目:django-sspanel    作者:Ehco1996    | 项目源码 | 文件源码
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_link = node.get_ssr_link(ss_user)
    ssr_img = qrcode.make(ssr_link)
    buf = BytesIO()
    ssr_img.save(buf)
    image_stream = buf.getvalue()
    # ????reponse
    response = HttpResponse(image_stream, content_type="image/png")
    return response
项目:django-sspanel    作者:Ehco1996    | 项目源码 | 文件源码
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
项目:django-sspanel    作者:Ehco1996    | 项目源码 | 文件源码
def gen_face_pay_qrcode(request):
    '''?????????'''
    try:
        # ?seesion?????????
        url = request.session.get('code_url', '')
        # ?????????
        record = AlipayRequest.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')
项目:django-droidstore    作者:mathuin    | 项目源码 | 文件源码
def save(self, *args, **kwargs):
        with ZipFile(self.apkfile, 'r') as myzip:
            am = myzip.read('AndroidManifest.xml')
            ap = axmlprinter.AXMLPrinter(am)
            ax = minidom.parseString(ap.getBuff())
            manifest = ax.getElementsByTagName('manifest')[0]
            for (name, value) in list(manifest.attributes.items()):
                if name == 'android:versionName':
                    self.version = value
                elif name == 'package':
                    self.package = value
            # http://stackoverflow.com/questions/7894897/django-saving-an-image-manually-to-an-imagefield-field
            qrimage = qrcode.make('market://search?q=pname:%s' % self.package)
            temp_handle = StringIO()
            qrimage.save(temp_handle, 'png')
            temp_handle.seek(0)
            suf = SimpleUploadedFile('suf', temp_handle.read(), content_type='image/png')
            # pylint: disable-msg=E1101 
            self.qrcodefile.save('save', suf, save=False)
            # pylint: enable-msg=E1101
        super(Product, self).save(*args, **kwargs)
项目:passport    作者:SRELabs    | 项目源码 | 文件源码
def user_otp_qrcode(request):
    uid = request.REQUEST.get('uid', '')
    otp_type = request.REQUEST.get('type', 'users')
    try:
        if otp_type == 'users':
            data = Users.objects.get(pk=uid)
            otp = data.users_otp
            email = data.users_email
        else:
            data = User.objects.get(pk=uid)
            otp = UserProfile.objects.get(user=data).otp
            email = data.email
        tmp = "otpauth://totp/%s?secret=%s" % (email, otp)
        img = qrcode.make(tmp)

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

        response = HttpResponse(image_stream, content_type="image/png")
        # response['Last-Modified'] = 'Mon, 27 Apr 2015 02:05:03 GMT'
        # response['Cache-Control'] = 'max-age=1'
        return response
    except Exception,e:
        return HttpResponse()
项目:swjtu-oj-insite    作者:swjtuacmer    | 项目源码 | 文件源码
def get(self, request):
        """
        ???????
        """
        user = request.user
        if user.two_factor_auth:
            return error_response(u"?????????")
        token = rand_str()
        user.tfa_token = token
        user.save()

        image = qrcode.make(OtpAuth(token).to_uri("totp", settings.WEBSITE_INFO["url"], "OnlineJudgeAdmin"))
        buf = StringIO.StringIO()
        image.save(buf, 'gif')

        return HttpResponse(buf.getvalue(), 'image/gif')
项目:Guanja    作者:Desgard    | 项目源码 | 文件源码
def get(self, request):
        """
        ???????
        """
        user = request.user
        if user.two_factor_auth:
            return error_response(u"?????????")
        token = rand_str()
        user.tfa_token = token
        user.save()

        image = qrcode.make(OtpAuth(token).to_uri("totp", settings.WEBSITE_INFO["url"], "OnlineJudgeAdmin"))
        buf = StringIO.StringIO()
        image.save(buf, 'gif')

        return HttpResponse(buf.getvalue(), 'image/gif')
项目:plumeria    作者:sk89q    | 项目源码 | 文件源码
def qr(message):
    """
    Generates a QR code from given text.

    Example::

        /qrcode Hello there!
    """
    if len(message.content) > 200:
        raise CommandError("Text is too long to generate a QR code for.")

    def execute():
        old = qrcode.make(message.content, border=2)
        new = Image.new("RGB", old.size, (255, 255, 255))
        new.paste(old)
        return new

    im = await asyncio.get_event_loop().run_in_executor(None, execute)
    return Response("", [ImageAttachment(im, "qr.png")])
项目:retoohs    作者:youyaochi    | 项目源码 | 文件源码
def get_ss_qr(request):
    if request.user.is_anonymous():
        return JsonResponse({'error': 'unauthorized'})

    if not hasattr(request.user, 'ss_user'):
        return JsonResponse({'error': 'no linked shadowsocks account'})
    ss_user = request.user.ss_user

    if request.GET.get('nid'):
        try:
            node = Node.objects.get(pk=request.GET.get('nid'))
        except Node.DoesNotExist:
            return JsonResponse({'error': 'node not exist'})
    else:
        node = Node.objects.all().order_by('-weight')
        if node:
            node = node[0]
        else:
            return JsonResponse({'error': 'no node at all'})

    password = '{}:{}@{}:{}'.format(node.method, ss_user.password, node.server, ss_user.port)
    img = qrcode.make('ss://{}'.format(base64.b64encode(bytes(password, 'utf8')).decode('ascii')))
    response = HttpResponse(content_type="image/png")
    img.save(response)
    return response
项目:OnlineJudgeSHU    作者:lonelam    | 项目源码 | 文件源码
def get(self, request):
        """
        ???????
        """
        user = request.user
        if user.two_factor_auth:
            return error_response(u"?????????")
        token = rand_str()
        user.tfa_token = token
        user.save()

        image = qrcode.make(OtpAuth(token).to_uri("totp", settings.WEBSITE_INFO["url"], "OnlineJudgeAdmin"))
        buf = StringIO.StringIO()
        image.save(buf, 'gif')

        return HttpResponse(buf.getvalue(), 'image/gif')
项目:Tktr    作者:Intuity    | 项目源码 | 文件源码
def add_ticket_to_pdf(self, pdf, ticket, offset=0):
        if offset < 10:
            offset = offset * 75
        # Generate and save the QR code temporarily
        tmp_path = self.request.registry._settings["base_dir"] + "/data/tmp/"
        qr_img = qrcode.make("id:" + ticket.__name__ + ":pay:" + ticket.payment.__name__ + ":owner:" + ticket.owner.profile.fullname + ":price:" + str(ticket.tick_type.cost) + ":type:" + ticket.tick_type.name)
        qr_tmp_path = tmp_path + ticket.__name__ + ".png"
        qr_img.save(qr_tmp_path, "PNG")

        # Draw a ticket background if it exists
        bg_path = self.request.registry._settings["base_dir"] + "/data/ticket_backer.png"
        if os.path.isfile(bg_path):
            pdf.image(bg_path, x=10, y=10 + offset, w=190, h=70, type='PNG')

        # Draw the QR Code
        pdf.image(qr_tmp_path, x=12, y=12 + offset, w=66, h=66, type='PNG')

        pdf.set_font('Arial', 'B', 16)
        pdf.set_text_color(0,0,0)
        title = self.event_name
        if len(title) > 30:
            title = title[:30] + "..."
        pdf.text(x=80, y=23 + offset, txt=title)
        pdf.set_font('Arial', 'I', 13)
        pdf.text(x=80, y=30 + offset, txt=PROP_KEYS.getProperty(self.request, PROP_KEYS.EVENT_DATE).strftime('%A %d %B %Y'))
        pdf.set_font('Arial', '', 16)
        pdf.text(x=80, y=37 + offset, txt=ticket.guest_info.fullname)
        pdf.text(x=80, y=44 + offset, txt=ticket.tick_type.name)
        pdf.text(x=80, y=52 + offset, txt=self.format_price(ticket.tick_type.cost))
        pdf.set_font('Arial', '', 16)
        pdf.set_text_color(150,150,150)
        pdf.text(x=80, y=60 + offset, txt="Ticket ID: " + ticket.__name__)
        pdf.text(x=80, y=68 + offset, txt="Payment ID:" + ticket.payment.__name__)

        # Draw the ticket box outline
        pdf.set_draw_color(100, 100, 100)
        pdf.set_line_width(0.1)
        pdf.rect(10, 10 + offset, 190, 70)
项目:workflows.kyoyue    作者:wizyoung    | 项目源码 | 文件源码
def test_basic(self):
        qr = qrcode.QRCode(version=1)
        qr.add_data('a')
        qr.make(fit=False)
项目:workflows.kyoyue    作者:wizyoung    | 项目源码 | 文件源码
def test_large(self):
        qr = qrcode.QRCode(version=27)
        qr.add_data('a')
        qr.make(fit=False)
项目:workflows.kyoyue    作者:wizyoung    | 项目源码 | 文件源码
def test_invalid_version(self):
        qr = qrcode.QRCode(version=41)
        self.assertRaises(ValueError, qr.make, fit=False)
项目:workflows.kyoyue    作者:wizyoung    | 项目源码 | 文件源码
def test_overflow(self):
        qr = qrcode.QRCode(version=1)
        qr.add_data('abcdefghijklmno')
        self.assertRaises(DataOverflowError, qr.make, fit=False)
项目:workflows.kyoyue    作者:wizyoung    | 项目源码 | 文件源码
def test_add_qrdata(self):
        qr = qrcode.QRCode(version=1)
        data = QRData('a')
        qr.add_data(data)
        qr.make(fit=False)
项目:workflows.kyoyue    作者:wizyoung    | 项目源码 | 文件源码
def test_mode_number(self):
        qr = qrcode.QRCode()
        qr.add_data('1234567890123456789012345678901234', optimize=0)
        qr.make()
        self.assertEqual(qr.version, 1)
        self.assertEqual(qr.data_list[0].mode, MODE_NUMBER)
项目:workflows.kyoyue    作者:wizyoung    | 项目源码 | 文件源码
def test_mode_alpha(self):
        qr = qrcode.QRCode()
        qr.add_data('ABCDEFGHIJ1234567890', optimize=0)
        qr.make()
        self.assertEqual(qr.version, 1)
        self.assertEqual(qr.data_list[0].mode, MODE_ALPHA_NUM)
项目:workflows.kyoyue    作者:wizyoung    | 项目源码 | 文件源码
def test_regression_mode_comma(self):
        qr = qrcode.QRCode()
        qr.add_data(',', optimize=0)
        qr.make()
        self.assertEqual(qr.data_list[0].mode, MODE_8BIT_BYTE)
项目:workflows.kyoyue    作者:wizyoung    | 项目源码 | 文件源码
def test_mode_8bit(self):
        qr = qrcode.QRCode()
        qr.add_data(u'abcABC' + UNICODE_TEXT, optimize=0)
        qr.make()
        self.assertEqual(qr.version, 1)
        self.assertEqual(qr.data_list[0].mode, MODE_8BIT_BYTE)
项目:workflows.kyoyue    作者:wizyoung    | 项目源码 | 文件源码
def test_mode_8bit_newline(self):
        qr = qrcode.QRCode()
        qr.add_data('ABCDEFGHIJ1234567890\n', optimize=0)
        qr.make()
        self.assertEqual(qr.data_list[0].mode, MODE_8BIT_BYTE)
项目:workflows.kyoyue    作者:wizyoung    | 项目源码 | 文件源码
def test_optimize_size(self):
        text = 'A1abc12345123451234512345def1HELLOHELLOHELLOHELLOa' * 5

        qr = qrcode.QRCode()
        qr.add_data(text)
        qr.make()
        self.assertEqual(qr.version, 10)

        qr = qrcode.QRCode()
        qr.add_data(text, optimize=0)
        qr.make()
        self.assertEqual(qr.version, 11)
项目:workflows.kyoyue    作者:wizyoung    | 项目源码 | 文件源码
def runTest(self):
        qrcode.make('image')
项目:SpongeAuth    作者:lukegb    | 项目源码 | 文件源码
def regenerate(request, device_id):
    device_qs = (
        twofa.models.Device.objects
        .active_for_user(request.user).select_subclasses())
    device = get_object_or_404(device_qs, pk=device_id)
    if not device.can_regenerate():
        messages.error(request, _('The "%(auth_name)s" authenticator cannot be regenerated.') % {
            'auth_name': device.name()})
        return redirect('twofa:list')

    device.regenerate()

    # TODO(lukegb): make this more general
    return redirect(reverse('twofa:paper-code', kwargs={'device_id': device.pk}))
项目:wank.party    作者:Streetwalrus    | 项目源码 | 文件源码
def qr(filename=None):
    if not filename:
        abort(400)
    if not Upload.query.filter_by(path=filename).first():
        abort(404)

    url = _cfg("protocol") + "://" + _cfg("domain") + "/" + filename
    qr = qrcode.make(url)

    byte_io = BytesIO()
    img = qr.save(byte_io, "PNG")
    byte_io.seek(0)

    return send_file(byte_io, mimetype="image/png")
项目:audio-feeder    作者:pganssle    | 项目源码 | 文件源码
def generate_qr(self, data, save_path):
        img = qrcode.make(data, **self.qr_options)
        img.save(save_path)
项目:python-django-wechat    作者:JingRanCor    | 项目源码 | 文件源码
def generate_qrcode(data, filepath):
    '''?????'''
    try:
        img = qrcode.make(data)
        img.save(filepath)
        return True
    except:
        return False
项目:SuperOcto    作者:mcecchi    | 项目源码 | 文件源码
def _write_qr_to_file(self, api_key):
        folder = self.get_plugin_data_folder()
        img = qrcode.make(api_key)
        img.save('{}/{}'.format(folder, 'qr_code.png'))
项目:RoBrutev6    作者:RussianOtter    | 项目源码 | 文件源码
def qr_ran(size=args.random,amount=args.amount,rate=args.Rate):
    for _ in range(amount):
        key = []
        for i in range(size):
            key.append(random.choice(list(string.hexdigits)))
        key = "".join(key)
        qr = qrcode.make(key)
        qr.show()
        time.sleep(rate)
        try:
            #console.clear()
            pass
        except:
            pass
项目:RoboLCD    作者:victorevector    | 项目源码 | 文件源码
def _write_qr_to_file(self, api_key):
        folder = self.get_plugin_data_folder()
        img = qrcode.make(api_key)
        img.save('{}/{}'.format(folder, 'qr_code.png'))
项目:python_learn    作者:jetty-guo    | 项目源码 | 文件源码
def create_QR():
    img = qrcode.make(
        'hello, qrcode111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111')
    img.save(pic_url)
项目:lenuage    作者:laboiteproject    | 项目源码 | 文件源码
def generate_qrcode(self):
        url = 'http://'
        url += str(Site.objects.get_current())
        url += '/boites/redirect/'
        url += str(self.api_key)
        img = qrcode.make(url)

        buffer = BytesIO()
        img.save(buffer)

        filename = 'qrcode-%s.png' % str(self.api_key)
        filebuffer = InMemoryUploadedFile(buffer, None, filename,
                                          'image/png', len(buffer.getvalue()), None)
        self.qrcode.save(filename, filebuffer)
项目:xf    作者:red-green    | 项目源码 | 文件源码
def generate():
    txt = raw_input('text to encode> ')
    path = raw_input('path to write out file to (include an extension)> ').strip()
    img = qrcode.make(txt)
    img.save(path)
项目:Wox.Plugin.Py.Qrcode    作者:ousui    | 项目源码 | 文件源码
def _genBarcode(self, content):
        md5 = hashlib.md5(bytes(content, 'utf-8')).hexdigest()
        path = os.path.join(PKG_DIR, 'images', 'qrcodes', '{}.png'.format(md5))
        # ??????md5????????????????????
        if os.path.isfile(path):
            return path
        qrcode.make(content).save(path)
        return path
项目:king-phisher-plugins    作者:securestate    | 项目源码 | 文件源码
def enrollment_remove(self, _):
        rpc = self.application.rpc
        this_user = rpc.remote_table_row('users', rpc.username)
        if this_user.otp_secret is None:
            gui_utilities.show_dialog_info(
                'Not Enrolled',
                self.application.get_active_window(),
                'This account is not currently enrolled in two factor\n'\
                + 'authentication. There are no changes to make.'
            )
            return
        remove = gui_utilities.show_dialog_yes_no(
            'Already Enrolled',
            self.application.get_active_window(),
            'Are you sure you want to unenroll in TOTP? This will remove\n'\
            + 'two factor authentication on your account.'
        )
        if not remove:
            return
        this_user.otp_secret = None
        this_user.commit()
        gui_utilities.show_dialog_info(
            'TOTP Unenrollment',
            self.application.get_active_window(),
            'Successfully removed the TOTP secret. Your account is now unenrolled\n'\
            + 'in two factor authentication. You will no longer be prompted to enter\n'\
            + 'the value when you login.'
        )
项目:king-phisher-plugins    作者:securestate    | 项目源码 | 文件源码
def enrollment_setup(self, _):
        rpc = self.application.rpc
        this_user = rpc.remote_table_row('users', rpc.username)
        if this_user.otp_secret is not None:
            reset = gui_utilities.show_dialog_yes_no(
                'Already Enrolled',
                self.application.get_active_window(),
                'This account is already enrolled in TOTP,\nreset the existing TOTP token?'
            )
            if not reset:
                return
        new_otp = pyotp.TOTP(pyotp.random_base32())
        provisioning_uri = rpc.username + '@' + self.application.config['server'].split(':', 1)[0]
        provisioning_uri = new_otp.provisioning_uri(provisioning_uri) + '&issuer=King%20Phisher'
        bytes_io = io.BytesIO()
        qrcode_ = qrcode.make(provisioning_uri).get_image()
        qrcode_.save(bytes_io, 'PNG')
        pixbuf_loader = GdkPixbuf.PixbufLoader.new()
        pixbuf_loader.write(bytes_io.getvalue())
        pixbuf_loader.close()
        pixbuf = pixbuf_loader.get_pixbuf()

        self.logger.debug('loading gtk builder file from: ' + gtk_builder_file)
        builder = Gtk.Builder()
        builder.add_from_file(gtk_builder_file)
        window = builder.get_object('TOTPEnrollment.window')
        window.set_transient_for(self.application.get_active_window())

        self.application.add_window(window)

        image = builder.get_object('TOTPEnrollment.image_qrcode')
        image.set_from_pixbuf(pixbuf)

        button_check = builder.get_object('TOTPEnrollment.button_check')
        entry_totp = builder.get_object('TOTPEnrollment.entry_totp')
        button_check.connect('clicked', self.check_totp, window, entry_totp, new_otp, this_user)
        entry_totp.connect('activate', self.check_totp, window, entry_totp, new_otp, this_user)

        window.show_all()
项目:bctip    作者:norn    | 项目源码 | 文件源码
def qrcode_view(request, key):
    wallet = get_object_or_404(Wallet, key=key)
    img = qrcode.make(
        wallet.bcaddr_uri, box_size=6, error_correction=qrcode.ERROR_CORRECT_M)
    output = StringIO.StringIO()
    img.save(output, "PNG")
    c = output.getvalue()
    return HttpResponse(c, content_type="image/png")
项目:bctip    作者:norn    | 项目源码 | 文件源码
def qrcode_img(text):
    img = qrcode.make(text, box_size=2, error_correction=qrcode.ERROR_CORRECT_M)
    output = StringIO.StringIO()
    img.save(output, "PNG")
    c = output.getvalue()
    return c
项目:pyzcto    作者:miguelmarco    | 项目源码 | 文件源码
def showzcpqr(self):
        fd = open('./hidden_service/hostname')
        oniondom = fd.readline().split()[0]
        fd.close()
        username = str(self.line_user.text())
        password = str(self.line_password.text())
        img = qrcode.make(username+':'+password+'@'+oniondom)
        img.save('qrcode.png', 'PNG')
        qrc = QPixmap('qrcode.png')
        os.remove('qrcode.png')
        self.onionlabelname.setText(username+':'+password+'@'+oniondom)
        self.onionlabelname.show()
        self.onionlabel.setPixmap(qrc.scaled(self.onionlabel.size(), Qt.KeepAspectRatio))
        self.onionlabel.show()
项目:pyzcto    作者:miguelmarco    | 项目源码 | 文件源码
def showorbotqr(self):
        fd = open('./hidden_service/hostname')
        line = fd.readline()
        oniondom =line.split()[0]
        cookie = line.split()[1]
        fd.close()
        jsonstring = '{'+'"auth_cookie_value": "{}", "domain":"{}"'.format(cookie, oniondom)+'}'
        img = qrcode.make(jsonstring)
        img.save('qrcode.png', 'PNG')
        qrc = QPixmap('qrcode.png')
        os.remove('qrcode.png')
        self.onionlabelname.setText(jsonstring)
        self.onionlabelname.show()
        self.onionlabel.setPixmap(qrc.scaled(self.onionlabel.size(), Qt.KeepAspectRatio))
        self.onionlabel.show()
项目:pyzcto    作者:miguelmarco    | 项目源码 | 文件源码
def geneartereceiveqr(self):
        try:
            address = self.receiveaddresses[self.listaddresses_receive.currentIndex().row()]
        except:
            address = ''
        amount = self.line_receiveamount.text()
        comment = self.line_receivedesc.text()
        if address and amount:
            if comment:
                try:
                    string = 'zcash:{}?amount={}&message={}'.format(address,amount,comment)
                except:
                    self.label_qrreceive.hide()
                    self.label_textreceive.hide()
                    return
            else:
                string = 'zcash:{}?amount={}'.format(address,amount)
            img = qrcode.make(string)
            img.save('qrcode.png', 'PNG')
            qrc = QPixmap('qrcode.png')
            os.remove('qrcode.png')
            self.label_textreceive.setText(string)
            self.label_textreceive.show()
            self.label_qrreceive.setPixmap(qrc.scaled(self.onionlabel.size(), Qt.KeepAspectRatio))
            self.label_qrreceive.show()
        else:
            self.label_qrreceive.hide()
            self.label_textreceive.hide()
项目:qrcode_track    作者:flingjie    | 项目源码 | 文件源码
def post(self):
        name = self.request.arguments.get('name')[0]
        post_type = self.request.arguments.get('type')[0]
        if int(post_type) == LINK_TYPE:
            data = self.request.arguments.get('info')[0]
            url = add_http(data.decode("utf-8"))
        else:
            b64img = self.request.arguments.get('image')[0]
            img = BytesIO(base64.b64decode(b64img))
            scanner = zbar.ImageScanner()
            scanner.parse_config('enable')
            pil = Image.open(img).convert('L')
            width, height = pil.size
            raw = pil.tobytes()
            image = zbar.Image(width, height, 'Y800', raw)
            scanner.scan(image)
            for symbol in image:
                url = add_http(symbol.data)

        cur_user = self.get_current_user()
        if cur_user:
            users = self.db[USER_COLLECTION]
            users.update({'phone': cur_user['phone']}, {'$addToSet': {'qrcode': url}})
        stat_col = self.db[STATISTIC_COLLECTION]
        if not stat_col.find_one({'url': url}):
            stat_col.insert({
                'name': name,
                'url': url,
                'visit': []
            })
        else:
            stat_col.update({'url': url}, {"$set": {'name': name}})
        img = qrcode.make(gen_new_url(url))
        o = BytesIO()
        img.save(o, "JPEG")
        s = base64.b64encode(o.getvalue())

        img = qrcode.make(gen_statistic_url(url))
        o = BytesIO()
        img.save(o, "JPEG")
        s2 = base64.b64encode(o.getvalue())

        self.write({
            "qrcode": s.decode('utf-8'),
            "statistic": s2.decode('utf-8')
        })
项目:health-mosconi    作者:GNUHealth-Mosconi    | 项目源码 | 文件源码
def make_qrcode(self, name):
    # Create the QR code

        patient_puid = self.puid or ''

        patient_blood_type = self.blood_type or ''

        patient_rh = self.rh or ''

        patient_gender = self.gender or ''

        patient_dob = self.dob or ''

        patient_id = self.puid or ''

        if self.lastname:
            patient_lastname = self.lastname + ', '
        else:
            patient_lastname = ''

        qr_string = 'ID: ' + patient_id \
            + '\nName: ' + patient_lastname + ',' \
                + self.name.name \
            + '\nPUID: ' + patient_puid \
            + '\nGender: ' + patient_gender \
            + '\nDoB: ' + str(patient_dob) \
            + '\nBlood Type: ' + patient_blood_type \
                + ' ' + patient_rh


        qr_image = qrcode.make(qr_string)

        # Make a PNG image from PIL without the need to create a temp file

        holder = StringIO.StringIO()
        qr_image.save(holder)
        qr_png = holder.getvalue()
        holder.close()

        return bytearray(qr_png)

# Add the QR code field and image to the Newborn
项目:health-mosconi    作者:GNUHealth-Mosconi    | 项目源码 | 文件源码
def make_qrcode(self, name):
    # Create the QR code

        if self.mother:
            if self.mother.name.lastname:
                newborn_mother_lastname = self.mother.name.lastname + ', '
            else:
                newborn_mother_lastname = ''

            newborn_mother_name = self.mother.name.name or ''

            newborn_mother_id = self.mother.puid or ''

        else:
            newborn_mother_lastname = ''
            newborn_mother_name = ''
            newborn_mother_id = ''

        newborn_name = self.name or ''

        newborn_sex = self.sex or ''

        newborn_birth_date = self.birth_date or ''

        qr_string = 'PUID: ' + newborn_name \
            + '\nMother: ' + newborn_mother_lastname \
                    + newborn_mother_name \
            + '\nMother\'s PUID: ' + newborn_mother_id \
            + '\nSex: ' + newborn_sex \
            + '\nDoB: ' + str(newborn_birth_date)


        qr_image = qrcode.make(qr_string)

        # Make a PNG image from PIL without the need to create a temp file

        holder = StringIO.StringIO()
        qr_image.save(holder)
        qr_png = holder.getvalue()
        holder.close()

        return bytearray(qr_png)
项目:SpongeAuth    作者:lukegb    | 项目源码 | 文件源码
def setup_totp(request):
    if twofa.models.TOTPDevice.objects.active_for_user(request.user).exists():
        messages.error(request, _('You may not have multiple Google Authenticators attached to your account.'))
        return redirect('twofa:list')

    setup_signer = TimestampSigner('twofa.views.setup_totp:{}'.format(request.user.pk))

    if request.method == 'POST' and 'secret' in request.POST:
        try:
            b32_secret = setup_signer.unsign(request.POST['secret'], max_age=600)
        except SignatureExpired:
            messages.error(request, _('That took too long and your challenge expired. Here\'s a new one.'))
            return redirect('twofa:setup-totp')
        except BadSignature:
            messages.error(request, _('Whoops - something went wrong. Please try again.'))
            return redirect('twofa:setup-totp')
    else:
        b32_secret = base64.b32encode(secrets.token_bytes(10))
    signed_secret = setup_signer.sign(b32_secret)

    url = 'otpauth://totp/Sponge:{}?{}'.format(
        urlquote(request.user.username),
        urlencode({
            'secret': b32_secret,
            'issuer': 'Sponge'}))
    img = qrcode.make(url, image_factory=qrcode.image.svg.SvgPathFillImage)
    img_buf = io.BytesIO()
    img.save(img_buf)

    device = twofa.models.TOTPDevice(base32_secret=b32_secret, owner=request.user)
    device.activated_at = timezone.now()  # this won't be saved unless the form is valid
    form = device.verify_form(secret=signed_secret)
    if request.method == 'POST':
        form = device.verify_form(request.POST, secret=signed_secret)

        if form.is_valid():
            # relying on verify_form to save the new device
            request.user.twofa_enabled = True
            request.user.save()

            messages.success(request, _('Your authenticator has been added to your account.'))
            return _generate_paper_codes_if_needed(request.user, reverse('twofa:list'))

    return render(request, 'twofa/setup/totp.html', {
        'form': form, 'qr_code_svg': img_buf.getvalue(), 'b32_secret': b32_secret})
项目:gnuhealth-live    作者:kret0s    | 项目源码 | 文件源码
def make_qrcode(self, name):
    # Create the QR code

        patient_puid = self.puid or ''

        patient_blood_type = self.blood_type or ''

        patient_rh = self.rh or ''

        patient_gender = self.gender or ''

        patient_dob = self.dob or ''

        patient_id = self.puid or ''

        if self.lastname:
            patient_lastname = self.lastname + ', '
        else:
            patient_lastname = ''

        qr_string = 'ID: ' + patient_id \
            + '\nName: ' + patient_lastname + ',' \
                + self.name.name \
            + '\nPUID: ' + patient_puid \
            + '\nGender: ' + patient_gender \
            + '\nDoB: ' + str(patient_dob) \
            + '\nBlood Type: ' + patient_blood_type \
                + ' ' + patient_rh


        qr_image = qrcode.make(qr_string)

        # Make a PNG image from PIL without the need to create a temp file

        holder = StringIO.StringIO()
        qr_image.save(holder)
        qr_png = holder.getvalue()
        holder.close()

        return bytearray(qr_png)

# Add the QR code field and image to the Newborn
项目:gnuhealth-live    作者:kret0s    | 项目源码 | 文件源码
def make_qrcode(self, name):
    # Create the QR code

        if self.mother:
            if self.mother.name.lastname:
                newborn_mother_lastname = self.mother.name.lastname + ', '
            else:
                newborn_mother_lastname = ''

            newborn_mother_name = self.mother.name.name or ''

            newborn_mother_id = self.mother.puid or ''

        else:
            newborn_mother_lastname = ''
            newborn_mother_name = ''
            newborn_mother_id = ''

        newborn_name = self.name or ''

        newborn_sex = self.sex or ''

        newborn_birth_date = self.birth_date or ''

        qr_string = 'PUID: ' + newborn_name \
            + '\nMother: ' + newborn_mother_lastname \
                    + newborn_mother_name \
            + '\nMother\'s PUID: ' + newborn_mother_id \
            + '\nSex: ' + newborn_sex \
            + '\nDoB: ' + str(newborn_birth_date)


        qr_image = qrcode.make(qr_string)

        # Make a PNG image from PIL without the need to create a temp file

        holder = StringIO.StringIO()
        qr_image.save(holder)
        qr_png = holder.getvalue()
        holder.close()

        return bytearray(qr_png)
项目:bitcoin_tools    作者:sr-gi    | 项目源码 | 文件源码
def sk_to_wif(sk, compressed=True, mode='image', v='test'):
    """ Generates a Wallet Import Format (WIF) representation of a provided elliptic curve private key.

    :param sk: elliptic curve private key.
    :type sk: hex str
    :param compressed: Whether the WIF will be used with a compressed or uncompressed public key
    :type compressed: bool
    :param mode: defines the type of return.
    :type mode: str
    :param v: version (prefix) used to calculate the WIF, it depends on the type of network.
    :type v: str
    :return: The WIF representation of the private key.

        - main network WIF if v is 'main'.
        - testnet WIF otherwise.
    :rtype:

        - qrcode is mode is 'image'.
        - str otherwise.
    """

    # Choose the proper version depending on the provided 'v'.
    if v in ['mainnet', 'main']:
        v = WIF
    elif v in ['testnet', 'test']:
        v = TESTNET_WIF
    else:
        raise Exception("Invalid version, use either 'main' or 'test'.")

    # Add the network version leading the private key (in hex).
    e_pkey = chr(v) + unhexlify(sk)
    # Flag compressed pk when needed
    if compressed:
        e_pkey += unhexlify('01')
    # Double sha256.
    h = sha256(sha256(e_pkey).digest()).digest()
    # Add the two first bytes of the result as a checksum tailing the encoded key.
    wif = e_pkey + h[0:4]
    # Enconde the result in base58.
    wif = b58encode(wif)

    # Choose the proper return mode depending on 'mode'.
    if mode is 'image':
        response = qr_make(wif)
    elif mode is 'text':
        response = wif
    else:
        raise Exception("Invalid mode, used either 'image' or 'text'.")

    return response