属性错误:更新事务中的日期时间时出现_纳秒

问题描述 投票:0回答:2

所以我尝试通过云函数更新云Firestore中的日期时间字段,如下所示:

transaction.update(doc_ref, {'dateTimeField1': dateTimeValue})

Google 在云函数的事件参数中以字符串形式发送日期时间对象,格式为

%Y-%m-%dT%H:%M:%SZ
%Y-%m-%dT%H:%M:%S.%fZ

例如:
2019-01-25T15:25:03.881Z

我将其转换为日期时间对象,如下所示:

try:
    datetime_obj = datetime.datetime.strptime(datetime_obj, '%Y-%m-%dT%H:%M:%S.%fZ')
except:
    datetime_obj = datetime.datetime.strptime(datetime_obj, '%Y-%m-%dT%H:%M:%SZ')
datetime_obj = datetime_obj.replace(tzinfo=timezone('UTC'))

但是当我尝试执行该操作时,出现以下错误:

AttributeError: _nanosecond

追溯:

File "/env/local/lib/python3.7/site-packages/google/cloud/firestore_v1beta1/batch.py", line 112, in update
    reference._document_path, field_updates, option
  File "/env/local/lib/python3.7/site-packages/google/cloud/firestore_v1beta1/_helpers.py", line 822, in pbs_for_update
    update_pb = extractor.get_update_pb(document_path)
  File "/env/local/lib/python3.7/site-packages/google/cloud/firestore_v1beta1/_helpers.py", line 459, in get_update_pb
    name=document_path, fields=encode_dict(self.set_fields)
  File "/env/local/lib/python3.7/site-packages/google/cloud/firestore_v1beta1/_helpers.py", line 215, in encode_dict
    return {key: encode_value(value) for key, value in six.iteritems(values_dict)}
  File "/env/local/lib/python3.7/site-packages/google/cloud/firestore_v1beta1/_helpers.py", line 215, in <dictcomp>
    return {key: encode_value(value) for key, value in six.iteritems(values_dict)}
  File "/env/local/lib/python3.7/site-packages/google/cloud/firestore_v1beta1/_helpers.py", line 169, in encode_value
    return document_pb2.Value(timestamp_value=value.timestamp_pb())
  File "/env/local/lib/python3.7/site-packages/google/api_core/datetime_helpers.py", line 278, in timestamp_pb
    nanos = self._nanosecond or self.microsecond * 1000
AttributeError: _nanosecond

是否允许通过交易设置日期时间,还是我在这里遗漏了一些东西?

编辑:
代码片段:

@firestore.transactional
def update_datetime_field(transaction, doc_ref, datetime_value):
    try:
        datetime_obj = datetime.datetime.strptime(datetime_value, '%Y-%m-%dT%H:%M:%S.%fZ')
    except:
        datetime_obj = datetime.datetime.strptime(datetime_value, '%Y-%m-%dT%H:%M:%SZ')
    datetime_obj = datetime_obj.replace(tzinfo=timezone('UTC'))
    # Example of datetime_obj -> datetime.datetime(2019, 1, 25, 15, 25, 3, 881000, tzinfo=<UTC>)
    transaction.update(doc_ref, {'datetimeField1': datetime_obj})
    return True

更多信息:

  1. 当文档更新时,上面的代码会被触发
    collection1/document1/collection2/document2
  2. datetime 对象是来自标准库的 python 日期时间
  3. 我正在尝试通过使用 pytz 更改时区来将日期转换为 UTC

编辑2:

更好的完整图:

from firebase_admin import credentials, firestore

# initialize firebase admin sdk
creds = credentials.ApplicationDefault()
firebase_admin.initialize_app(creds,{'projectId': 'myProjectId'})


@firestore.transactional
def update_datetime_field(transaction, doc_ref, datetime_value):
    try:
        datetime_obj = datetime.datetime.strptime(datetime_value, '%Y-%m-%dT%H:%M:%S.%fZ')
    except:
        datetime_obj = datetime.datetime.strptime(datetime_value, '%Y-%m-%dT%H:%M:%SZ')
    datetime_obj = datetime_obj.replace(tzinfo=timezone('UTC'))
    # Example of datetime_obj -> datetime.datetime(2019, 1, 25, 15, 25, 3, 881000, tzinfo=<UTC>)
    transaction.update(doc_ref, {'datetimeField1': datetime_obj})
    return True

def update_datetime_in_transaction(event, context):
    datetime_value = event['value']['fields']['datetimeField1']['timestampValue']
    # this looks something like 2019-01-25T15:25:03.881Z

    # prepare document reference to document
    doc_ref = prepare_doc_ref(event, context)

    # update_datetime_field
    client = firestore.client()
    transaction = client.transaction()
    update_datetime_field(transaction, doc_ref, datetime_value)

    return True

编辑3:

事件参数截图: enter image description here

控制台截图:
enter image description here

python firebase transactions google-cloud-firestore firebase-admin
2个回答
8
投票

因此 firestore python sdk 需要

_nanosecond
属性,该属性目前在 python 标准库的日期时间中不可用(将来会添加。更多详细信息这里

因此,在检查了他们的代码库之后,我发现了一个名为

DatetimeWithNanoseconds
的类,它为传统日期时间对象添加了纳秒支持

该类的代码(google/api_core 中的 datetime_helpers.py 文件)如下(为简洁起见,故意删除了一些部分):

class DatetimeWithNanoseconds(datetime.datetime):
"""Track nanosecond in addition to normal datetime attrs.

Nanosecond can be passed only as a keyword argument.
"""
__slots__ = ('_nanosecond',)

@classmethod
def from_rfc3339(cls, stamp):
    with_nanos = _RFC3339_NANOS.match(stamp)
    if with_nanos is None:
        raise ValueError(
            'Timestamp: {}, does not match pattern: {}'.format(
                stamp, _RFC3339_NANOS.pattern))
    bare = datetime.datetime.strptime(
        with_nanos.group('no_fraction'), _RFC3339_NO_FRACTION)
    fraction = with_nanos.group('nanos')
    if fraction is None:
        nanos = 0
    else:
        scale = 9 - len(fraction)
        nanos = int(fraction) * (10 ** scale)
    return cls(bare.year, bare.month, bare.day,
               bare.hour, bare.minute, bare.second,
               nanosecond=nanos, tzinfo=pytz.UTC)

所以现在,我可以使用此类而不是

datetime.datetime
来解析使用
DatetimeWithNanoseconds.from_rfc3339(timestamp)
方法在云函数的事件参数中作为字符串发送的日期时间。

示例:

from google.api_core.datetime_helpers import DatetimeWithNanoseconds

d1 = DatetimeWithNanoseconds.from_rfc3339('2019-01-25T15:25:03.881Z')
print(d1)
# DatetimeWithNanoseconds(2019, 1, 25, 15, 25, 3, 881000, tzinfo=<UTC>)

该类还有

rfc3339()
方法来为您提供字符串表示形式。

示例:

d1.rfc3339()
# 2019-01-25T15:25:03.881Z

替代解决方案:

您也可以使用

pandas.Timestamp()
代替
DatetimeWithNanoseconds.from_rfc3339()

示例:

import pandas as pd

d1 = pd.Timestamp('2019-01-25T15:25:03.881Z')
print(d1)
# Timestamp('2019-01-25 15:25:03.881000+0000', tz='UTC')

我建议使用

DatetimeWithNanoseconds
,因为它与 sdk 一起提供,并且您无需在
requirements.txt
中添加额外的 pandas 依赖项,这会增加冷启动期间的调用延迟。更多详情这里

希望这有帮助。


0
投票

目前 Firestore Python SDK 支持标准日期时间对象来添加/更新记录。例如添加/更新到 datetime.datetime.now(datetime.timezone.utc) - 没问题。

写这篇文章是因为我遇到了同样的异常。背景是,我首先从现有数据库记录中获取包含类似日期时间对象的记录(不是Python的标准日期时间,而是DatetimeWithNanoseconds),然后使用“替换”方法对其进行修改,最后发出包含更改后的日期时间的更新请求-就像数据库的对象一样。 问题的原因是“侵入性”“替换”方法从 DatetimeWithNanoseconds 对象中删除了纳秒属性。 其他一些修改(例如添加 timedelta 对象)没有任何问题。

© www.soinside.com 2019 - 2024. All rights reserved.