python - 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
做这项工作。到目前为止,我可以使用它,只是感觉非常……脏。那么,继续这个问题,是否有适当的解决方案?
解决方案
使用Python Timer Triggered Azure Function遇到了类似的问题。
我使用一个包含时间戳的全局变量,该变量将用于创建我上传的 blob 的文件夹结构,例如/year/month/day/hour
。
我注意到在函数的初始调用后值保持不变,这意味着如果函数在第二天触发,全局时间戳似乎仍然保持相同的值。注意到这是因为该函数将文件写入了错误的 blobstorage 文件夹。
对我来说,这些全局变量似乎只被初始化一次,然后就永远存在了。因此,Azure 函数运行时永远不会真正“关闭”并重新启动,__init__.py
它只会触发主函数。
在我使用 HTTP 触发器之前,我没有遇到这个问题。因此,就我而言,这似乎只是 Timer 触发的天蓝色函数的问题。
也许对 Azure 运行时有更深入了解的人可能会更详细地解释这种行为以及为什么会发生这种情况?
推荐阅读
- javascript - 改变
- python - 换行到txt文件python
- spring-boot - spring rest api 无法设置 Set-Cookie
- java - 如何创建从队列执行随机任务的线程池
- ios - 如何修复 SafeAreaLayoutGuide
- javascript - 与我的实时站点集成时,隐藏和显示 div 的 JQuery 代码不起作用
- sql - CASE WHEN 具有特定条件和范围条件
- authentication - 通过 REST 进行 Office 365 身份验证,无需注册应用程序
- web-applications - 我可以让 Web 客户端访问数据库吗?
- java - 回收站聊天分页在顶部添加新消息