首页 > 解决方案 > 使用 SSL 证书通过 python 脚本连接到 cloudSQL (MySQL)

问题描述

我需要使用 SSL 将 python 脚本连接到 Google Cloud SQL 数据库。我知道如何仅通过 ip 地址连接到数据库,但我不明白如何使用我使用 python.pem在文件中收到的 SSL 证书(3 个证书)、令牌 ID 等。.json我尝试了一些代码,但它们不起作用,我也不明白发生了什么。

import psycopg2
import psycopg2.extensions
import os
import stat
from google.cloud import storage

def main():
    con = connect()
    connection = con.connect_to_db()
    result = connection.execute('SELECT * FROM 
       personaformation').fetchall()
    for row in result:
        votes.append({
            'fname': row[0],
            'lname': row[1],
            'email': row[2]
        })
    print(votes[0])

def connect_to_db(self):

    # Get keys from GCS
    client = storage.Client()

    bucket = client.get_bucket(weightssl)
    bucket.get_blob('C:/Users/tasne/Downloads/serverca.pem').
    download_to_filename('server-ca.pem')
    
    bucket.get_blob('C:/Users/tasne/Downloads/clientkey.pem').
    download_to_filename('client-key.pem')
    os.chmod("client-key.pem", stat.S_IRWXU)
    bucket.get_blob('C:/Users/tasne/Downloads/clientcert.pem').
    download_to_filename('client-cert.pem')

    sslrootcert = 'server-ca.pem'
    sslkey = 'client-key.pem'
    sslcert = 'client-cert.pem'

    print("reached here")

    con = psycopg2.connect(
        host='37.246.65.223',
        dbname='personalformation',
        user='hello',
        password='world',
        sslmode = 'verify-full',
        sslrootcert=sslrootcert,
        sslcert=sslcert,
        sslkey=sslkey)
    return con

当我尝试代码时,这是我得到的错误,但是我不知道在哪里指定凭据,也没有使用计算引擎,因为这不是我正在创建的应用程序,而只是一个 python 脚本

C:\Users\tasne\PycharmProjects\project1\venv\Scripts\python.exe C:/Users/tasne/Downloads/database2.py
Traceback (most recent call last):
  File "C:/Users/tasne/Downloads/database2.py", line 21, in <module>
    credentials = GoogleCredentials.get_application_default()
  File "C:\Users\tasne\PycharmProjects\project1\venv\lib\site-packages\oauth2client\client.py", line 1288, in get_application_default
    return GoogleCredentials._get_implicit_credentials()
  File "C:\Users\tasne\PycharmProjects\project1\venv\lib\site-packages\oauth2client\client.py", line 1278, in _get_implicit_credentials
    raise ApplicationDefaultCredentialsError(ADC_HELP_MSG)
oauth2client.client.ApplicationDefaultCredentialsError: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.

标签: pythonsslgoogle-cloud-sql

解决方案


推荐阅读