Para automatizar la generación de códigos QR asociados a determinadas URL, he creado este pequeño guión en Python que, dada un URL y, opcionalmente, un nombre de fichero, guarda en dicho fichero el código QR creado a partir de la URL.
Es muy sencillo, pero me gustaría remarcar la regexp que comprueba la validez de la URL:
- Los carácteres ‘^‘ y ‘$‘ marcan el inicio y final de la cadena, respectivamente.
- «(https?|ftp)://» indica el protocolo. Se pueden poner muchos más (en esta expresión están http, https y ftp).
- «(www|ftp).)[a-z0-9-]+(.[a-z0-9-]+)+» Nombre y dominio
- «([/?].*)?» El path y parámetros que pueda haber.
Lo único que no permite es poner el usuario y contraseña. Si alguien lo hace, que la deje modificada en los comentarios 😉
Aquí tenéis el guión:
#!/usr/bin/python try: import qrcode except: print("Error: import qrcode. You have install it: sudo pip install pil qrcode") import optparse,sys,re parser = optparse.OptionParser("usage%prog " + "-u <URL> [-s <file to save qr code>]") parser.add_option('-u', dest = 'url', type = 'string', help = 'Please, specify the url to convert to QR code.') parser.add_option('-s', dest = 'file', type = 'string') parser.add_option('-t', dest = 'size', type = 'string') (options, args) = parser.parse_args() if (options.url == None): print '[-] You must specify a url to convert to QR code.' exit(0) if (re.match("^((https?|ftp)://|(www|ftp).)[a-z0-9-]+(.[a-z0-9-]+)+([/?].*)?$",options.url)): url=options.url else: print("%s is not a correct URL" % options.url) exit(2) if (options.file == None): if (re.search("http[s]?://", options.url)): file="./"+url.split('/')[2]+".png" elif (re.search("/", options.url)): file="./"+url.split('/')[0]+".png" else: file="./"+url+".png" else: file=options.file if (options.size == None): size=5 else: size=options.size qr=qrcode.QRCode(version=20, error_correction=qrcode.constants.ERROR_CORRECT_L,box_size=size) qr.add_data(url) qr.make try: image=qr.make_image() image.save(file) except OSError, e: print 'Error writing QR code file '+e[1] except: print("Error writing QR code file")
Referencias:
- https://pypi.python.org/pypi/qrcode
- Python para todos, de Raúl González Duque