本文整理汇总了Python中pyqrcode.create函数的典型用法代码示例。如果您正苦于以下问题:Python create函数的具体用法?Python create怎么用?Python create使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了create函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_to_str
def test_to_str():
s = 'Märchen'
ok_(str(pyqrcode.create(s)))
s = '外来語'
qr = pyqrcode.create(s)
ok_(str(pyqrcode.create(s)))
示例2: test_kanji_enforce_binary
def test_kanji_enforce_binary():
data = '点'
# 1. Try usual mode --> kanji
qr = pyqrcode.create(data)
eq_('kanji', qr.mode)
# 2. Try another encoding --> binary
qr = pyqrcode.create(data, mode='binary', encoding='utf-8')
eq_('binary', qr.mode)
示例3: test_unicode_utf8
def test_unicode_utf8():
s = '\u263A' # ☺ (WHITE SMILING FACE)
try:
pyqrcode.create(s, encoding='latin1')
raise Exception('Expected an error for \u263A and ISO-8859-1')
except ValueError:
pass
qr = pyqrcode.create(s, encoding='utf-8')
eq_('binary', qr.mode)
示例4: decryptMiniProdFile
def decryptMiniProdFile(key):
# List files in the export folder
export_file_names = [f for f in listdir("export/") if isfile(join("export/", f))]
# Ask for Mooltipass ID
mooltipass_ids = raw_input("Enter Mooltipass ID: ")
# Generate a list with Mooltipass IDs
mooltipass_ids_list = mooltipass_ids.split(' ')
# Find Mooltipass ID in files
for mooltipass_id in mooltipass_ids_list:
for file_name in export_file_names:
if "Mooltipass-" + mooltipass_id + ".txt" in file_name:
print "Found export file:", file_name
data = pickle_read(join("export/",file_name))
decrypted_data = seccure.decrypt(data, key, curve='secp521r1/nistp521')
items = decrypted_data.split('|')
#print decrypted_data
# Mooltipass ID | aes key 1 | aes key 2 | request ID key | UID, flush write
if True:
# Print Mooltipass ID | aes key 1 | aes key 2 | request ID key | UID (might get quite big)
data_qr = pyqrcode.create(decrypted_data, error="L")
print(data_qr.terminal(quiet_zone=1))
raw_input("Press enter:")
else:
# This is just here in case you need it....
# key1
key1 = items[1]
key1_qr = pyqrcode.create(key1)
print ""
print "AES key 1:", key1
print(key1_qr.terminal(quiet_zone=1))
# key2
key2 = items[2]
key2_qr = pyqrcode.create(key2)
print ""
print "AES key 2:", key2
print(key2_qr.terminal(quiet_zone=1))
# Request UID
request = items[3]
request_qr = pyqrcode.create(request)
print "Request UID key:", request
print(request_qr.terminal(quiet_zone=1))
# UID
request = items[4]
request_qr = pyqrcode.create(request)
print "UID :", request
print(request_qr.terminal(quiet_zone=1))
示例5: getQRArray
def getQRArray(text, errorCorrection):
""" Takes in text and errorCorrection (letter), returns 2D array of the QR code"""
# White is True (1)
# Black is False (0)
# ECC: L7, M15, Q25, H30
# Create the object
qr = pyqrcode.create(text, error=errorCorrection)
# Get the terminal representation and split by lines (get rid of top and bottom white spaces)
plainOut = qr.terminal().split("\n")[5:-5]
# Initialize the output 2D list
out = []
for line in plainOut:
thisOut = []
for char in line:
if char == u'7':
# This is white
thisOut.append(1)
elif char == u'4':
# This is black, it's part of the u'49'
thisOut.append(0)
# Finally add everything to the output, stipping whitespaces at start and end
out.append(thisOut[4:-4])
# Everything is done, return the qr code list
return out
示例6: create_barcodes
def create_barcodes(file,delim):
currenttime=time.time()
tempfilename='temp_'+str(currenttime)
cwd = os.getcwd()
directory = str(cwd)+"/"+str(tempfilename)
path = str(directory)+"/"
barcodefile = str(file)
if not os.path.exists(directory):
os.makedirs(directory)
else:
raise RuntimeError("A temp directory of this name exists, fatal error.")
if delim=='tab':
delimvalue='\t'
elif delim=='comma':
delimvalue=','
else:
delimvalue=None
with open(barcodefile) as fileinput:
reader = csv.reader(fileinput, delimiter=delimvalue)
for row in reader:
barcodeqr=qr.create(str(row[0]))
currenttime1 = time.time()
barname=str(path)+str(currenttime1)+".png"
barcodeqr.png(barname , scale=2)
barcodepic=cv2.imread(barname)
barcodepic1=cv2.copyMakeBorder(barcodepic,10,20, 25, 25,cv2.BORDER_CONSTANT,value=(255,255,255))
ix,iy,iz=np.shape(barcodepic1)
cv2.putText(barcodepic1,str(row[1]),(25,ix-5),cv2.FONT_HERSHEY_SIMPLEX,0.4,(0,0,0))
cv2.imwrite(barname,barcodepic1)
return path
示例7: handle
def handle(self, request, data):
try:
user = fiware_api.keystone.user_get(request, request.user.id)
if request.POST.get(u'enable', None):
security_question = data['security_question']
security_answer = data['security_answer']
else:
security_question = security_answer = None
(key, uri) = fiware_api.keystone.two_factor_new_key(request=request,
user=user,
security_question=security_question,
security_answer=security_answer)
LOG.info('Enabled two factor authentication or new key requested')
# NOTE(@federicofdez) Fix this to always use redirect
if request.is_ajax():
context = {}
context['two_factor_key'] = key
qr = pyqrcode.create(uri, error='L')
qr_buffer = io.BytesIO()
qr.svg(qr_buffer, scale=3)
context['two_factor_qr_encoded'] = base64.b64encode(qr_buffer.getvalue())
context['hide'] = True
return shortcuts.render(request, 'settings/multisettings/_two_factor_newkey.html', context)
else:
cache_key = uuid.uuid4().hex
cache.set(cache_key, (key, uri))
request.session['two_factor_data'] = cache_key
messages.success(request, "Two factor authentication was successfully enabled.")
return shortcuts.redirect('horizon:settings:multisettings:newkey')
except Exception as e:
exceptions.handle(request, 'error')
LOG.error(e)
return False
示例8: qr
async def qr(app, request):
# Generate a QR code SVG and save it to a stream; we need at least version 8
# for the QR code
with io.BytesIO() as stream:
pyqrcode.create(
url(app['server'].configuration),
version=8).svg(
stream,
background='white',
omithw=True)
return Response(
status=200,
body=stream.getvalue(),
headers={
'Content-Type': 'image/svg+xml'})
示例9: gen_qr_code
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)
elif self.conf['qr'] == 'tty':
print(qr.terminal(quiet_zone=1))
示例10: test_custom_svg_class
def test_custom_svg_class():
qr = pyqrcode.create('test')
out = io.BytesIO()
qr.svg(out, svgclass='test-class')
root = _parse_xml(out)
ok_('class' in root.attrib)
eq_('test-class', root.attrib.get('class'))
示例11: qr_encode_material
def qr_encode_material(wallet_password_filename, wallet_material_name, qr_page_message):
import pyqrcode
qr = None
with open(wallet_password_filename, 'r') as fin:
qr = pyqrcode.create(fin.read(), version=40, error='M')
qr_temp_file_name = working_directory_name + "/qrtempfile.eps"
qr.eps(qr_temp_file_name, scale=2.5) # this will write the qrcode to the disk. only uncomment if you want that
#generate page
print_font = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeSerif.ttf", 16) #may want to play with this; very ubuntu specific.
qr = Image.open(qr_temp_file_name)
qr_page = Image.new("RGB", (850, 1100), 'white') # assuming an 8.5 x 11 page at 300 DPI, no margin, fully specified
# lay out the page
draw = ImageDraw.Draw(qr_page)
draw.text((10 ,10), ' /\_/\ ',(0,0,0),font=print_font)
draw.text((10 ,24), "(='.'=) meow offline material for wallet" + wallet_material_name ,(0,0,0),font=print_font)
draw.text((10,40), ' > ^ < ',(0,0,0),font=print_font)
draw.text((10,46), qr_page_message ,(0,0,0),font=print_font)
draw = ImageDraw.Draw(qr_page)
qr_page.paste(qr, (10, 70))
# uncomment these if you want a separate on-disk file of some sort. note we are not setting local directory here
# qr_temp_file_name_jpeg = working_directory_name + "/qrtempfile.jpeg"
# qr_page.save(qr_temp_file_name_jpeg, 'JPEG')
# print "temp sample QRcode jpeg file is " + qr_temp_file_name_jpeg
# debug = raw_input( 'press any key to continue...')
#test_page.save('test_page.png', 'PNG')
#test_page.save('test_page.bmp', 'BMP')
qr_print_success = "/"
while not qr_print_success.lower()[0] in ('y', 'r', 'q'):
try:
# generate the page
lpr = subprocess.Popen(["/usr/bin/lpr", '-E'], stdin=subprocess.PIPE)
output = StringIO.StringIO()
format = 'jpeg' # or 'JPEG' or whatever you want
qr_page.save(output, format)
lpr.communicate(output.getvalue())
output.close() # what happens when this is here?
qr_print_success = raw_input( 'Did the item ' + qr_page_message + ' print for wallet ' + wallet_material_name + ' successfully? (Yes | Retry | Quit)')
if qr_print_success.lower()[0] == 'q':
splash('goodbye!')
raise Exception('Program cancelled by User')
elif qr_print_success.lower()[0] == 'y':
return
elif qr_print_success.lower()[0] == 'r':
qr_print_success = "/"
except Exception as e:
print('Error attempting to print:' + str(e))
示例12: generate_QRcode
def generate_QRcode(self, text, escala):
qr = pyqrcode.create(text)
output = StringIO.StringIO()
qr.png(output, scale=escala)
result = output.getvalue().encode("base64")
# se devuelve un PNG codificado en base64
return result
示例13: setTwoFactorMethod
def setTwoFactorMethod(self, user_dn, factor_method, user_password=None):
if factor_method == "u2f":
print(_("checking U2F devices..."))
# check for devices
devices = u2f.list_devices()
if len(devices) == 0:
print(_("No U2F devices found, aborting!"))
return
response = self.proxy.setTwoFactorMethod(user_dn, factor_method, user_password)
if response is None:
return
if factor_method == "u2f":
# bind
response = loads(response)
for device in devices:
# The with block ensures that the device is opened and closed.
print(_("Please touch the flashing U2F device now."))
with device as dev:
# Register the device with some service
for request in response['registerRequests']:
registration_response = u2f.register(device, request, request['appId'])
response = self.proxy.completeU2FRegistration(user_dn, registration_response)
if response is True:
print(_("U2F authentication has been enabled"))
elif response.startswith("otpauth://"):
url = pyqrcode.create(response, error='L')
print(url.terminal(quiet_zone=1))
else:
print(response)
示例14: generateQrCode
def generateQrCode(request):
if request.method == 'POST':
form = ToPhoneForm(request.POST)
if form.is_valid():
# process data
print "\n\nProcessing data..."
print form.cleaned_data
link_val = form.cleaned_data.get('copy_value', None)
# short circuit if no value exists, this should never happen
# because the form will not validate without input
if not link_val:
return render(request, 'tophone.html', {'form': ToPhoneForm()})
qrcode = pyqrcode.create(link_val)
uuid_val = uuid() # third-party short, url-safe uuid generator
img_name = "qrcoderepo/svg/%s.svg" % uuid_val
print img_name
qrcode.svg(img_name, scale=8)
print "svg image created"
return HttpResponseRedirect(uuid_val + '/')
else:
form = ToPhoneForm()
return render(request, 'tophone.html', {'form': form})
示例15: qr
def qr( qr_id=None ):
if qr_id:
if request.method == "GET":
width = request.args.get('width', '800')
height = request.args.get('height', '600')
table = db.session.query(Table).filter(Table.id == qr_id).first()
if table is None:
return jsonify({'msg': 'None'}), 404
svg = render_template( str(qr_id) + '.svg', width=width, height=height)
response = make_response(svg)
response.content_type = 'image/svg+xml'
return response
if request.method == "POST":
if qr_id > 20 : qr_id =20
total = db.session.query(Table).count()
import pyqrcode
for i in range( qr_id - total ):
table = Table( str( total + i + 1) )
db.session.add(table)
qr = pyqrcode.create( table.orderUrl())
qr.svg('templates/' + str( total + i + 1) + '.svg', scale=8)
else:
db.session.commit()
table = db.session.query(Table).filter(Table.id == qr_id).first()
form = TableDescriptionForm(request.form)
form.validate()
table.description = form.description
form.populate_obj( table)
db.session.add(table)
db.session.commit()
if request.is_xhr:
tables = db.session.query(Table)
result = tables_schema.dump(tables)
return jsonify({'tables': result.data})
return render_template('QRs.html', form=TableDescriptionForm(), title='QR')