"""A local support-request form with application-owned language queue rules.""" import hmac import os import re import secrets import httpx from flask import Flask, render_template_string, request, session app = Flask(__name__) app.secret_key = os.environ.get("APP_SECRET") or secrets.token_hex(32) app.config.update(MAX_CONTENT_LENGTH=16384, SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SAMESITE="Lax", TRUSTED_HOSTS=["127.0.0.1", "localhost"]) # example:queues QUEUES = {"en": "English support", "fr": "French support", "es": "Spanish support"} REVIEW_QUEUE = "Language review" # /example:queues PAGE = """ Route a support request

Route a support request

Find the right support queue from the language of a message.

{% if error %}{% endif %}

Use one language per request, up to 2,000 characters.

{{ field_error or '' }}

{% if ticket %}

Route for this request

{{ ticket.queue }}

Detected language: {{ ticket.language_name }}

{% if ticket.review %}Keep this request for a person to review. Its language is unidentified or has no configured queue.{% else %}This queue matches the language of the submitted message.{% endif %}

{% endif %}

This page chooses a queue. It does not send a message or create a help-desk ticket.

""" @app.after_request def private_response(response): response.headers["Cache-Control"] = "no-store" response.headers["X-Content-Type-Options"] = "nosniff" return response @app.errorhandler(413) def too_large(_error): return "

Request too large

Go back and use a message of at most 2,000 characters.

", 413 @app.route("/", methods=["GET", "POST"]) def index(): message, field_error, error, ticket, status = "", None, None, None, 200 token = session.setdefault("csrf", secrets.token_urlsafe(32)) if request.method == "POST": # example:input message = request.form.get("message", "") # /example:input submitted = request.form.get("csrf", "") if not submitted.isascii() or not hmac.compare_digest(submitted, token): error, status = "This form expired. Refresh the page and try again.", 403 elif not message.strip() or len(message) > 2000 or "\x00" in message: field_error, status = "Enter a message of 1 to 2,000 characters.", 422 else: key = os.environ.get("PARSEAPI_KEY", "").strip() if not key or key.startswith(("parse_public_", "parse_app_")): error, status = "The language check is unavailable. Please try again later.", 503 else: try: # Explicit direct HTTP: Python1.12 has no language-detection helper. # example:request with httpx.Client( base_url=os.environ.get("PARSEAPI_BASE_URL", "https://api.parseapi.com"), timeout=10.0, follow_redirects=False, ) as client: response = client.post( "/language/detect", json={"text": message.strip()}, headers={"X-API-Key": key, "X-API-Version": "2.1.0"}, ) # /example:request response.raise_for_status() if response.headers.get("X-API-Version") != "2.1.0": raise ValueError("Unexpected API version.") # example:response detection = response.json() # /example:response if not isinstance(detection, dict) or not all(name in detection for name in ("language", "name")): raise ValueError("Unexpected detection response.") if detection["language"] is None: if detection["name"] is not None: raise ValueError("Unexpected unidentified response.") elif (not isinstance(detection["language"], str) or not re.fullmatch(r"[a-z]{2,3}", detection["language"]) or not isinstance(detection["name"], str) or not detection["name"].strip()): raise ValueError("Unexpected detection fields.") # example:fields language = detection["language"] language_name = detection["name"] # /example:fields # example:route queue = QUEUES.get(language, REVIEW_QUEUE) # /example:route ticket = {"queue": queue, "language_name": language_name or "Not identified", "review": language not in QUEUES} except httpx.HTTPStatusError as failure: if failure.response.status_code == 400: field_error, status = "This message could not be checked. Review the text and try again.", 422 else: error, status = "The language check did not complete. Please try again later.", 503 except (httpx.RequestError, ValueError): error, status = "The language response could not be used. Please try again later.", 503 return render_template_string(PAGE, message=message, field_error=field_error, error=error, ticket=ticket, csrf=token), status if __name__ == "__main__": app.run(host="127.0.0.1", port=int(os.environ.get("PORT", "8000")), debug=False, use_reloader=False)