首页 > 编程问答 >如何使用 python 在 influxdb 中创建组织和存储桶

如何使用 python 在 influxdb 中创建组织和存储桶

时间:2024-07-30 14:59:52浏览次数:10  
标签:python influxdb influxdb-python

如何使用python在influxdb中创建组织和存储桶? 我有一个 python 脚本,用于在 influx db 中创建组织和存储桶,但它无法工作并返回未经授权的响应

任何人可以使用 influxdb api 帮助我解决这个问题吗?

HTTP response body: 
{   "code": "unauthorized",     "message": "write:orgs is unauthorized" }

Python 代码:

from influxdb_client import InfluxDBClient, BucketRetentionRules
from influxdb_client.rest import ApiException

def create_org_and_bucket(url, token, org_name, bucket_name, bucket_retention_days):
    # Convert retention days to seconds
    if bucket_retention_days == -1:
        bucket_retention_seconds = None  # No expiration
    else:
        bucket_retention_seconds = bucket_retention_days * 86400  # Convert days to seconds

    # Connect to InfluxDB
    client = InfluxDBClient(url=url, token=token)
    orgs_api = client.organizations_api()
    buckets_api = client.buckets_api()

    try:
        # Create organization
        org = orgs_api.create_organization(name=org_name)
        print(f"Organization '{org_name}' created successfully.")

        try:
            # Create bucket
            if bucket_retention_seconds is None:
                retention_rules = []
            else:
                retention_rules = [BucketRetentionRules(type="expire", every_seconds=bucket_retention_seconds)]

            bucket = buckets_api.create_bucket(name=bucket_name, org_id=org.id, retention_rules=retention_rules)
            print(f"Bucket '{bucket_name}' in organization '{org_name}' created successfully.")
            return org, bucket

        except ApiException as e:
            # If bucket creation fails, delete the created organization
            print(f"Error creating bucket: {e}")
            orgs_api.delete_organizations_id(org.id)
            print(f"Rolled back organization '{org_name}'.")
            return False

    except ApiException as e:
        print(f"Error creating organization: {e}")
        return False

    finally:
        # Close the connection to InfluxDB
        client.close()

url = "http://localhost:8086/"
token = ""
org_name = input("org name: ")
bucket_name = input("bucket name: ")
bucket_retention_days = -1

result = create_org_and_bucket(url, token, org_name, bucket_name, bucket_retention_days)
if result:
    org, bucket = result
    print(f"Successfully created organization '{org.name}' and bucket '{bucket.name}'.")
else:
    print("Failed to create organization and bucket.")

我尝试这个并还询问 gpt 和 Gemini,但它不起作用并返回相同的错误


根据错误消息“write:orgs is unauthorized”,你的问题出在用来连接 InfluxDB 的令牌上,它没有足够的权限来创建组织。

以下是如何使用 influxdb API 使用 Python 创建组织和存储桶的方法,以及如何解决权限问题:

1. 使用正确的令牌

  • InfluxDB v2 和 v1.8+:

    • 登录到 InfluxDB 用户界面。
    • 转到“数据”>“API 令牌”。
    • 生成一个新令牌,并赋予它以下权限:
      • write:orgs (用于创建组织)
      • read:orgs (用于读取组织信息)
      • write:buckets (用于创建存储桶)
    • 在你的 Python 脚本中使用此令牌。
  • InfluxDB v1.7 及更早版本:

    • InfluxDB 中没有用于管理组织和存储桶的细粒度权限。你需要使用具有管理员权限的令牌,该令牌通常在初始设置期间创建。

2. 验证你的代码

以下修改后的代码包含了错误处理和更清晰的注释:

from influxdb_client import InfluxDBClient, BucketRetentionRules
from influxdb_client.rest import ApiException

def create_org_and_bucket(url, token, org_name, bucket_name, bucket_retention_days):
    """创建组织和存储桶,如果发生错误,则回滚。

    Args:
        url (str): InfluxDB 实例的 URL。
        token (str): 具有适当权限的 InfluxDB API 令牌。
        org_name (str): 要创建的组织的名称。
        bucket_name (str): 要创建的存储桶的名称。
        bucket_retention_days (int): 存储桶的保留期限(以天为单位)。 使用 -1 表示无期限。

    Returns:
        tuple: 创建的组织和存储桶,如果发生错误,则返回 (False, False)。
    """

    try:
        # 使用提供的 URL 和令牌连接到 InfluxDB
        client = InfluxDBClient(url=url, token=token)

        # 获取组织和存储桶 API 的实例
        orgs_api = client.organizations_api()
        buckets_api = client.buckets_api()

        try:
            # 创建组织
            org = orgs_api.create_organization(name=org_name)
            print(f"组织 '{org_name}' 已成功创建。")

            try:
                # 创建存储桶保留规则(如果提供)
                if bucket_retention_days == -1:
                    retention_rules = []  # 无期限
                else:
                    retention_seconds = bucket_retention_days * 86400  # 将天数转换为秒数
                    retention_rules = [BucketRetentionRules(type="expire", every_seconds=retention_seconds)]

                # 创建具有指定保留规则的存储桶
                bucket = buckets_api.create_bucket(name=bucket_name, org_id=org.id, retention_rules=retention_rules)
                print(f"存储桶 '{bucket_name}' 在组织 '{org_name}' 中已成功创建。")
                return org, bucket

            except ApiException as e:
                # 如果创建存储桶失败,则删除已创建的组织
                print(f"创建存储桶时出错: {e}")
                orgs_api.delete_organizations_id(org.id)
                print(f"已回滚组织 '{org_name}'。")
                return False, False  # 在发生错误时返回 False 作为两个值的元组

        except ApiException as e:
            print(f"创建组织时出错: {e}")
            return False, False  # 在发生错误时返回 False 作为两个值的元组

    finally:
        # 关闭与 InfluxDB 的连接
        client.close()


# 从用户获取输入
url = "http://localhost:8086/" 
token = input("输入你的 InfluxDB 令牌:")  # 确保使用的是具有正确权限的令牌
org_name = input("组织名称:")
bucket_name = input("存储桶名称:")
bucket_retention_days = int(input("存储桶保留期限(以天为单位,-1 表示无期限):"))

# 创建组织和存储桶
result = create_org_and_bucket(url, token, org_name, bucket_name, bucket_retention_days)

# 检查创建操作是否成功
if result and result[0] is not False:  # 检查 result 是否是包含两个非 False 值的元组
    org, bucket = result
    print(f"已成功创建组织 '{org.name}' 和存储桶 '{bucket.name}'。")
else:
    print("无法创建组织和存储桶。")

确保使用具有正确权限的令牌,并且你的 InfluxDB 实例配置正确。 如果仍然遇到问题,请检查 InfluxDB 服务器日志以获取更多信息。

标签:python,influxdb,influxdb-python
From: 78810187

相关文章