英文:
StringParam not working in python Cloud Function Gen2 for global vars
问题
我使用新的云函数 gen 2 在 Python 中,遵循这个 指南 和这个代码示例:
from firebase_functions import https_fn
from firebase_functions.params import IntParam, StringParam
MIN_INSTANCES = IntParam("HELLO_WORLD_MIN_INSTANCES")
WELCOME_MESSAGE = StringParam("WELCOME_MESSAGE")
# 要在函数的配置中使用配置的参数,请直接提供它们。要在运行时使用它们,请在其上调用 .value()。
@https_fn.on_request(min_instances=MIN_INSTANCES)
def hello_world(req):
return https_fn.Response(f'{WELCOME_MESSAGE.value()}! I am a function!')
我遇到运行时错误,原因如下:
- 第一个问题是
.value()
是一个字符串,所以不可调用,我们需要使用.value
。 - 第二个问题是
WELCOME_MESSAGE.value
似乎在全局变量加载时还没有准备好。
在我的代码中:
db_url = StringParam("DB_URL")
db_name = StringParam("DB_NAME")
client = MongoClient(db_url.value)
db = client.get_database(db_name.value)
抛出异常 pymongo.errors.ConfigurationError: Empty host (or extra comma in host list)
。
这个变量似乎是从这个消息中加载的:i functions: Loaded environment variables from .env.
注意:如果我在函数内部使用 print
打印该值,它是有效的,所以参数对于全局变量不可用吗?
提前感谢!
英文:
I am using the new Cloud Function gen 2 in python and following this guide and this code sample :
from firebase_functions import https_fn
from firebase_functions.params import IntParam, StringParam
MIN_INSTANCES = IntParam("HELLO_WORLD_MIN_INSTANCES")
WELCOME_MESSAGE = StringParam("WELCOME_MESSAGE")
# To use configured parameters inside the config for a function, provide them
# directly. To use them at runtime, call .value() on them.
@https_fn.on_request(min_instances=MIN_INSTANCES)
def hello_world(req):
return https_fn.Response(f'{WELCOME_MESSAGE.value()}! I am a function!')
I have runtime errors because :
- First
.value()
isstr
so it's not callable, we need to use.value
- Second,
WELCOME_MESSAGE.value
seems to not be loaded on time for global vars
In my code :
db_url = StringParam("DB_URL")
db_name = StringParam("DB_NAME")
client = MongoClient(db_url.value)
db = client.get_database(db_name.value)
Throws an exception pymongo.errors.ConfigurationError: Empty host (or extra comma in host list)
.
The var seems to be loaded from this message : i functions: Loaded environment variables from .env.
Note : if i print
the value inside a function, it's working, so are parameters not available for global vars ?
Thanks in advance
答案1
得分: 1
看起来你遇到了与nodejs这个问题相似的问题,解决方法是仅在函数调用时请求参数的值,而不是在全局范围内请求。
我只能想象在Python中也是同样的工作方式。如果在先前的调用中尚未初始化全局变量,你应该考虑在函数被调用后进行延迟初始化。
英文:
It looks like you're having the same sort of problem as this question for nodejs, where the solution was to only request the values of parameters when the function is invoked, and not at the global scope.
I can only imagine it works the same way for python. You should consider lazy-initializing the globals after the function is invoked, if they were not already in a prior invocation.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论