gpt4 book ai didi

python - Azure Functions (Python) 无法使用 [SSL : WRONG_VERSION_NUMBER] 连接到 Azure MySQL 实例

转载 作者:太空宇宙 更新时间:2023-11-03 13:58:00 47 4
gpt4 key购买 nike

我正在使用 Python 创建一个简单的 Azure 函数。它只是简单地从 Azure MySQL 实例中读取数据并将某些内容写回同一实例。但是,我无法成功连接到数据库。

import logging
from datetime import datetime

import azure.functions as func
import mysql.connector
from mysql.connector import errorcode

def connect_to_db():
logging.info(os.getcwd())
try:
db_conn = mysql.connector.connect(
user="...",
password='...',
host="....mysql.database.azure.com",
port=3306,
database='...'
)
return db_conn
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
logging.error("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
logging.error("Database does not exist")
else:
logging.error(err)

return None


def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')

db_conn = connect_to_db()
if db_conn:
logging.info('DB Connection is established {}'.format(db_conn))
else:
return func.HttpResponse(
"Azure Functions cannot connect to MySQL database.",
status_code=500
)

....

当我使用 func host start 时,代码在我的本地机器上运行良好,我也使用了相同的 Azure MySQL 实例。

但是,在我部署 Azure Function 后,它不起作用并给我以下错误:

2055: Lost connection to MySQL server at '....mysql.database.azure.com:3306', 
system error: 1 [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:852)

我还尝试在 Azure 门户中禁用“强制执行 SSL”,并启用允许访问 Azure 服务,但这没有帮助。

任何帮助和意见将不胜感激!谢谢!

最佳答案

最终我自己解决了这个问题。

步骤如下:

  1. 从 Azure 文档存储库下载 SSL 证书。你可以在这里得到它:https://learn.microsoft.com/en-us/azure/mysql/howto-configure-ssl

  2. 将证书文件与 Azure Functions 项目放在一起。对我来说,我把它放在项目的根文件夹中,因为我很可能在这个项目中有多个功能需要这个证书

  3. 然后在python代码中获取认证文件如下

    import pathlib

    def get_ssl_cert():
    current_path = pathlib.Path(__file__).parent.parent
    return str(current_path / 'BaltimoreCyberTrustRoot.crt.pem')
  4. 这样,我就可以在连接MySQL时使用SSL证书了

    # Connect to MySQL
    cnx = mysql.connector.connect(
    user="ctao@azure-mysql-test",
    password='*******',
    host="azure-mysql-test.mysql.database.azure.com",
    port=3306,
    database='ciscoepcstats',
    ssl_ca=get_ssl_cert()
    )

附言出于安全考虑,禁用 SSL 验证对我来说不是一个选项。但幸运的是我找到了解决方案。

关于python - Azure Functions (Python) 无法使用 [SSL : WRONG_VERSION_NUMBER] 连接到 Azure MySQL 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58515927/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com