简体   繁体   English

从 Google Cloud Function 连接到 Mssql 实例的问题

[英]Issue Connecting to Mssql Instance From Google Cloud Function

I am trying to connect to a mssql instance in cloud sql in a cloud function.我正在尝试连接到云 function 中的云 sql 中的 mssql 实例。 I have gone through the necessary steps of setting up a private IP, serverless VPC connector, and connecting my function to the VPC.我已经完成了设置私有 IP、无服务器 VPC 连接器并将我的 function 连接到 VPC 的必要步骤。 I have been able to connect to the instance in nodejs but python suits my current needs more.我已经能够连接到 nodejs 中的实例,但 python 更适合我当前的需求。 The error I'm getting in the logs is:我在日志中得到的错误是:

pyodbc.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 17 for SQL Server' pyodbc.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 17 for SQL Server'

From all the examples I have read it does not appear that you need to import them or anything.从我读过的所有示例中,您似乎不需要导入它们或任何东西。 This is my process of connecting and executing a simple request.这是我连接和执行一个简单请求的过程。

import sqlalchemy
import pyodbc

def hello_world(request):
        # connect_simple()
        db = connect_tcp_socket()
        a = execute_request(db)
        return a
    
def connect_tcp_socket() -> sqlalchemy.engine.base.Engine:
    db_host = 'my_private_ip'  
    db_user = 'my_db_user'
    db_pass = 'my_db_pass'
    db_name = 'my_db_name'
    db_port = 'my_db_port' 

    connection_string = 'DRIVER={ODBC Driver 17 for SQL Server};SERVER='+db_host+';PORT='+db_port+'DATABASE='+db_name+';UID='+db_user+';PWD='+ db_pass+';Encrypt=no'
    connection_url = sqlalchemy.engine.url.URL.create("mssql+pyodbc", query={"odbc_connect": connection_string})
    engine = sqlalchemy.create_engine(
        connection_url
    )

def execute_request(db: sqlalchemy.engine.base.Engine):
        print('ok')
        with db.connect() as conn:
            result = conn.execute('SELECT @@VERSION')
            barray= []
            for row in result:
                barray.append(row)
        return barray

I'd recommend using the Cloud SQL Python Connector to connect to Cloud SQL from Python as it will not require the ODBC driver and is much easier to use within Cloud Functions/Cloud Run. I'd recommend using the Cloud SQL Python Connector to connect to Cloud SQL from Python as it will not require the ODBC driver and is much easier to use within Cloud Functions/Cloud Run.

Just replace your connect_tcp_socket with the below connect_with_connector function.只需将您的connect_tcp_socket替换为以下connect_with_connector function。

from google.cloud.sql.connector import Connector, IPTypes
import pytds

import sqlalchemy

def connect_with_connector() -> sqlalchemy.engine.base.Engine:
    def getconn() -> pytds.Connection:
        with Connector() as connector:
            conn = connector.connect(
                "project-id:region:instance-name",  # Cloud SQL connection name
                "pytds",
                user="my-user",
                password="my-password",
                db="my-database",
                ip_type=IPTypes.PRIVATE
            )
            return conn

    engine = sqlalchemy.create_engine(
        "mssql+pytds://localhost",
        creator=getconn,
    )
    return engine

You can find a code sample for the Python Connector similar to the one you are using for establishing a TCP connection.您可以找到 Python 连接器的代码示例,类似于您用于建立 TCP 连接的代码示例。

Note: Pytds driver is not super great with error handling.注意: Pytds 驱动程序在错误处理方面并不是超级棒。 If you see the OSError: [Errno 9] Bad file descriptor error it usually means your database user is missing proper permissions and should grant them the necessary grants from a root user.如果您看到OSError: [Errno 9] Bad file descriptor错误,这通常意味着您的数据库用户缺少适当的权限,应该从 root 用户那里授予他们必要的权限。

Your requirements.txt should include the following:您的requirements.txt应包括以下内容:

cloud-sql-python-connector
SQLAlchemy
python-tds
sqlalchemy-pytds

There is also an interactive getting started Colab Notebook that will walk you through using the Python Connector without you needing to change a single line of code!还有一个交互式入门Colab 笔记本,它将引导您使用 Python 连接器,而无需更改一行代码!

It makes connecting to Cloud SQL both easy and secure from Cloud Functions.它使从 Cloud Functions 连接到 Cloud SQL 既简单又安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从云数据融合管道连接到谷歌云 sql 用于 postgres 的问题 - Issue connecting to google cloud sql for postgres from cloud data fusion pipeline 使用 python 中的 SSL 连接到云 SQL postgres 实例 - Connecting to Cloud SQL postgres instance with SSL in python 从本地运行的 NodeJS / TypeORM 连接到 Google Cloud MySQL 实例 - Connect to Google Cloud MySQL instance from local running NodeJS / TypeORM 从谷歌云返回的错误请求 function - Bad request returned from google cloud function 从 Blazor WASM 调用 Google Cloud Function - Calling Google Cloud Function from Blazor WASM 无法访问 Google Cloud 实例 - Can not access Google Cloud Instance 将 Google Cloud Build 连接到私有端点 - Connecting Google Cloud Build to Private Endpoints 防火墙问题 - 从 GKE 到云的出口 Function HTTP 触发器 - Firewall issue - egress from GKE to Cloud Function HTTP Trigger 使用谷歌云中的数据流从云存储中读取数百万个文件的问题 - Issue with reading millions of files from cloud storage using dataflow in Google cloud 从 Google Cloud function 中调用 shell 脚本 - Call shell script from within Google Cloud function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM