我们从Python开源项目中,提取了以下45个代码示例,用于说明如何使用pyqrcode.create()。
def showQR(addr, errcorr): # generate QR code and display on LED grid code = pyqrcode.create(addr, error=errcorr, version=3) t = code.text(1) row = 31 col = 0 bufferInit() for i in t: if i != '\n': bufferPixel(row, col, 255-int(i)*255, 255-int(i)*255, 255-int(i)*255) col += 1 else: row -= 1 col = 0 bufferDraw() #time.sleep(0.001) # give us a chance to scan it time.sleep(QRTIME) # draw blocks since last difficulty adjustment
def create_qrcode(data='QR Code Symbol'): """qrcode create""" qr = QRCode(error_correction=ERROR_CORRECT_M) qr.add_data(data, optimize=False) qr.make()
def create_pyqrcode(data='QR Code Symbol'): """PyQRCode create""" pyqrcode.create(data, error='m')
def svg_pyqrcode(data='QR Code Symbol'): """PyQRCode SVG""" pyqrcode.create(data, error='m').svg('out/pyqrcode_%s.svg' % data, scale=10)
def png_pyqrcode(data='QR Code Symbol'): """PyQRCode PNG""" pyqrcode.create(data, error='m').png('out/pyqrcode_%s.png' % data, scale=10)
def create_qrcodegen(data='QR Code Symbol'): """qrcodegen create""" QrCode.encode_text(data, QrCode.Ecc.MEDIUM)
def twofactor_qrcode(): """Return a QRcode of the TOTP URI for the current user""" user = User.query.filter_by(id=current_user.id).first_or_404() url = pyqrcode.create(user.get_totp_uri()) stream = BytesIO() url.svg(stream, scale=5) return stream.getvalue(), 200, { 'Content-Type': 'image/svg+xml', 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0' }
def gen_qr_code(self, qr_file_path): string = 'https://login.weixin.qq.com/l/' + self.uuid qr = pyqrcode.create(string) if self.conf['qr'] == 'png': qr.png(qr_file_path, scale=8) show_image(qr_file_path) # img = Image.open(qr_file_path) # img.show() elif self.conf['qr'] == 'tty': print(qr.terminal(quiet_zone=1))
def gen_qr_code(self, qr_file_path): string = 'https://login.weixin.qq.com/l/' + self.uuid qr = pyqrcode.create(string) if self.conf['qr'] == 'png': qr.png(qr_file_path, scale=8) show_image(qr_file_path) # img = Image.open(qr_file_path) # img.show() elif self.conf['qr'] == 'tty': qr.png(qr_file_path, scale=8) print(qr.terminal(quiet_zone=1))
def qr_by_account(account): account = 'xrb:{0}'.format(account) path = '{1}{0}.png'.format(account, qr_folder_path) if (not os.path.isfile(path)): qr = pyqrcode.create(account, error='L', version=4, mode=None, encoding='iso-8859-1') qr.png('{1}{0}.png'.format(account, qr_folder_path), scale=8)
def gen_qr_code(self, qr_file_path): string = 'https://login.weixin.qq.com/l/' + self.uuid qr = pyqrcode.create(string) if self.conf['qr'] == 'png': qr.png(qr_file_path, scale=5) self.show_image(qr_file_path) # img = Image.open(qr_file_path) # img.show() elif self.conf['qr'] == 'tty': print(qr.terminal(quiet_zone=1))
def create_qr_code(data): buffer = io.BytesIO() qr_code = pyqrcode.create(data) qr_code.svg(buffer, scale=10) logging.info('QR code created') return buffer
def run_backup(self, args): """Run the backup operation.""" chunksize = args.chunksize encodefunc = base64.b85encode #FIXME: add arg infile = open(args.infile, "rb") infile_size = os.path.getsize(infile.name) outfile = args.outfile inputhash = hashlib.sha256() framedata = self.frame_data_func(args) qr_count = infile_size / chunksize + 1 self.logger.info('Original file size: %dKiB', infile_size / 1024) self.logger.info('Total number of QR codes: %d', qr_count) exporter = self.setup_exporter(args, qr_count) qr_number = 0 sizesofar = 0 while True: bindata = infile.read(chunksize) if not bindata: break frame = framedata(bindata, qr_count, sizesofar) inputhash.update(bindata) sizesofar += len(bindata) qr_number += 1 self.logger.info('Exporting QR %d of %d', qr_number, qr_count) encdata = encodefunc(frame).decode() qr = pyqrcode.create(encdata) exporter.add_qr(qr) exporter.finish(inputhash) self.logger.info('Finished exporting') if args.sha256: print('SHA-256 of input: %s' % inputhash.hexdigest())
def shorten_url(long_url): url_data = parse.urlencode(dict(url=long_url)) byte_data = str.encode(url_data) ret = request.urlopen("http://tinyurl.com/api-create.php", data=byte_data).read() result = str(ret)[2:-1] return result
def make_qrcode_image(url,path='',event=None): try: url = shorten_url(url) if event: ID = event qr = pyqrcode.create(url,version=15) else: ID = hashlib.md5(url.encode('utf8')).hexdigest() qr = pyqrcode.create(url,version=15) file_name = os.path.join(path,'%s.png' % ID) qr.png(file_name,scale=4) return ID except Exception as e: print(str(e)) return -1
def gen_qr_code(self, qr_file_path): string = 'https://login.weixin.qq.com/l/' + self.uuid qr = pyqrcode.create(string) if self.conf['qr'] == 'png': qr.png(qr_file_path, scale=8) show_image(qr_file_path) # img = Image.open(qr_file_path) # img.show() elif self.conf['qr'] == 'tty': print(qr.terminal(quiet_zone=4))
def _get_qr_code(**get_params): data = get_params['url'] qr = pyqrcode.create('www.google.comwww.google.comwww.google.comUnladden swallow') return dict(binary_array=qr.code)
def create_QR_image(text, scale): full_QR_path = os.getcwd() + '/img/QRcode.png' url = pyqrcode.create(text) url.png(full_QR_path, scale) print('Create QR Code succes in here: ' + full_QR_path) print(url.text())
def returnQRCodeText(self, validURL): objectQRCode = pyqrcode.create(validURL) return objectQRCode.text()
def saveQRCodeSVG(self, validURL, filename, imageDirectory=None): fullfilename = imageDirectory + filename if imageDirectory is not None else filename objectQRCode = pyqrcode.create(validURL) objectQRCode.svg(fullfilename + ".svg", scale=4) # in-memory stream is also supported buffer = io.BytesIO() objectQRCode.svg(buffer) # do whatever you want with buffer.getvalue() print(list(buffer.getvalue()))
def saveQRCodePNG(self, validURL, filename, imageDirectory=None): fullfilename = imageDirectory + filename if imageDirectory is not None else filename objectQRCode = pyqrcode.create(validURL) with open(fullfilename + ".png", 'wb') as fstream: objectQRCode.png(fstream, scale=5) # same as above objectQRCode.png(fullfilename + ".png", scale=5) # in-memory stream is also supported buffer = io.BytesIO() objectQRCode.png(buffer) # do whatever you want with buffer.getvalue() print(list(buffer.getvalue()))
def showQR(): global rpc_connection print "Loading 2nd bitcoin address..." # connect to node and get new wallet address try: addr = rpc_connection.getnewaddress() except (socket.error, httplib.CannotSendRequest): print "showQR Timeout" initRPC() return False # bypass rpc for testing #addr = '1CepbXDXPeJTsk9PUUKkXwfqcyDgmo1qoE' # generate QR code and display on LED grid code = pyqrcode.create(addr, error='M', version=3) t = code.text(1) print addr # print the actual QR code to terminal with 1's and 0's print t row = 31 col = 0 matrix.Clear() for i in t: if i != '\n': matrix.SetPixel(row, col, 255-int(i)*255, 255-int(i)*255, 255-int(i)*255) col += 1 else: row -= 1 col = 0 time.sleep(0.001) # give us a chance to scan it time.sleep(5) return True
def getOtp( self ): totp = session._tmp_otp totpImg = None if totp is not None: totpImg = 'data:image/png;base64,%s' % pyqrcode.create( totp ).png_as_base64_str( scale = 4 ) return ( totp, totpImg )
def doPOST( self ): params = web.input( oid = None, iid = None, tags = '', desc = '' ) try: oid = uuid.UUID( params.oid ) except: oid = None try: if params.iid is not None: iid = uuid.UUID( params.iid ) else: # If no IID is present it indicates to create a new one. iid = None except: iid = None if oid is None: raise web.HTTPError( '400 Bad Request: oid required' ) if not isOrgAllowed( oid ): raise web.HTTPError( '401 Unauthorized' ) tags = [ x.strip() for x in params.tags.split( ',' ) ] resp = deployment.request( 'set_installer_info', { 'oid' : oid, 'iid' : iid, 'tags' : tags, 'desc' : params.desc } ) if resp.isSuccess: redirectTo( 'manage' ) else: raise web.HTTPError( '503 Service Unavailable: %s' % str( resp ) )
def _qrcode_from_signify_ed25519_pubkey(pubkey_file, mode='text'): """ Usage: 1. Get the OpenBSD 5.7 release public key from here http://cvsweb.openbsd.org/cgi-bin/cvsweb/src/etc/signify/Attic/openbsd-57-base.pub?rev=1.1 2. Generate QR Code and print to terminal print(cryptosign._qrcode_from_signify_ed25519_pubkey('openbsd-57-base.pub')) 3. Compare to (scroll down) QR code here https://www.openbsd.org/papers/bsdcan-signify.html """ assert(mode in ['text', 'svg']) import pyqrcode with open(pubkey_file) as f: pubkey = f.read().splitlines()[1] qr = pyqrcode.create(pubkey, error='L', mode='binary') if mode == 'text': return qr.terminal() elif mode == 'svg': import io data_buffer = io.BytesIO() qr.svg(data_buffer, omithw=True) return data_buffer.getvalue() else: raise Exception('logic error')
def qrcode_from_totp(secret, label, issuer): if type(secret) != six.text_type: raise Exception('secret must be of type unicode, not {}'.format(type(secret))) if type(label) != six.text_type: raise Exception('label must be of type unicode, not {}'.format(type(label))) try: import pyqrcode except ImportError: raise Exception('pyqrcode not installed') import io buffer = io.BytesIO() data = pyqrcode.create(u'otpauth://totp/{}?secret={}&issuer={}'.format(label, secret, issuer)) data.svg(buffer, omithw=True) return buffer.getvalue() # # The following code is adapted from the pbkdf2_bin() function # in here https://github.com/mitsuhiko/python-pbkdf2 # Copyright 2011 by Armin Ronacher. Licensed under BSD license. # https://github.com/mitsuhiko/python-pbkdf2/blob/master/LICENSE #
def handle_payment(uuid, address, satoshis, wallet_command, currency): """ Payment handling routine for spawn and topup. """ if wallet_command is not None: full_wallet_command = '{} {} {} >&2'.format(wallet_command, address, satoshis) if os.system(full_wallet_command) != 0: raise return True amount = "{0:.8f}".format(satoshis * 0.00000001) if currency == 'btc': uri = 'bitcoin:{}?amount={}'.format(address, amount) elif currency == 'bch': uri = 'bitcoincash:{}?amount={}'.format(address, amount) else: raise ValueError('Currency must be one of: btc, bch') premessage = '''UUID: {} Bitcoin URI: {} Pay with Bitcoin *within an hour*. QR code will change every so often but the current and previous QR codes are both valid for about an hour. The faster you make payment, the better. Pay *exactly* the specified amount. No more, no less. Resize your terminal and try again if QR code above is not readable. Press ctrl+c to abort.''' message = premessage.format(uuid, uri) qr = pyqrcode.create(uri) stderr(qr.terminal(module_color='black', background='white', quiet_zone=1)) stderr(message)
def getQRCode(request, music_id): # generate token - save to database # generate URL with token --> this will be a QR code to be displayed newMusic = Music.objects.get(id=music_id) stringToHash = str(time.time()) + str(newMusic.artist) + str(newMusic.title) h = hashlib.sha1() h.update(stringToHash) tokenToAppendinURL = str(h.hexdigest()) # save music query to database newQuery = MusicQuery(query=newMusic, token=tokenToAppendinURL) newQuery.save() #QR code to be displayed # url = pyqrcode.create('http://35.163.220.222:8000/musician/music/' + tokenToAppendinURL) # url = pyqrcode.create('http://54.209.248.145:8000/musician/music/' + tokenToAppendinURL) # url = pyqrcode.create('http://localhost:8000/musician/music/' + tokenToAppendinURL) url = pyqrcode.create(settings.ROOT_URL + '/musician/music/' + tokenToAppendinURL) # image_as_str = code.png_as_base64_str(scale=5) # html_img = '<img src="data:image/png;base64,{}">'.format(image_as_str) strToSave = 'musician/static/images/' + tokenToAppendinURL + '.png' url.png(strToSave, scale=6) strToShow = '/static/images/' + tokenToAppendinURL + '.png' x = json.dumps({'qrpath': strToShow}) return JsonResponse(x, safe=False) # executed on QR code url
def download(request, token): context = {} if request.method == 'GET': try: # check token in database and retrieve corresponding music targetQuery = MusicQuery.objects.get(token=token) targetMusic = targetQuery.query file_name = targetMusic.file_name dir_path = os.path.dirname(os.path.realpath(__file__)) file_path = dir_path + '/music/' + file_name file_wrapper = FileWrapper(file(file_path, 'rb')) file_mimetype = mimetypes.guess_type(file_path) # store the download record newDownload = Download.objects.create(music=targetMusic, download_loc='') newDownload.save() # download the music file response = HttpResponse(file_wrapper, content_type=file_mimetype) response['X-Sendfile'] = file_path response['Content-Length'] = os.stat(file_path).st_size response['Content-Disposition'] = 'attachment; filename=' + file_name targetQuery.delete() return response except Exception as e: messages.add_message(request, messages.ERROR, "Music Download Failed: QR Code Expired") logging.exception("message") return redirect('/musician') else: return redirect('/musician') # artist upload handler
def showResult(self, message, url=None): if url: imagefile = os.path.join(xbmc.translatePath(PROFILE),'%s.png'%str(url.split('/')[-2])) qrIMG = pyqrcode.create(url) qrIMG.png(imagefile, scale=10) qr = QRCode( "script-loguploader-main.xml" , CWD, "default", image=imagefile, text=message) qr.doModal() del qr xbmcvfs.delete(imagefile) else: dialog = xbmcgui.Dialog() confirm = dialog.ok(ADDONNAME, message)
def admin_user_add(): u = user.User() u.username, u.salted_password, u.sskey = [request.forms.get(n) for n in ('username', 'password', 'sskey')] u.create() u.write() return { "id": u.id }
def postprocess_pdf(input_pdf, qr_data, qr_x=545, qr_y=20, version=None): """ PDF post-processor. Append QR code on each PDF page. :param input_pdf: PDF byte content :param qr_data: QR code data :param qr_x: X possition of QR image :param qr_y: Y possition of QR image """ qr = pyqrcode.create(qr_data, version=version) eps = StringIO() qr.eps(eps) eps.seek(0) qr_pdf = BytesIO() qr_img = Image(file=BytesIO(bytes(eps.read(), 'utf-8'))) qr_img.format = 'pdf' qr_img.save(qr_pdf) qr_page = PdfFileReader(qr_pdf).getPage(0) output_writer = PdfFileWriter() output_pdf = BytesIO() for page in PdfFileReader(BytesIO(input_pdf)).pages: page.mergeTranslatedPage(qr_page, qr_x, qr_y) output_writer.addPage(page) output_writer.write(output_pdf) output_pdf.seek(0) return output_pdf.read()
def save(self, **kwargs): """overrides the save method for the model """ request = pyqrcode.create( '{0}.{1}'.format(str(self.uuid), self.price), version=10 ) encoded_request = request.png_as_base64_str() image = Image.open( BytesIO(base64.b64decode(encoded_request.encode())) ) filename = '{0}.{1}'.format( str(time.time())[:10], (image.format).lower() ) memory_image = BytesIO() image.save(memory_image, format=image.format) qr_file = InMemoryUploadedFile( memory_image, None, filename, 'image/png', memory_image.tell, None ) self.commodity_qr.save( filename, qr_file, save=False, ) super(Commodity, self).save(**kwargs)
def gen_qr_code(self, qr_file_path): string = 'https://login.weixin.qq.com/l/' + self.uuid qr = pyqrcode.create(string) if self.conf['qr'] == 'png': qr.png(qr_file_path, scale=8) show_image(qr_file_path) elif self.conf['qr'] == 'tty': ret = qr.terminal(quiet_zone=1) print ret
def show_qr_image(self): self.logger.debug('begin to show qr image') url = 'https://qrlogin.taobao.com/qrcodelogin/generateQRCode4Login.do?from=alimama&_ksTS=%s_30&callback=jsonp31' % int( time.time() * 1000) # get qr image headers = { 'method': 'GET', 'authority': 'qrlogin.taobao.com', 'scheme': 'https', 'path': '/qrcodelogin/generateQRCode4Login.do?%s' % url.split('generateQRCode4Login.do?')[-1], 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'accept': '*/*', 'referer': 'https://login.taobao.com/member/login.jhtml?style=mini&newMini2=true&from=alimama&redirectURL=http%3A%2F%2Flogin.taobao.com%2Fmember%2Ftaobaoke%2Flogin.htm%3Fis_login%3d1&full_redirect=true&disableQuickLogin=true', 'accept-encoding': 'gzip, deflate, sdch, br', 'accept-language': 'zh-CN,zh;q=0.8', } res = self.get_url(url, headers=headers) rj = json.loads(res.text.replace('(function(){jsonp31(', '').replace(');})();', '')) lg_token = rj['lgToken'] url = 'https:%s' % rj['url'] headers = { 'method': 'GET', 'authority': 'img.alicdn.com', 'scheme': 'https', 'path': '/tfscom/%s' % url.split('tfscom/')[-1], 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'accept': 'image/webp,image/*,*/*;q=0.8', 'referer': 'https://login.taobao.com/member/login.jhtml?style=mini&newMini2=true&from=alimama&redirectURL=http%3A%2F%2Flogin.taobao.com%2Fmember%2Ftaobaoke%2Flogin.htm%3Fis_login%3d1&full_redirect=true&disableQuickLogin=true', 'accept-encoding': 'gzip, deflate, sdch, br', 'accept-language': 'zh,en-US;q=0.8,en;q=0.6,zh-CN;q=0.4,zh-TW;q=0.2', } res = self.get_url(url, headers=headers) qrimg = BytesIO(res.content) sysstr = platform.system() if (sysstr == "Windows"): # windows????????????? img = Image.open(qrimg) img.show() elif (sysstr == "Linux") or (sysstr == "Darwin"): # ??url import zbarlight img = Image.open(qrimg) codes = zbarlight.scan_codes('qrcode', img) qr_url = codes[0] # ??pyqrcode????????linux???? pyqrcode_url = pyqrcode.create(qr_url) print (pyqrcode_url.terminal()) self.logger.debug(u"??????????") return lg_token # do login