encode / databases

Async database support for Python. 🗄
https://www.encode.io/databases/
BSD 3-Clause "New" or "Revised" License
3.85k stars 262 forks source link

SSL handshake failed #537

Open nitanmarcel opened 1 year ago

nitanmarcel commented 1 year ago

I'm trying to connect to planetscale's mysql database, but I can't get the connection working.

They offer a snippet of code, on how to connect to them using different programming languages.

For example in python:

from dotenv import load_dotenv
load_dotenv()
import os
import MySQLdb

connection = MySQLdb.connect(
  host= os.getenv("HOST"),
  user=os.getenv("USERNAME"),
  passwd= os.getenv("PASSWORD"),
  db= os.getenv("DATABASE"),
  ssl_mode = "VERIFY_IDENTITY",
  ssl      = {
    "ca": "/etc/ssl/cert.pem"
  }
)

I have no idea where to pass the ca thing. My database string is the following:

mysql://8jdabgcbksmalfucug29:************@eu-central.connect.psdb.cloud/default?ssl=true

There's a similar string for nodejs, in their documentation similar to mine:

mysql://8jdabgcbksmalfucug29:************@eu-central.connect.psdb.cloud/default?ssl={"rejectUnauthorized":true}

darkshloser commented 1 year ago

Hi @nitanmarcel,

Based on the information in your question, I believe you are using Django ORM (correct me if I'm wrong). I would suggest using SQLAlchemy for many, some of it is described in the following article https://djangostars.com/blog/merging-django-orm-with-sqlalchemy-for-easier-data-analysis/

First of all, you need to create a global variable with Engine. create_engine accepts additional configuration for connection, which needs to be used in that case.

You can prepare the database string as the following example: db_connect_string='mysql://<user>:<pswd>@<db server>:3306/<database>'

After that SSL certificates along with engine creation could be defined as it's listed below:

ssl_args = {
    "sslrootcert": "server-ca.pem", 
    "sslcert": "client-cert.pem",
    "sslkey": "client-key.pem"
}
create_engine(db_connect_string, connect_args=ssl_args)