最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ssl - Try running a Python window app on https URL - Stack Overflow

programmeradmin2浏览0评论

I have build a python window exe which runs locally for printing labels on the window. but since my website is https i have to run the local app also on https URL using SSL certificate.

I have tried building a local certificate which includes following code

def generate_pfx():
try:
    subprocess.run(
        [
            "openssl", "pkcs12", "-export",
            "-out", PFX_FILE,
            "-inkey", KEY_PEM,
            "-in", CERT_PEM,
            "-password", f"pass:{PFX_PASSWORD}"
        ],
        check=True
    )
    print(f"PFX file '{PFX_FILE}' generated successfully.")
except subprocess.CalledProcessError as e:
    print(f"Error generating PFX: {e}")


def install_certificate():
    try:
        subprocess.run(
            ["certutil", "-importpfx", PFX_FILE, "-p", PFX_PASSWORD],
            check=True
        )
        print("Certificate successfully added to Trusted Root Certification Authorities.")
    except subprocess.CalledProcessError as e:
        print(f"Error importing certificate: {e}")


def run_as_admin():
    if not ctypes.windll.shell32.IsUserAnAdmin():
        ctypes.windll.shell32.ShellExecuteW(
            None, "runas", sys.executable, " ".join(sys.argv), None, 1
        )
        sys.exit()


def get_private_ip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        ip = s.getsockname()[0]
        s.close()
        return ip
    except Exception:
        return "127.0.0.1"


def generate_ssl_cert():
    if not os.path.exists(CERT_PEM) or not os.path.exists(KEY_PEM):
        print("Generating self-signed SSL certificate...")
        command = [
            "openssl", "req", "-x509", "-newkey", "rsa:4096", "-nodes",
            "-out", "cert.pem", "-keyout", "key.pem", "-days", "365"
        ]

        # Execute the command
        try:
            subprocess.run(command, check=True)
            print("Certificate and key have been generated successfully.")
        except subprocess.CalledProcessError as e:
            print(f"An error occurred: {e}")
    else:
        print("SSL certificate already exists.")


def log_message(message):
    log_messages.append(message)
    print(message)
    update_log_display()


def get_printers():
    return [printer[2] for printer in win32print.EnumPrinters(2)]


def send_to_printer(printer_name, content, paper_size):
    global job_counter
    job_name = f"WTW-{job_counter:02d}"
    job_counter += 1

    try:
        hprinter = win32print.OpenPrinter(printer_name)
        hdc = win32ui.CreateDC()
        hdc.CreatePrinterDC(printer_name)

        hdc.StartDoc(job_name)
        hdc.StartPage()
        hdc.TextOut(100, 100, content)
        hdc.EndPage()
        hdc.EndDoc()
        hdc.DeleteDC()
        win32print.ClosePrinter(hprinter)

        log_message(f"Printed: {content} on {printer_name} with {paper_size}")
        print_jobs.append((job_name, printer_name, content, paper_size, "Printed"))
        update_table()
        return True, "Print Successful"

    except Exception as e:
        log_message(f"Error: {str(e)}")
        print_jobs.append((job_name, printer_name, content, paper_size, "Failed"))
        update_table()
        return False, str(e)


@app.route('/print', methods=['POST'])
def print_document():
    data = request.json
    printer_name = data.get("printer_name")
    content = data.get("content")
    paper_size = data.get("paper_size", "62mm x 4m")

    if not printer_name or not content:
        return jsonify({"error": "Missing printer_name or content"}), 400

    success, message = send_to_printer(printer_name, content, paper_size)
    if success:
        return jsonify({"message": "Print command sent successfully"})
    else:
        return jsonify({"error": message}), 500


def run_flask():
    private_ip = get_private_ip()
    generate_ssl_cert()
    generate_pfx()
    install_certificate()

    print(f"Starting Flask server at https://{private_ip}:5000")
    #app.run(host=private_ip, port=5000, ssl_context=('adhoc'), debug=False, use_reloader=False)
    app.run(host=private_ip, port=5000, ssl_context=(CERT_PEM, KEY_PEM), debug=False, use_reloader=False)

But the certificate.pfx always gives me error and when i try import a certificate manually and use in the app it gives invalid certificate error on the react side where i call this URL

发布评论

评论列表(0)

  1. 暂无评论