gpt4 book ai didi

python - 类型错误 : tuple indices must be integers, 不是 str Python/django

转载 作者:行者123 更新时间:2023-11-29 18:27:36 26 4
gpt4 key购买 nike

我遇到了一个错误:

cursor = connection.cursor()

cursor.execute("SELECT username as username, sum(ACCTSESSIONTIME) as total_acctsessiontime FROM RADUSAGE GROUP BY username LIMIT 0, 10")

usage_summary = cursor.fetchall()

for row in usage_summary:
row['total_acctsessiontime'] = 0 if row['total_acctsessiontime'] is None else humanize_seconds(row['total_acctsessiontime'])
row['total_acctinputoctets'] = 0 if row['total_acctinputoctets'] is None else naturalsize(row['total_acctinputoctets'])
row['total_acctoutputoctets'] = 0 if row['total_acctoutputoctets'] is None else naturalsize(row['total_acctoutputoctets'])

return jsonify(cursor)

错误:

Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 42, in inner
response = get_response(request)
File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/loc_rad/admin_app/dashboard.py", line 57, in inquiry
row['total_acctsessiontime'] = 0 if row['total_acctsessiontime'] is None else humanize_seconds(row['total_acctsessiontime'])
TypeError: tuple indices must be integers, not str

这是我第一次使用光标连接。我希望有人能帮助我解决这个问题。

最佳答案

cursor.fetchall() 返回元组。在你的情况下,这个元组将是这样的:(('用户名1', 100), ('用户名2', 200),)

要使用此方法row['total_acctsessiontime'],您应该每次在循环中创建字典,或者这样做

items = {'username': 0, 'total_acctoutputoctets': 1}
for row in usage_summary:
row[item['total_acctsessiontime']] = 0 if row[item['total_acctsessiontime']] is None else humanize_seconds(row[item['total_acctsessiontime']])

但简单的方法是:

for row in usage_summary:
row[1] = 0 if row[1] is None else humanize_seconds(row[1])

更新1

acctsessiontime, acctoutputoctets, acctinputoctets == [], [], []
for row in usage_summary:
acctsessiontime.append(0 if row[1] is None else humanize_seconds(row[1]))
acctoutputoctets.append(0 if row[1] is None else humanize_seconds(row[1]))
acctinputoctets.append(0 if row[1] is None else humanize_seconds(row[1]))
all_sum = sum(acctsessiontime) + sum(acctoutputoctets) + sum(acctinputoctets)

关于python - 类型错误 : tuple indices must be integers, 不是 str Python/django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46032202/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com