Skip to content

Instantly share code, notes, and snippets.

@h2rd
Created October 24, 2013 16:00
Show Gist options
  • Save h2rd/7139932 to your computer and use it in GitHub Desktop.
Save h2rd/7139932 to your computer and use it in GitHub Desktop.
from argparse import ArgumentParser
from math import sqrt
from urllib import urlencode
import sys
MAX_SIZE = 300000
def main():
parser = ArgumentParser(
description='Generate a QR code using Google Chart Tools.')
parser.add_argument('--encoding',
choices=['UTF-8', 'Shift_JIS', 'ISO-8859-1'], default='UTF-8')
parser.add_argument('--height', type=int)
parser.add_argument('--level', choices='LMQH', default='L')
parser.add_argument('--margin', default=4, type=int)
parser.add_argument('--width', type=int)
parser.add_argument('data')
args = parser.parse_args()
if args.height is None and args.width is None:
args.height = args.width = 512
elif args.height is not None and args.width is None:
args.width = args.height
elif args.width is not None and args.height is None:
args.height = args.width
if args.width * args.height > MAX_SIZE:
ratio = args.width / float(args.height)
args.width = int(sqrt(MAX_SIZE * ratio))
args.height = int(sqrt(MAX_SIZE / ratio))
print '{url}?{parameters}'.format(
url='https://chart.googleapis.com/chart',
parameters=urlencode({
'cht': 'qr',
'chs': '{width}x{height}'.format(
width=args.width, height=args.height),
'chl': args.data,
'choe': args.encoding,
'chld': '{level}|{margin}'.format(
level=args.level, margin=args.margin),
}),
)
if __name__ == '__main__':
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment