我正在尝试连接到我的MySQL Azure数据库,我的端点是用FastAPI
编写的。当我单独运行我的连接方法时,连接正在工作,但一旦集成到端点中,我就会收到错误:
Failed to connect to the database: (mysql.connector.errors.InterfaceError) 2055: Lost connection to MySQL server at 'cluster_name.mysql.database.azure.com:port', system error: 1 [SSL: NO_CIPHERS_AVAILABLE] no ciphers available (_ssl.c:1006)
字符串
连接到数据库的代码看起来像这样:
def create_db_engine():
try:
# Format the connection string
connection_string = f"mysql+mysqlconnector://{user}:{password}@{host}/{database}"
ssl_args = {'ssl_ca': "DigiCertGlobalRootCA.crt.pem"}
# Create the SQLAlchemy engine
engine = create_engine(connection_string, connect_args=ssl_args)
# Test the connection
connection = engine.connect()
print("Successfully connected to the database.")
connection.close()
return engine
except exc.SQLAlchemyError as e:
print(f"Failed to connect to the database: {e}")
return None
engine = create_db_engine()
#conn = engine.connect()
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
型
当我从python单独运行这个方法时,它可以正确连接。我的API定义如下:
# Dependency
def get_db():
db = db_init.SessionLocal()
try:
yield db
finally:
db.close()
@app.post("/users/")
def create_user(user: schema.UserCreate, db: Session = Depends(get_db)):
db_user = crud.get_user_by_email(db, email=user.email)
if db_user:
raise HTTPException(status_code=400, detail="Email already registered")
return crud.create_user(db=db, user=user)
@app.post("/assistant_chat/")
def create_chat_message(chat_message: schema.ChatMessageCreate, db: Session = Depends(get_db)):
return crud.create_chat_message(db=db, chat_message=chat_message)
型
当我使用uvicorn和uvicorn API:app --reload运行此服务器时,我收到以下错误消息:Failed to connect to the database:(mysql.connector.errors.InterfaceError) 2055: Lost connection to MySQL server at 'cluster_name.mysql.database.azure.com:port', system error: 1 [SSL: NO_CIPHERS_AVAILABLE] no ciphers available (_ssl.c:1006)
个
1条答案
按热度按时间jw5wzhpr1#
我尝试了你的代码,做了一些小的修改,我能够连接Azure MySql数据库并启用SSL。
请确保安装mysql-connector-python
main.py:
字符串
这是我连接Azure Mysql数据库的连接代码
型
我使用uvicorn运行了以下命令:
型
我得到了下面的输出:x1c 0d1x
并成功上传数据:
这是我的架构输出: