Skip to content

Commit

Permalink
Merge pull request #18 from vshn/async-and-redirect
Browse files Browse the repository at this point in the history
async printing and redirect after submit
  • Loading branch information
tobru authored Oct 3, 2024
2 parents ef7b0a0 + 9bf1d86 commit 46de0c0
Show file tree
Hide file tree
Showing 7 changed files with 172 additions and 109 deletions.
45 changes: 26 additions & 19 deletions contactform/app.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import logging
import threading
from flask import (
Flask,
render_template,
Expand All @@ -18,7 +19,6 @@
Configuration,
ServerConfiguration,
PrinterConfiguration,
Font,
LabelConfiguration,
WebsiteConfiguration,
)
Expand Down Expand Up @@ -151,29 +151,36 @@ def index():
except Exception as e:
logging.error(f"Couldn't create Lead in Odoo: {e}")

# Extract necessary form data
name_data = form.name.data
company_data = form.company.data
email_data = form.email.data
phone_data = form.phone.data

if config.PRINT_APPUIO_VOUCHER:
print_voucher(
form=form,
voucher_code=voucher_code,
config=config,
printer_config=printer_config,
)
threading.Thread(
target=print_voucher,
args=(
name_data,
company_data,
email_data,
phone_data,
voucher_code,
config,
printer_config,
),
).start()

if config.PRINT_RAFFLE_TICKET:
print_raffle(
form=form,
voucher_code=voucher_code,
config=config,
printer_config=printer_config,
)
threading.Thread(
target=print_raffle,
args=(name_data, voucher_code, config, printer_config),
).start()

flash("Thanks for submitting", "success")
return redirect(url_for("index"))

return render_template(
"form.html",
form=form,
)
return render_template("success.html")
else:
return render_template("form.html", form=form)


@app.route("/config", methods=["GET", "POST"])
Expand Down
2 changes: 1 addition & 1 deletion contactform/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ def save_config(config):
def setup_logging(log_level):
logging.basicConfig(
level=logging.getLevelName(log_level),
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
format="%(asctime)s [%(threadName)s] %(levelname)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)

Expand Down
81 changes: 48 additions & 33 deletions contactform/label_raffle.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import logging
from flask import flash
from wtforms.fields import *
import uuid
import os
from html2image import Html2Image
from brother_ql_web.labels import (
LabelParameters,
Expand All @@ -10,8 +10,9 @@
from brother_ql.backends.network import BrotherQLBackendNetwork


def print_raffle(form, voucher_code, config, printer_config):
label_filename = "label_raffle.png"
def print_raffle(name_data, voucher_code, config, printer_config):
unique_id = uuid.uuid4().hex
label_filename = f"label_raffle_{unique_id}.png"

label_css = """
body, html {
Expand All @@ -35,47 +36,61 @@ def print_raffle(form, voucher_code, config, printer_config):
"""
label_html = f"""\
<div>
<h1>{form.name.data}</h1>
<h1>{name_data}</h1>
<p class="big">{config.LABEL_HEADER}</p>
<p class="small">{voucher_code}</p>
</div>
"""

hti = Html2Image(
size=(590, 500),
custom_flags=[
"--default-background-color=FFFFFF",
"--hide-scrollbars",
],
)
hti.screenshot(
html_str=label_html,
css_str=label_css,
save_as=label_filename,
)
try:
# Generate image from HTML and CSS
hti = Html2Image(
size=(590, 500),
custom_flags=[
"--default-background-color=FFFFFF",
"--hide-scrollbars",
],
)
hti.screenshot(
html_str=label_html,
css_str=label_css,
save_as=label_filename,
)

label_image = open(label_filename, "rb")
with open(label_filename, "rb") as label_image:
parameters = LabelParameters(
configuration=printer_config,
image=label_image.read(),
label_size="54",
)

parameters = LabelParameters(
configuration=printer_config,
image=label_image.read(),
label_size="54",
)
logging.info(f"Printing raffle label for {name_data}")
preview_filename = (
f"print-preview-raffle_{unique_id}.png"
if config.LOG_LEVEL == "DEBUG"
else None
)
qlr = generate_label(
parameters=parameters,
configuration=printer_config,
save_image_to=preview_filename,
)

logging.info(f"Printing raffle label for {form.name.data}")
qlr = generate_label(
parameters=parameters,
configuration=printer_config,
save_image_to=(
"print-preview-raffle.png" if config.LOG_LEVEL == "DEBUG" else None
),
)
try:
print_label(
parameters=parameters,
qlr=qlr,
configuration=printer_config,
backend_class=BrotherQLBackendNetwork,
)
except Exception as e:
flash(f"Printing of raffle ticket failed: {e}", "error")
logging.error(f"Printing of raffle ticket failed for {name_data}: {e}")
finally:
# Clean up temporary files
if os.path.exists(label_filename):
os.remove(label_filename)
if (
config.LOG_LEVEL == "DEBUG"
and preview_filename
and os.path.exists(preview_filename)
):
os.remove(preview_filename)
134 changes: 80 additions & 54 deletions contactform/label_voucher.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import segno
import urllib
import logging
import uuid
import os


from flask import flash
from wtforms.fields import *
from html2image import Html2Image
from brother_ql_web.labels import (
LabelParameters,
Expand All @@ -14,9 +13,18 @@
from brother_ql.backends.network import BrotherQLBackendNetwork


def print_voucher(form, voucher_code, config, printer_config):
label_filename = "label_voucher.png"
qr_code_filename = "appuio_voucher_qr.png"
def print_voucher(
name_data,
company_data,
email_data,
phone_data,
voucher_code,
config,
printer_config,
):
unique_id = uuid.uuid4().hex
label_filename = f"label_voucher_{unique_id}.png"
qr_code_filename = f"appuio_voucher_qr_{unique_id}.png"

label_css = """
body, html {
Expand All @@ -41,7 +49,7 @@ def print_voucher(form, voucher_code, config, printer_config):
label_html = f"""\
<div>
<p><img src="appuio-bw.png" class="logo"></p>
<p class="text">Hi {form.name.data}<p>
<p class="text">Hi {name_data}<p>
<p class="text">Your personal voucher code to try out APPUiO:</p>
<p class="text"><strong>{voucher_code}</strong></p>
<p class="text_small">Register here: {config.APPUIO_SIGNUP_URL}</p>
Expand All @@ -51,60 +59,78 @@ def print_voucher(form, voucher_code, config, printer_config):

registration_url_parameters = (
f"?voucher={voucher_code}"
f"&name={urllib.parse.quote(form.name.data)}"
f"&company={urllib.parse.quote(form.company.data)}"
f"&email={urllib.parse.quote(form.email.data)}"
f"&phone={urllib.parse.quote(form.phone.data)}"
f"&name={urllib.parse.quote(name_data)}"
f"&company={urllib.parse.quote(company_data)}"
f"&email={urllib.parse.quote(email_data)}"
f"&phone={urllib.parse.quote(phone_data)}"
f"&utm_campaign={urllib.parse.quote(config.CAMPAIGN_NAME)}"
f"&utm_source=Voucher"
)
signup_url = f"{config.APPUIO_SIGNUP_URL}{registration_url_parameters}"
logging.debug(f"URL: {signup_url}")
qrcode = segno.make_qr(signup_url)
qrcode.save(
qr_code_filename,
scale=5,
)

hti = Html2Image(
size=(590, 1200),
custom_flags=[
"--default-background-color=FFFFFF",
"--hide-scrollbars",
],
)
hti.load_file(config.APPUIO_LOGO_PATH)
hti.load_file(qr_code_filename)
hti.browser.print_command = True if config.LOG_LEVEL == "DEBUG" else False
hti.screenshot(
html_str=label_html,
css_str=label_css,
save_as=label_filename,
)
try:
# Generate QR code
qrcode = segno.make_qr(signup_url)
qrcode.save(
qr_code_filename,
scale=5,
)

hti = Html2Image(
size=(590, 1200),
custom_flags=[
"--default-background-color=FFFFFF",
"--hide-scrollbars",
],
)
hti.load_file(config.APPUIO_LOGO_PATH)
hti.load_file(qr_code_filename)
hti.browser.print_command = True if config.LOG_LEVEL == "DEBUG" else False
hti.screenshot(
html_str=label_html,
css_str=label_css,
save_as=label_filename,
)

label_image = open(label_filename, "rb")
with open(label_filename, "rb") as label_image:
parameters = LabelParameters(
configuration=printer_config,
image=label_image.read(),
label_size="54",
high_quality=True,
)

parameters = LabelParameters(
configuration=printer_config,
image=label_image.read(),
label_size="54",
high_quality=True,
)
logging.info(f"Printing voucher label for {name_data}")
preview_filename = (
f"print-preview-voucher_{unique_id}.png"
if config.LOG_LEVEL == "DEBUG"
else None
)

logging.info(f"Printing voucher label for {form.name.data}")
qlr = generate_label(
parameters=parameters,
configuration=printer_config,
save_image_to=(
"print-preview-voucher.png" if config.LOG_LEVEL == "DEBUG" else None
),
)
try:
print_label(
parameters=parameters,
qlr=qlr,
configuration=printer_config,
backend_class=BrotherQLBackendNetwork,
)
qlr = generate_label(
parameters=parameters,
configuration=printer_config,
save_image_to=preview_filename,
)

print_label(
parameters=parameters,
qlr=qlr,
configuration=printer_config,
backend_class=BrotherQLBackendNetwork,
)
except Exception as e:
flash(f"Printing of voucher failed: {e}", "error")
logging.error(f"Printing of voucher failed for {name_data}: {e}")
finally:
# Clean up temporary files
if os.path.exists(label_filename):
os.remove(label_filename)
if os.path.exists(qr_code_filename):
os.remove(qr_code_filename)
if (
config.LOG_LEVEL == "DEBUG"
and preview_filename
and os.path.exists(preview_filename)
):
os.remove(preview_filename)
2 changes: 2 additions & 0 deletions contactform/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@
<html lang="en">

<head>
{% block head %}
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>VSHN Conference Booth Hit</title>
<link rel="icon" href="{{ url_for('static', filename='favicon.png') }}">
{{ bootstrap.load_css() }}
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
{% endblock %}
</head>

<body class="bg-image">
Expand Down
10 changes: 10 additions & 0 deletions contactform/templates/success.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{% extends 'base.html' %}

{% block head %}
{{ super() }}
<meta http-equiv="refresh" content="2;url=https://vshn.ch">
{% endblock %}

{% block content %}
<p>You will be redirected to <a href="https://vshn.ch">vshn.ch</a> shortly.</p>
{% endblock %}
Loading

0 comments on commit 46de0c0

Please sign in to comment.