You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyScript + Pyodide 连接MySQL数据库遭遇WebSocket问题:无法建立数据库连接

PyScript无法连接MySQL数据库(InterfaceError 2003)问题求助

我现在在排查一个PyScript项目里无法连接MySQL数据库的问题,折腾了好一阵都没搞定,想请教下有没有遇到过类似情况的朋友能给点建议?

项目代码

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <title>PyScript - MySQL DB connection test</title>
    <link rel="icon" type="image/png" href="https://pyscript.net/examples/favicon.png" />
    <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
    <script defer src="https://pyscript.net/latest/pyscript.js"></script>
    <py-env>
        - mysql-connector-python
    </py-env>
    <py-config>
        packages = [ "mysql-connector-python" ]
    </py-config>
</head>
<body>
    <div id="outputDiv"></div>
    <py-script src="./connectDB.py" output="outputDiv">
    </py-script>
    <p>PyScript - MySQL DB connection test</p>
</body>
</html>

connectDB.py

import mysql.connector
mydb = mysql.connector.connect(
    host="sql7.freemysqlhosting.net",
    user="dbuser",
    password="dbpassword",
    database="mytestdatabase"
)
print(mydb)

错误情况

  1. HTTP访问时:
    抛出PythonError,核心错误信息:
mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'sql7.freemysqlhosting.net:3306' (26 Operation in progress)

浏览器控制台还出现警告:

WebSocket connection to 'ws://sql7.freemysqlhosting.net:3306/' failed: WebSocket is closed before the connection is established.
  1. HTTPS访问时:
    同样抛出PythonError,核心错误:
mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'sql7.freemysqlhosting.net:3306' (23 Host is unreachable)

浏览器控制台错误:

Mixed Content: The page at 'https://****.**/psproject/' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://sql7.freemysqlhosting.net:3306/'. This request has been blocked; this endpoint must be available over WSS.

已尝试的解决措施

  • 在执行Python脚本前手动提前建立到数据库的WebSocket连接,没用
  • 换了其他几个MySQL托管服务,问题还是一样

有没有大佬知道这问题出在哪?或者有什么可行的解决思路?万分感谢!

内容的提问来源于stack exchange,提问作者krafteuer31

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 12:44:06