【问题标题】:SQLAlchemy create_engine not working in Google Cloud FunctionSQLAlchemy create_engine 在谷歌云函数中不起作用
【发布时间】:2020-11-23 08:14:40
【问题描述】:

我正在尝试运行一个谷歌云函数,该函数从网站上收集数据,然后将其插入到 Cloud SQL (MySQL) 数据库中,但在我的本地计算机上没有出现的云端 SQLAlchemy 问题。 有什么建议吗!?

当我使用 Cloud SQL 代理和 SQLAlchemy 针对 Py3.7(在 Mac 上,不使用 virtualenv)在本地运行该函数时,我成功连接到数据库。

在运行云函数时,我使用mysql+pymysql://<username>:<password>/<dbname>?unix_socket=/cloudsql/<PROJECT-NAME>:<INSTANCE-REGION>:<INSTANCE-NAME>这种格式的连接字符串。

云函数不断为 SQLAlchemy.create_engine 抛出以下异常。它似乎与能否连接无关,而是由于实例化。

一切都在同一个项目中。

我也尝试过使用mysql+pymysql://<username>:<password>@<public ip address>:3306/<dbname>格式的公共IP和连接字符串,没有区别。

Traceback (most recent call last):
  File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker_v2.py", line 449, in run_background_function
    _function_handler.invoke_user_function(event_object)
  File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker_v2.py", line 268, in invoke_user_function
    return call_user_function(request_or_event)
  File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker_v2.py", line 265, in call_user_function
    event_context.Context(**request_or_event.context))
  File "/user_code/main.py", line 14, in retrieve_and_log
    engine = create_engine(connection_string,echo=True)
  File "/env/local/lib/python3.7/site-packages/sqlalchemy/engine/__init__.py", line 500, in create_engine
    return strategy.create(*args, **kwargs)
  File "/env/local/lib/python3.7/site-packages/sqlalchemy/engine/strategies.py", line 56, in create
    plugins = u._instantiate_plugins(kwargs)
AttributeError: 'Context' object has no attribute '_instantiate_plugins'

这是我的代码的 sn-p:

import requests
from bs4 import BeautifulSoup
from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String

def retrieve_and_log(store_string, connection_string = 'mysql+pymysql://<username>:<password>/<dbname>?unix_socket=/cloudsql/<PROJECT-NAME>:<INSTANCE-REGION>:<INSTANCE-NAME>'):

    engine = create_engine(connection_string,echo=True)
    
    conn = engine.connect()
    # ....


【问题讨论】:

  • 如果您使用documentation 中使用的 SQLAlchemy 连接字符串构建器,是否也会发生这种情况?
  • @RafaelLemos,是的,它仍然发生了。达斯汀的回答成功了。

标签: python mysql google-cloud-platform sqlalchemy google-cloud-functions


【解决方案1】:

如果 retrieve_and_log 是您尝试部署为后台云函数的函数,则它需要如下签名:

def retrieve_and_log(data, context):
    ...

它不能带任意参数。

更多详情请见https://cloud.google.com/functions/docs/writing/background

【讨论】:

  • 太好了,很高兴听到!不要忘记将答案标记为已接受。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-05
  • 2020-06-28
  • 2017-11-25
  • 1970-01-01
  • 1970-01-01
  • 2018-04-19
  • 2017-05-02
相关资源
最近更新 更多