3

我正在利用 InfluxDB 库的 SeriesHelper 对象(请查看 https://influxdb-python.readthedocs.io/en/latest/examples.html#tutorials-serieshelper)将一组数据点推送到 InfluxDB。SeriesHelper类必须被继承,子类需要初始化各种对象作为其元属性,从而覆盖 Parent 类中对象的默认值。

实际代码

class MySeriesHelper(SeriesHelper):
    """Instantiate SeriesHelper to write points to the backend."""

    class Meta:
        """Meta class stores time series helper configuration."""
        client = myclient
        series_name = 'rf_results'
        fields = ['some_stat', 'other_stat']
        tags = ['server_name']
        bulk_size = 5
        autocommit = True

这里的“series_name”对象在它作为脚本运行之前被初始化(硬编码)。我的用例是根据传递给此脚本的运行时参数初始化“series_name” 。我尝试定义一个全局变量,其值在运行时提供,并将该全局变量分配给下面的“series_name”,但徒劳无功。

有问题的代码

series_configured = None
class MySeriesHelper(SeriesHelper):
    """Instantiate SeriesHelper to write points to the backend."""

    class Meta:
        """Meta class stores time series helper configuration."""
        client = myclient
        series_name = series_configured
        fields = ['some_stat', 'other_stat']
        tags = ['server_name']
        bulk_size = 5
        autocommit = True

def main():
    global series_configured
    series_configured = args.series_name

    MySeriesHelper(server_name='server_A', some_stat='Master server', other_stat='Controller')
    MySeriesHelper.commit()

if __name__ == "__main__":
    parser = argparse.ArgumentParser()

    parser.add_argument("--series_name", dest='series_name', 
                        help="The measurement to be used for storing the data points",required=True)
    args = parser.parse_args()
    main()

运行时看到的错误是

“NoneType”对象没有属性“格式”

它推断对象“series_name”未使用值初始化。有什么方法可以正确初始化它吗?

4

1 回答 1

1

python 解释器遍历代码(逐行)时,它定义了所有类的静态变量。在从类创建实例之前设置静态变量。这意味着当您达到以下目标时:

autocommit = True

的值series_name已设置为None(因为那是该series_configured点的值)。

以下示例显示在我创建实例之前已经设置了静态变量:

>>> series_configured = None
>>> class MySeriesHelper:
    """Instantiate SeriesHelper to write points to the backend."""

    class Meta:
        """Meta class stores time series helper configuration."""
        series_name = series_configured
        fields = ['some_stat', 'other_stat']
        tags = ['server_name']
        bulk_size = 5
        autocommit = True

>>> print(MySeriesHelper.Meta.series_name)
None

如果要更改Meta.series_configured 静态变量,则必须在series_configured更改其内容后对其进行设置。

尝试以下主要。

def main():
    global series_configured
    series_configured = args.series_name
    # The following line will set the variable at the inner Meta class.
    MySeriesHelper.Meta.series_name = series_configured

    MySeriesHelper(server_name='server_A', some_stat='Master server', other_stat='Controller')
    MySeriesHelper.commit()
于 2019-12-31T14:06:24.563 回答