[Python] Connect to thermal printer on client from Flask web app deployed on cloud

Discussão em 'Python' iniciado por Stack, Junho 11, 2025.

  1. Stack

    Stack Membro Participativo

    I am working on a Flask-based restaurant ordering system that will be deployed on a cloud hosting service, in this case Render. On the admin panel of the ordering system, the admin user can enter the IP address and host of the thermal printer and store it in the system, and can perform a test print using the printer attributes the user entered.

    If the Flask server is on a local computer, the server can print the receipt through the thermal printer that is connected to the local computer, be it using Ethernet, Wi-fi or Bluetooth. However, if the Flask server is deployed onto a cloud hosting service, how can the Flask server be able to tell the thermal printer that is connected to the client to print the receipt?

    JavaScript

    const testStatus = document.getElementById('test-status');
    const btnTestPrinter = document.getElementById('btn-test');
    btnTestPrinter.addEventListener('click', async function(event) {
    var name = document.getElementById('name').value;
    var ipAddress = document.getElementById('ip_address').value;
    var port = document.getElementById('port').value;

    printer = {
    "name": name,
    "ip_address": ipAddress,
    "port": port
    }

    const testPrinterUrl = window.location.origin+'{{ url_for("test_printer") }}';

    try {
    console.log("Testing printer: "+name);
    const placeOrderResponse = await fetch(testPrinterUrl, {
    method: "POST",
    headers: {
    "Content-Type": "application/json"
    },
    body: JSON.stringify(printer)
    });
    const testResult = await placeOrderResponse.json();

    var success = testResult.success;
    if (success) {
    testStatus.textContent = "Test print success";
    } else {
    testStatus.textContent = "Unable to perform test print";
    }
    } catch (error) {
    console.error("Error: ", error);
    }
    });


    Flask server

    @route('/test_printer', methods=['POST'])
    def test_printer():
    data:dict = json.loads(request.data)
    print("Printer info: "+data.__repr__())

    name = data['name']
    ip_address = data['ip_address']
    port = int(data['port'])
    date_str = datetime.now().strftime("%m/%d/%Y, %H:%M:%S")

    try:
    p = printer.Network(ip_address, port=port, timeout=30)
    p.text("Receipt text goes here")

    p.cut() # Cut the paper

    p.close()

    except Exception as e:
    print(f"Error: {e}")
    return json.dumps({'success': False}), 500, {'ContentType':'application/json'}

    return json.dumps({'success':True}), 200, {'ContentType':'application/json'}

    Continue reading...

Compartilhe esta Página