Using SSL with SQLAlchemy

前端 未结 3 1788
梦毁少年i
梦毁少年i 2021-02-13 04:42

I\'ve recently changed my project to use SQLAlchemy and my project runs fine, it used an external MySQL server.

Now I\'m trying to work with a different MySQL server wit

相关标签:
3条回答
  • 2021-02-13 04:48

    If you just connect from a client machine with an ssl connection (so you don't have access to the cert and key), you could simple add ssl=true to your uri.

    Edit:

    For example: mysql_db = "mysql+mysqlconnector://<user>:<pass>@<addr>/<schema>?ssl=true"

    0 讨论(0)
  • 2021-02-13 05:06

    Another solution is to use sqlalchemy.engine.url.URL to define the URL and pass it to create_engine.

    sqlUrl = sqlalchemy.engine.url.URL(
        drivername="mysql+pymysql",
        username=db_user,
        password=db_pass,
        host=db_host,
        port=3306,
        database=db_name,
        query={"ssl_ca": "main_app/certs/BaltimoreCyberTrustRoot.crt.pem"},
    )
    create_engine(sqlUrl)
    

    You can include SSL parameters as a dictionary in the query argument.

    This approach is useful if you are using Flask to initialize the SqlAlchemy engine with a config parameter like SQLALCHEMY_DATABASE_URI rather than directly using create_engine.

    0 讨论(0)
  • 2021-02-13 05:08

    I changed the DBAPI to MySQL-Connector, and used the following code:

    ssl_args = {'ssl_ca': ca_path}
    engine = create_engine("mysql+mysqlconnector://<user>:<pass>@<addr>/<schema>",
                            connect_args=ssl_args)
    

    And now it works.

    0 讨论(0)
提交回复
热议问题