首页 > 解决方案 > Azure 上的 Python 函数应用中的全局变量

问题描述

我有一个 Azure 函数应用程序,其中我需要几个 python 函数中的当前日期时间(-3 小时)。

为了确保每个函数使用相同的时间,我在函数定义之前全局生成 datetime 对象,然后在函数内部使用它:

from datetime import datetime, timedelta
import pytz

# get the current time in the correct timezone. Since triggers are executed based on UTC, we then again subtract
#   3 hours (just to be save) to end up with the correct day
current_time = datetime.now(tz=pytz.timezone('Europe/Berlin'))
current_time -= timedelta(days=(3 / 24))

def _file_exists() -> bool:
    filename = current_time.strftime('%Y-%m-%d.csv')
    # ... further code


def main():
    save_as = '{path}/{filename}'.format(path=path_raw, filename=filename)
    # ... further code

我不需要修改内容,所以global那里没有关键字。

但是,当我将此函数发布到 azure(Python 3.8、Linux)时,它会解析脚本并将current_time变量设置为上传的日期时间,并且对于所有后续执行(timerTrigger)都是固定的。例如,我昨天上传了我的函数,然后logging.warning(current_time)main()输出中的命令2020-04-14 08:31:05.003618+02:00

如果我在本地尝试(Python 3.7、Windows、PyCharm),即使我手动对文件进行字节编译,它也可以正常工作:

python test.py    # 2020-04-15 11:30:36.426750+02:00
python test.py    # 2020-04-15 11:31:00.439632+02:00

python -m compileall .
python __pycache__/test.pyc # 2020-04-15 11:33:27.189967+02:00
python __pycache__/test.pyc # 2020-04-15 11:33:36.853601+02:00

这是天蓝色的错误吗?和/或最好的解决方法是什么?它是否与(im)可变类型有关,如果是,有没有人为这种情况解释它的链接(我知道类/函数参数中的行为)?

我考虑将其全局定义为,并在脚本中某处调用None的函数中设置该值。_init()

编辑:经过几次不成功的尝试后,我发现

# get the current time in the correct timezone. Since triggers are executed based on UTC, we then again subtract
#   3 hours (just to be save) to end up with the correct day
current_time = None


def _init_current_time():
    global current_time
    current_time = datetime.now(tz=pytz.timezone('Europe/Berlin')) - timedelta(days=(3 / 24))

def main():
    _init_current_time()
    # main code

做这项工作。到目前为止,我可以使用它,只是感觉非常……脏。那么,继续这个问题,是否有适当的解决方案?

标签: pythonazureglobal-variablesazure-function-app

解决方案


使用Python Timer Triggered Azure Function遇到了类似的问题。

使用一个包含时间戳的全局变量,该变量将用于创建我上传的 blob 的文件夹结构,例如/year/month/day/hour

注意到在函数的初始调用后值保持不变,这意味着如果函数在第二天触发,全局时间戳似乎仍然保持相同的值。注意到这是因为该函数将文件写入了错误的 blobstorage 文件夹。

对我来说,这些全局变量似乎只被初始化一次,然后就永远存在了。因此,Azure 函数运行时永远不会真正“关闭”并重新启动,__init__.py它只会触发主函数。

在我使用 HTTP 触发器之前,我没有遇到这个问题。因此,就我而言,这似乎只是 Timer 触发的天蓝色函数的问题。

也许对 Azure 运行时有更深入了解的人可能会更详细地解释这种行为以及为什么会发生这种情况?


推荐阅读