def test_size(self): base_ref_file_name = 'qrfromtext_size' sizes = [ 't', 'T', 's', 'S', None, -1, 0, 'm', 'M', 'l', 'L', 'h', 'H', '6', 6, '8', 8, '10', 10 ] size_names = ['tiny'] * 2 + ['small'] * 2 + ['medium'] * 5 + [ 'large' ] * 2 + ['huge'] * 2 + ['6'] * 2 + ['8'] * 2 + ['10'] * 2 for i in range(len(sizes)): size = sizes[i] print('Testing SVG with size %s' % size) size_name = size_names[i] qr1 = make_embedded_qr_code(TEST_TEXT, QRCodeOptions(size=size)) qr2 = qr_from_text(TEST_TEXT, size=size) qr3 = qr_from_text(TEST_TEXT, size=size, image_format='svg') qr4 = qr_from_text(TEST_TEXT, options=QRCodeOptions(size=size, image_format='svg')) qr5 = qr_from_text(TEST_TEXT, size=size, image_format='invalid-format-name') result_file_name = '%s_%s' % (base_ref_file_name, size_name) if REFRESH_REFERENCE_IMAGES: write_svg_content_to_file(result_file_name, qr1) result = get_svg_content_from_file_name(result_file_name) self.assertEqual(qr1, qr2) self.assertEqual(qr1, qr3) self.assertEqual(qr1, qr4) self.assertEqual(qr1, qr5) self.assertEqual(qr1, result)
def test_size(self): base_ref_file_name = 'qrfromtext_size' sizes = [ 't', 'T', 's', 'S', None, -1, 0, 'm', 'M', 'l', 'L', 'h', 'H', '6', 6, '8', 8, '10', 10 ] size_names = ['tiny'] * 2 + ['small'] * 2 + ['medium'] * 5 + [ 'large' ] * 2 + ['huge'] * 2 + ['6'] * 2 + ['8'] * 2 + ['10'] * 2 for i in range(len(sizes)): size = sizes[i] print('Testing PNG with size %s' % size) size_name = size_names[i] result_file_name = '%s_%s' % (base_ref_file_name, size_name) qr1 = make_embedded_qr_code( TEST_TEXT, QRCodeOptions(size=size, image_format='png')) qr2 = qr_from_text(TEST_TEXT, size=size, image_format='png') qr3 = qr_from_text(TEST_TEXT, options=QRCodeOptions(size=size, image_format='png')) if REFRESH_REFERENCE_IMAGES: match = IMAGE_TAG_BASE64_DATA_RE.search(qr1) source_image_data = match.group('data') write_png_content_to_file(result_file_name, base64.b64decode(source_image_data)) result = base64.b64encode( get_png_content_from_file_name(result_file_name)).decode( 'utf-8') self.assertEqual(qr1, qr2) self.assertEqual(qr1, qr3) self.assertEqual(qr1, BASE64_PNG_IMAGE_TEMPLATE % result)
def test_version(self): base_file_name = "qrfromtext_version" versions = [ None, -1, 0, 41, '-1', '0', '41', 'blabla', 1, '1', 2, '2', 4, '4' ] version_names = ['default'] * 10 + ['2', '2', '4', '4'] for i in range(len(versions)): version = versions[i] print('Testing PNG with version %s' % version) version_name = version_names[i] qr1 = make_embedded_qr_code( TEST_TEXT, QRCodeOptions(version=version, image_format='png')) qr2 = qr_from_text(TEST_TEXT, version=version, image_format='png') qr3 = qr_from_text(TEST_TEXT, version=version, image_format='PNG') qr4 = qr_from_text(TEST_TEXT, options=QRCodeOptions(version=version, image_format='PNG')) result_file_name = '%s_%s' % (base_file_name, version_name) if REFRESH_REFERENCE_IMAGES: match = IMAGE_TAG_BASE64_DATA_RE.search(qr1) source_image_data = match.group('data') write_png_content_to_file(result_file_name, base64.b64decode(source_image_data)) result = base64.b64encode( get_png_content_from_file_name(result_file_name)).decode( 'utf-8') self.assertEqual(qr1, qr2) self.assertEqual(qr1, qr3) self.assertEqual(qr1, qr4) self.assertEqual(qr1, BASE64_PNG_IMAGE_TEMPLATE % result)
def test_version(self): base_file_name = "qrfromtext_version" versions = [ None, -1, 0, 41, '-1', '0', '41', 'blabla', 1, '1', 2, '2', 4, '4' ] version_names = ['default'] * 10 + ['2', '2', '4', '4'] for i in range(len(versions)): version = versions[i] print('Testing SVG with version %s' % version) version_name = version_names[i] qr1 = make_embedded_qr_code(TEST_TEXT, QRCodeOptions(version=version)) qr2 = qr_from_text(TEST_TEXT, version=version) qr3 = qr_from_text(TEST_TEXT, version=version, image_format='svg') qr4 = qr_from_text(TEST_TEXT, version=version, image_format='SVG') qr5 = qr_from_text(TEST_TEXT, options=QRCodeOptions(version=version, image_format='SVG')) qr6 = qr_from_text(TEST_TEXT, version=version, image_format='invalid-format-name') result_file_name = '%s_%s' % (base_file_name, version_name) if REFRESH_REFERENCE_IMAGES: write_svg_content_to_file(result_file_name, qr1) result = get_svg_content_from_file_name(result_file_name) self.assertEqual(qr1, qr2) self.assertEqual(qr1, qr3) self.assertEqual(qr1, qr4) self.assertEqual(qr1, qr5) self.assertEqual(qr1, qr6) self.assertEqual(qr1, result)
def test_qr_code_options(self): with self.assertRaises(TypeError): QRCodeOptions(foo='bar') options = QRCodeOptions() self.assertEqual(options.border, 4) self.assertEqual(options.size, DEFAULT_MODULE_SIZE) self.assertEqual(options.image_format, DEFAULT_IMAGE_FORMAT) self.assertEqual(options.version, DEFAULT_VERSION) self.assertEqual(options.error_correction, DEFAULT_ERROR_CORRECTION) options = QRCodeOptions(image_format='invalid-image-format') self.assertEqual(options.image_format, DEFAULT_IMAGE_FORMAT)
def test_png_url(self): is_first = True for url_options in product([True, False, None], [True, False, None]): cache_enabled = url_options[0] url_signature_enabled = url_options[1] url_options_kwargs = dict() if cache_enabled is not None: url_options_kwargs['cache_enabled'] = cache_enabled if url_signature_enabled is not None: url_options_kwargs[ 'url_signature_enabled'] = url_signature_enabled url1 = make_qr_code_url(TEST_TEXT, QRCodeOptions(image_format='png', size=1), **url_options_kwargs) url2 = qr_url_from_text(TEST_TEXT, image_format='png', size=1, **url_options_kwargs) url3 = qr_url_from_text(TEST_TEXT, image_format='PNG', size=1, **url_options_kwargs) url4 = qr_url_from_text(TEST_TEXT, options=QRCodeOptions(image_format='PNG', size=1), **url_options_kwargs) url = url1 if url_signature_enabled is not False: urls = get_urls_without_token_for_comparison( url1, url2, url3, url4) else: urls = [url1, url2, url3, url4] self.assertEqual(urls[0], urls[1]) self.assertEqual(urls[0], urls[2]) self.assertEqual(urls[0], urls[3]) response = self.client.get(url) print("\t - cache_enabled=%s, url_signature_enabled=%s" % (cache_enabled, url_signature_enabled)) expected_status_code = 200 if url_signature_enabled is False and not allows_external_request_from_user( None): expected_status_code = 403 self.assertEqual(response.status_code, expected_status_code) if expected_status_code == 200: if is_first and REFRESH_REFERENCE_IMAGES: write_png_content_to_file( TestQRUrlFromTextResult.default_ref_base_file_name, response.content) is_first = False self.assertEqual( response.content, TestQRUrlFromTextResult. _get_reference_result_for_default_png())
def test_svg_error_correction(self): base_file_name = 'qrfromtext_error_correction' for correction_level in ERROR_CORRECTION_DICT: print('Testing SVG URL with error correction: %s' % correction_level) url1 = make_qr_code_url( COMPLEX_TEST_TEXT, QRCodeOptions(error_correction=correction_level), cache_enabled=False) url2 = qr_url_from_text(COMPLEX_TEST_TEXT, error_correction=correction_level, cache_enabled=False) url3 = qr_url_from_text(COMPLEX_TEST_TEXT, error_correction=correction_level, image_format='svg', cache_enabled=False) url4 = qr_url_from_text(COMPLEX_TEST_TEXT, error_correction=correction_level, image_format='SVG', cache_enabled=False) url5 = qr_url_from_text(COMPLEX_TEST_TEXT, options=QRCodeOptions( error_correction=correction_level, image_format='SVG'), cache_enabled=False) # Using an invalid image format should fallback to SVG. url6 = qr_url_from_text(COMPLEX_TEST_TEXT, error_correction=correction_level, image_format='invalid-format-name', cache_enabled=False) url = url1 urls = get_urls_without_token_for_comparison( url1, url2, url3, url4, url5, url6) self.assertEqual(urls[0], urls[1]) self.assertEqual(urls[0], urls[2]) self.assertEqual(urls[0], urls[3]) self.assertEqual(urls[0], urls[4]) self.assertEqual(urls[0], urls[5]) response = self.client.get(url) self.assertEqual(response.status_code, 200) source_image_data = response.content.decode('utf-8') # Skip header and adjust tag format. source_image_data = source_image_data[source_image_data. index('\n') + 1:] source_image_data = _make_closing_path_tag(source_image_data) ref_file_name = '%s_%s' % (base_file_name, correction_level.lower()) if REFRESH_REFERENCE_IMAGES: write_svg_content_to_file(ref_file_name, source_image_data) ref_image_data = get_svg_content_from_file_name(ref_file_name) self.assertEqual(source_image_data, ref_image_data)
def test_url_with_wrong_signature_token(self): valid_url_with_signature_token_for_size_10 = make_qr_code_url( TEST_TEXT, QRCodeOptions(size=10)) valid_url_with_signature_token_for_size_8 = make_qr_code_url( TEST_TEXT, QRCodeOptions(size=8)) token_regex = re.compile(r"token=([^&]+)") match = token_regex.search(valid_url_with_signature_token_for_size_8) size_8_token_value = match.group(1) match = token_regex.search(valid_url_with_signature_token_for_size_10) size_10_token_value = match.group(1) url_with_invalid_signature_token = valid_url_with_signature_token_for_size_10.replace( size_10_token_value, size_8_token_value) response = self.client.get(url_with_invalid_signature_token) self.assertEqual(response.status_code, 403)
def get_qr_code_option_from_request(request): request_query = request.GET.dict() for key in ('text', 'token', 'cache_enabled'): if key in request_query: request_query.pop(key) qr_code_options = QRCodeOptions(**request_query) return qr_code_options
def get(self, request): data = {} data['page_title'] = 'users' data['users'] = User.objects.all_user() # dump_data = dd(request, data['users']) # return HttpResponse(dump_data) # data['qr_code_message'] = 'Hello World! I am Rakib.' # Use a WifiConfig instance to encapsulate the configuration of the connexion. data['wifi_config'] = WifiConfig( ssid='my-wifi', authentication=WifiConfig.AUTHENTICATION.WPA, # password='******', password='******', ) data['qr_code_options'] = QRCodeOptions(size='10', border=6, error_correction='L') template = 'pages/user_list.html' # response = serializers.serialize('json', data['users']) # # response = serializers.serialize('json', data['users'], fields=('first_name','last_name','email')) # return HttpResponse(response) return render(request, template, data)
def qrcode_page(request, market_pk, user_pk): user_id = get_object_or_404(User, pk=user_pk) market_id = get_object_or_404(Market, pk=market_pk) time = datetime.now() contact_detail = dict( user_id=user_id, market_id=market_id, time=time, ) dataaa = dict(user_id=user_id, time=time) options = QRCodeOptions(size='t', border=6, error_correction='L') year = str(time.year) month = str(time.month) day = str(time.day) hour = str(time.hour) time_str = year+month+day+hour factory = qrcode.image.svg.SvgImage img = qrcode.make(contact_detail, image_factory=factory) img_save = img.save(f'market/images/{user_id}{market_id}{time_str}.png') # qrcode정보 visitorRecord에 저장하기 visitor_record = VisitorRecord() visitor_record.user_id=user_pk visitor_record.date=time visitor_record.markets_id=market_pk visitor_record.save() return HttpResponse(img_save, content_type="image/png")
def ReporteCodigoQR(request): if not request.user.empleado.actualizoContrasena: return HttpResponseRedirect(reverse('seguridad:log_out-url')) if request.method == 'POST': ahora = datetime.now() nombre = request.POST['nombre'] numero = request.POST['numero'] tamano = request.POST['tamano'] color = request.POST['color'] codigoQR = 'EQEL-' + nombre + '-' + numero + '-' + tamano + '-' + color + '-2' configuracionesQR = QRCodeOptions(size=100,border=0, error_correction='L') data = {'tamano':'Letter', 'posicion':'portrait', 'codigoQR': codigoQR, 'ahora': ahora, 'configuracionesQR':configuracionesQR, } return render(request,'equipo/reportes/reporteCodigoQR.html',data) else: pass
def make_qr_code_url(text, qr_code_options=None, cache_enabled=None, url_signature_enabled=None): """Build an URL to a view that handle serving QR code image from the given parameters. Any invalid argument related to the size or the format of the image is silently converted into the default value for that argument. :param bool cache_enabled: Allows to skip caching the QR code (when set to *False*) when caching has been enabled. :param bool url_signature_enabled: Tells whether the random token for protecting the URL against external requests is added to the returned URL. It defaults to *True*. """ qr_code_options = QRCodeOptions( ) if qr_code_options is None else qr_code_options if url_signature_enabled is None: url_signature_enabled = constants.DEFAULT_URL_SIGNATURE_ENABLED if cache_enabled is None: cache_enabled = constants.DEFAULT_CACHE_ENABLED encoded_text = str(base64.urlsafe_b64encode( bytes(force_str(text), encoding='utf-8')), encoding='utf-8') params = dict(text=encoded_text, cache_enabled=cache_enabled) # Only add non-default values to the params dict if qr_code_options.size != constants.DEFAULT_MODULE_SIZE: params['size'] = qr_code_options.size if qr_code_options.border != constants.DEFAULT_BORDER_SIZE: params['border'] = qr_code_options.border if qr_code_options.version != constants.DEFAULT_VERSION: params['version'] = qr_code_options.version if qr_code_options.image_format != constants.DEFAULT_IMAGE_FORMAT: params['image_format'] = qr_code_options.image_format if qr_code_options.error_correction != constants.DEFAULT_ERROR_CORRECTION: params['error_correction'] = qr_code_options.error_correction if qr_code_options.micro: params['micro'] = qr_code_options.micro params.update(qr_code_options.color_mapping()) path = reverse('qr_code:serve_qr_code_image') if url_signature_enabled: # Generate token to handle view protection. The token is added to the query arguments. It does not replace # existing plain text query arguments in order to allow usage of the URL as an API (without token since external # users cannot generate the signed token!). token = get_qr_url_protection_signed_token(qr_code_options) params['token'] = token url = '%s?%s' % (path, urllib.parse.urlencode(params)) return mark_safe(url)
def qr_code(request): # Build context for rendering QR codes. context = dict(my_options=QRCodeOptions(size='t', border=6, error_correction='L'), ) # Render the view. return render(request, 'Inventory/qr_code.html', context=context)
def myview(request): # Build context for rendering QR codes. context = dict(my_options=QRCodeOptions(size='t', border=6, error_correction='L'), ) # Render the view. return render(request, 'music/index.html', context=context)
def make_qr_code_with_args(text, qr_code_args): options = qr_code_args.get('options') if options: if not isinstance(options, QRCodeOptions): raise TypeError('The options argument must be of type QRCodeOptions.') else: options = QRCodeOptions(**qr_code_args) return make_embedded_qr_code(text, options)
def make_qr(text: Any, qr_code_options: QRCodeOptions): """Creates a QR code :rtype: segno.QRCode """ # WARNING: For compatibility reasons, we still allow to pass __proxy__ class (lazy string). Moreover, it would be OK to pass anything that has __str__ # attribute (e. g. class instance that handles phone numbers). return segno.make(str(text), **qr_code_options.kw_make())
def open_qrcode(request, room_name): qrcode_options = QRCodeOptions(size='H', border=1, error_correction='L') context = { 'qrcode_options' : qrcode_options, 'room_name' : room_name, 'qrcode_text': f"http://localhost:8000/patients/register/{room_name}" } return render(request, 'queues/open_qrcode.html', context = context)
def qr_code_session(request): prim_key = list(ClassAttentionID.objects.all().filter( session_teacher="rebecca"))[-1].hash_key context = dict(key=prim_key, my_options=QRCodeOptions(size='S', border=6, error_correction='L', image_format='png')) return render(request, 'attention/qr_code_session.html', context=context)
def ImprimePdf(request, id): texts = Demande.objects.get(id=id) context = { 'texts': texts, 'qrcode': QRCodeOptions(size='t', border=6, error_correction='L'), } return render_to_pdf('pdf_template.html', context)
def test_png_error_correction(self): base_file_name = 'qrfromtext_error_correction' for correction_level in ERROR_CORRECTION_DICT: print('Testing PNG URL with error correction: %s' % correction_level) url1 = make_qr_code_url(COMPLEX_TEST_TEXT, QRCodeOptions( error_correction=correction_level, image_format='png'), cache_enabled=False) url2 = make_qr_code_url(COMPLEX_TEST_TEXT, QRCodeOptions( error_correction=correction_level, image_format='PNG'), cache_enabled=False) url3 = qr_url_from_text(COMPLEX_TEST_TEXT, error_correction=correction_level, image_format='png', cache_enabled=False) url4 = qr_url_from_text(COMPLEX_TEST_TEXT, error_correction=correction_level, image_format='PNG', cache_enabled=False) url5 = qr_url_from_text(COMPLEX_TEST_TEXT, options=QRCodeOptions( error_correction=correction_level, image_format='PNG'), cache_enabled=False) url = url1 urls = get_urls_without_token_for_comparison( url1, url2, url3, url4, url5) self.assertEqual(urls[0], urls[1]) self.assertEqual(urls[0], urls[2]) self.assertEqual(urls[0], urls[3]) self.assertEqual(urls[0], urls[4]) response = self.client.get(url) self.assertEqual(response.status_code, 200) source_image_data = response.content ref_file_name = '%s_%s' % (base_file_name, correction_level.lower()) if REFRESH_REFERENCE_IMAGES: write_png_content_to_file(ref_file_name, source_image_data) ref_image_data = get_png_content_from_file_name(ref_file_name) self.assertEqual(source_image_data, ref_image_data)
def qrViewer(request): # Build context for rendering QR codes. context = { "my_options": QRCodeOptions(size='m', border=0, error_correction='s'), "qrCode": "http://127.0.0.1:8000/qrViewer", # Will need to be replaced with dynamic QR code generator "userName": request.session.get("userName") } # Render the view return render(request, 'parkingGenie/qrViewer.html', context)
def valider_repas(request): contact_detail = ContactDetail( tel="Matricule : " + str(request.user.etudiant.matricule) + '\n' + "Nom : " + str(request.user.etudiant.nom), ) context = dict( contact_detail=contact_detail, my_options=QRCodeOptions(size='t', border=6, error_correction='L'), ) return render(request, 'cossa/valider_repas.html', context=context)
def ordemservicos_detail(request, pk): msg = messages.get_messages(request) ordemservico = get_object_or_404(OrdemServico, pk=pk) options_qr = QRCodeOptions(size='t', border=6, error_correction='L') qr_url = make_qr_code_url("URL:https://excelencia.online/c/" + str(ordemservico.os_id), qr_code_options=options_qr) args = {'ordemservico': ordemservico, 'qr_url': qr_url, 'message': msg} return render(request, 'servicos/os/os_detail.html', args)
def make_qr_code_image(text: Any, qr_code_options: QRCodeOptions) -> bytes: """ Returns a bytes object representing a QR code image for the provided text. :param str text: The text to encode :param qr_code_options: Options to create and serialize the QR code. :rtype: bytes """ qr = make_qr(text, qr_code_options) out = io.BytesIO() qr.save(out, **qr_code_options.kw_save()) return out.getvalue()
def _options_from_args(args: Mapping) -> QRCodeOptions: """Returns a QRCodeOptions instance from the provided arguments. """ options = args.get('options') if options: if not isinstance(options, QRCodeOptions): raise TypeError('The options argument must be of type QRCodeOptions.') else: # Convert the string "None" into None kw = {k: v if v != 'None' else None for k, v in args.items()} options = QRCodeOptions(**kw) return options
def menu_qrcode_gen(request, pk): menu = Menu.objects.get(pk=pk) menu_url = reverse('menu-display', kwargs={'slug': menu.slug}) complete_url = ''.join( ['https://', get_current_site(request).domain, menu_url]) qrcode_options = QRCodeOptions(size='M') context = { 'menu': menu, 'complete_url': complete_url, 'qrcode_options': qrcode_options, } return render(request, 'menu/qr-gen.html', context=context)
def make_qr_code(text, qr_code_args, embedded): cache_enabled = DEFAULT_CACHE_ENABLED if 'cache_enabled' in qr_code_args: cache_enabled = qr_code_args.pop('cache_enabled') options = qr_code_args.get('options') if options: if not isinstance(options, QRCodeOptions): raise TypeError('The options argument must be of type QRCodeOptions.') else: options = QRCodeOptions(**qr_code_args) if embedded: return make_embedded_qr_code(text, options) else: return make_qr_code_url(text, options, cache_enabled=cache_enabled)
def test_reverse_lazy_url(self): from django.urls import reverse, reverse_lazy options = QRCodeOptions(image_format='svg', size=1) url1 = make_qr_code_url(reverse('qr_code:serve_qr_code_image'), options) url2 = make_qr_code_url(reverse_lazy('qr_code:serve_qr_code_image'), options) self.assertEqual(url1, url2) svg1 = make_embedded_qr_code(reverse('qr_code:serve_qr_code_image'), options) svg2 = make_embedded_qr_code( reverse_lazy('qr_code:serve_qr_code_image'), options) self.assertEqual(svg1, svg2)
def make_qr_code_url_with_args(text, qr_code_args): cache_enabled = DEFAULT_CACHE_ENABLED if 'cache_enabled' in qr_code_args: cache_enabled = qr_code_args.pop('cache_enabled') url_signature_enabled = DEFAULT_URL_SIGNATURE_ENABLED if 'url_signature_enabled' in qr_code_args: url_signature_enabled = qr_code_args.pop('url_signature_enabled') options = qr_code_args.get('options') if options: if not isinstance(options, QRCodeOptions): raise TypeError('The options argument must be of type QRCodeOptions.') else: options = QRCodeOptions(**qr_code_args) return make_qr_code_url(text, options, cache_enabled=cache_enabled, url_signature_enabled=url_signature_enabled)