遵循InfluxDB Python教程操作持续触发401未授权访问错误求助
问题背景
严格遵循InfluxDB官方Python入门教程操作,使用教程提供的代码,通过环境变量配置了全权限access token、对应环境的org和host,所有依赖已安装,但持续触发401 Unauthorized未授权访问错误,多次重置access token仍无法解决。
错误日志
>>> Request: 'POST https://us-east-1-1.aws.cloud2.influxdata.com/api/v2/write?org=PythonTesting&bucket=test1&precision=ns' >>> Content-Type: text/plain >>> Accept: application/json >>> User-Agent: influxdb-client-python/1.37.0 >>> Body: b'census,location=Klamath bees=23i' <<< Response: 401 <<< Date: Wed, 30 Aug 2023 17:15:22 GMT <<< Content-Type: application/json; charset=utf-8 <<< Content-Length: 55 <<< Connection: keep-alive <<< trace-id: a96c933eaca5845f <<< trace-sampled: false <<< x-platform-error-code: unauthorized <<< Strict-Transport-Security: max-age=15724800; includeSubDomains <<< X-Influxdb-Request-ID: 130ba81a98d7d837641571be3fabc194 <<< X-Influxdb-Build: Cloud <<< Body: {"code":"unauthorized","message":"unauthorized access"} Traceback (most recent call last): File "C:\Users\user G\PycharmProjects\MEAfile_parsing\InfluxDB_testing.py", line 51, in <module> client.write(database=database, record=point) File "C:\Users\user\PycharmProjects\MEAfile_parsing\venv\lib\site-packages\influxdb_client_3\__init__.py", line 106, in write raise e File "C:\Users\user\PycharmProjects\MEAfile_parsing\venv\lib\site-packages\influxdb_client_3\__init__.py", line 104, in write self._write_api.write(bucket=database, record=record, **kwargs) File "C:\Users\user\PycharmProjects\MEAfile_parsing\venv\lib\site-packages\influxdb_client\client\write_api.py", line 378, in write results = list(map(write_payload, payloads.items())) File "C:\Users\user\PycharmProjects\MEAfile_parsing\venv\lib\site-packages\influxdb_client\client\write_api.py", line 376, in write_payload return self._post_write(_async_req, bucket, org, final_string, payload[0]) File "C:\Users\user\PycharmProjects\MEAfile_parsing\venv\lib\site-packages\influxdb_client\client\write_api.py", line 509, in _post_write return self._write_service.post_write(org=org, bucket=bucket, body=body, precision=precision, File "C:\Users\user\PycharmProjects\MEAfile_parsing\venv\lib\site-packages\influxdb_client\service\write_service.py", line 60, in post_write (data) = self.post_write_with_http_info(org, bucket, body, **kwargs) # noqa: E501 File "C:\Users\user\PycharmProjects\MEAfile_parsing\venv\lib\site-packages\influxdb_client\service\write_service.py", line 90, in post_write_with_http_info return self.api_client.call_api( File "C:\Users\user\PycharmProjects\MEAfile_parsing\venv\lib\site-packages\influxdb_client\_sync\api_client.py", line 343, in call_api return self.__call_api(resource_path, method, File "C:\Users\user\PycharmProjects\MEAfile_parsing\venv\lib\site-packages\influxdb_client\_sync\api_client.py", line 173, in __call_api response_data = self.request( File "C:\Users\user\PycharmProjects\MEAfile_parsing\venv\lib\site-packages\influxdb_client\_sync\api_client.py", line 388, in request return self.rest_client.POST(url, File "C:\Users\user\PycharmProjects\MEAfile_parsing\venv\lib\site-packages\influxdb_client\_sync\rest.py", line 311, in POST return self.request("POST", url, File "C:\Users\user\PycharmProjects\MEAfile_parsing\venv\lib\site-packages\influxdb_client\_sync\rest.py", line 261, in request raise ApiException(http_resp=r) influxdb_client.rest.ApiException: (401) Reason: Unauthorized HTTP response headers: HTTPHeaderDict({'Date': 'Wed, 30 Aug 2023 17:15:22 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': '55', 'Connection': 'keep-alive', 'trace-id': 'a96c933eaca5845f', 'trace-sampled': 'false', 'x-platform-error-code': 'unauthorized', 'Strict-Transport-Security': 'max-age=15724800; includeSubDomains', 'X-Influxdb-Request-ID': '130ba81a98d7d837641571be3fabc194', 'X-Influxdb-Build': 'Cloud'}) HTTP response body: {"code":"unauthorized","message":"unauthorized access"} Process finished with exit code 1
使用代码
import os, time from influxdb_client_3 import InfluxDBClient3, Point token = os.environ.get("INFLUXDB_TOKEN") # 通过环境变量配置的全权限token org = "PythonTesting" host = "myhost" # AWS提供的host地址 client = InfluxDBClient3(host=host, token=token, org=org, debug=True) database="test1" data = { "point1": { "location": "Klamath", "species": "bees", "count": 23, }, "point2": { "location": "Portland", "species": "ants", "count": 30, }, "point3": { "location": "Klamath", "species": "bees", "count": 28, }, "point4": { "location": "Portland", "species": "ants", "count": 32, }, "point5": { "location": "Klamath", "species": "bees", "count": 29, }, "point6": { "location": "Portland", "species": "ants", "count": 40, }, } for key in data: point = ( Point("census") .tag("location", data[key]["location"]) .field(data[key]["species"], data[key]["count"]) ) client.write(database=database, record=point) time.sleep(1) # 每个点间隔1秒 print("Complete. Return to the InfluxDB UI.")
解决方案
验证环境变量加载正确性
在代码开头添加print(f"Token loaded: {token is not None}"),确认token不为空。如果输出False,说明环境变量未正确加载:Windows系统需重启IDE或终端生效,检查环境变量名是否拼写正确(如INFLUXDB_TOKEN是否少写字符)。确认Token与Org/Bucket的绑定关系
登录InfluxDB控制台,检查token所属的org是否为PythonTesting,且该token拥有test1bucket的写入权限(全权限token需确保创建时未选错org)。检查Org名称大小写匹配
InfluxDB的org名称大小写敏感,确保代码中的PythonTesting与控制台显示的名称完全一致,避免因大小写差异导致授权失败。修正Host地址格式
Host地址无需带https://前缀,将代码中的host改为us-east-1-1.aws.cloud2.influxdata.com(去掉协议头),避免客户端拼接地址时出现错误。确认Bucket归属
检查test1bucket是否确实属于PythonTestingorg,避免误操作将bucket创建到其他org下。临时硬编码Token测试
暂时将token直接写入代码(测试完成后务必删除),如token="你的实际token",排除环境变量加载问题,确认token本身是否有效。
内容的提问来源于stack exchange,提问作者Cai Lewendon

