大家好,
我正在使用 Python 通过 Discourse API 创建用户。用户创建请求返回了一个成功响应,但我遇到了一个问题:即使我在请求体中明确将其设置为 true,响应中的 active 属性始终为 false。confirmed 属性设置为 true,并且工作正常。
这是代码:
import csv
import requests
import json
from datetime import datetime
# Discourse API 详细信息
discourse_url = "https://forum.hobiguru.com/" # 替换为您的 Discourse URL
api_key = "your-api-key" # 替换为您的 Discourse API 密钥
api_username = "system" # 管理员用户名
# 请求头
headers = {
"Api-Key": api_key,
"Api-Username": api_username,
"Content-Type": "application/json"
}
# 创建用户的函数
def create_user(username, name, email, password, bio, location, confirmed, active, join_date):
url = f"{discourse_url}/users.json"
join_date_str = join_date.strftime('%Y-%m-%dT%H:%M:%SZ')
payload = {
"name": name,
"email": email,
"password": password,
"username": username,
"active": True, # 默认设置为 True
"confirmed": True, # 默认设置为 True
"created_at": join_date_str
}
print(f"\n请求 URL: {url}")
print(f"请求头: {json.dumps(headers, indent=2)}")
print(f"请求体: {json.dumps(payload, indent=2)}")
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 200:
response_json = response.json()
if response_json.get("success"):
print(f"用户创建成功: {json.dumps(response_json, indent=2)}")
else:
print(f"用户创建失败。原因: {response_json.get('message')}")
print(f"错误: {json.dumps(response_json.get('errors'), indent=2)}")
else:
print(f"请求失败: {response.status_code}, {response.text}")
# 从 CSV 文件读取用户
with open('input_users.csv', mode='r', encoding='utf-8') as file:
reader = csv.DictReader(file)
for row in reader:
# 从行中提取用户详细信息
create_user(row['Username'], row['Name'], row['Email'], row['Password'], row['Bio'], row['Location'], row['Confirmed'] == 'TRUE', row['Active'] == 'TRUE', datetime.strptime(row['Join Date'], '%Y-%m-%dT%H:%M:%SZ'))
我收到了以下打印输出:
请求创建用户的请求
{'name': 'Goran', 'email': 'bla+blaaa@gmail.com', 'password': 'P@ssword!23', 'username': 'goran12', 'active': True, 'confirmed': True, 'created_at': '2024-11-04T10:20:34Z'}
请求 URL: https://forum.hobiguru.com/users.json
请求头:
{
"Api-Key": "d9---------------e564d65d9b5a3",
"Api-Username": "system",
"Content-Type": "application/json"
}
请求体:
{
"name": "Goran",
"email": "'bla+blaaa@gmail.com",
"password": "P@ssword!23",
"username": "goran12",
"active": true,
"confirmed": true,
"created_at": "2024-11-04T10:20:34Z"
}
响应:
完整响应: {
"success": true,
"active": false,
"message": "Vaš račun je aktiviran i spreman za korištenje."
}
请求成功,用户已创建:
{'success': True, 'active': False, 'message': 'Vaš račun je aktiviran i spreman za korištenje.'}
问题:
- 尽管在请求体中传递了 “active”: True,但响应中的
active属性始终为 false,并且我在 Discourse 管理面板中查找用户时找不到任何用户。 - API 返回 success: true,但用户似乎并未完全激活。
问题:
- 我的请求中是否有遗漏的内容可能导致
active属性未正确设置? - Discourse API 中是否有任何特定条件会覆盖
active属性,即使它被明确设置为 true?
任何见解或建议都将不胜感激!

