python - SQLAlchemy create_engine 在谷歌云函数中不起作用
问题描述
我正在尝试运行一个谷歌云函数,该函数从网站上收集数据,然后将其插入到 Cloud SQL (MySQL) 数据库中,但是在我的本地计算机上没有出现在云中的 SQLAlchemy 问题。有什么建议么!?
当我使用 Cloud SQL 代理和 SQLAlchemy 在本地针对 Py3.7(在 Mac 上,不使用 virtualenv)运行该函数时,我成功连接到数据库。
运行 Cloud Function 时,我使用这种格式的连接字符串mysql+pymysql://<username>:<password>/<dbname>?unix_socket=/cloudsql/<PROJECT-NAME>:<INSTANCE-REGION>:<INSTANCE-NAME>
。
云函数不断为 SQLAlchemy.create_engine 抛出以下异常。它似乎与能够连接无关,而是由于实例化。
一切都在同一个项目中。
我也尝试过使用格式的公共 IP 和连接字符串mysql+pymysql://<username>:<password>@<public ip address>:3306/<dbname>
,这没有任何区别。
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'
这是我的代码片段:
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()
# ....
解决方案
如果retrieve_and_log
是您尝试部署为后台云功能的功能,它需要一个签名,例如:
def retrieve_and_log(data, context):
...
它不能采用任意参数。
有关更多详细信息,请参阅https://cloud.google.com/functions/docs/writing/background。
推荐阅读
- couchdb - 在 CouchDB 上清除包含特殊字符的文档
- php - mysql regex - 过滤大于 XX 后跟特定字符串的数字
- php - 通过 PHP CurlFile 上传文件从 cron 失败
- caching - 是否会使用 BAN 从 Varnish 中移除 hit-for-miss 和 hit-for-pass
- firebase - 如何刷新 Firebase 会话 Cookie?(auth/session-cookie-过期)
- ios - 在 URL 中使用自动登录令牌进行 iOS 深度链接
- python - 听不到我想用 pygame 播放的声音
- laravel - Laravel - 如何根据下拉列表值隐藏 div 元素
- ruby-on-rails - YearsController:Class 的未定义方法“before_save”你是说什么?before_action
- c# - WPF 中 Telerik RadNumericUpDown 的默认值