Django中GET/PUT测试命令报错,咨询正确测试方法及问题原因
Django CRUD接口GET/PUT报错排查与修正
问题描述
POST和DELETE接口测试正常,对应的curl命令:
curl -X POST http://localhost:8000/user/ -H "Content-Type: application/json" -d "{\"username\": \"john_doe\", \"email\": \"john@example.com\", \"first_name\": \"John\", \"last_name\": \"Doe\"}" curl -X DELETE http://localhost:8000/user/john_doe/
但执行GET、PUT命令时报错:
curl -X GET http://localhost:8000/user/john_doe/ curl -X PUT http://localhost:8000/user/john_doe/ -H "Content-Type: application/json" -d "{\"email\": \"john.new@example.com\"}"
问题原因
- URL路由冲突:
urls.py中重复定义了path('user/<username>/'),Django路由匹配从上到下执行,所有请求都会命中第一个绑定的delete_user视图,而该视图仅处理DELETE方法,GET/PUT请求无法得到正确响应。 - update_user视图参数错误:
pymongo的update_one第一个参数需要查询条件字典(如{'username': username}),而非直接传username;且该视图未返回任何响应,会触发服务器错误。 - view_user视图序列化问题:MongoDB返回的文档包含
ObjectId类型,JsonResponse无法直接序列化该类型,会抛出序列化异常。
修正后的代码
urls.py
将同一路径的多方法请求合并到单个视图,避免路由冲突:
from django.urls import path from . import views urlpatterns = [ path('user/', views.create_user), path('user/<username>/', views.user_detail), ]
views.py
修复参数错误、序列化问题,并统一处理同一路径的GET/PUT/DELETE方法:
import json import pymongo from bson.objectid import ObjectId from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt client = pymongo.MongoClient('mongodb://localhost:27017/') database = client['PoseTrack_Database'] users = database['users'] def serialize_user(user): # 将MongoDB的ObjectId转换为字符串,支持JsonResponse序列化 if user: user['_id'] = str(user['_id']) return user @csrf_exempt def create_user(request): if request.method == 'POST': user_data = json.loads(request.body) users.insert_one(user_data) return JsonResponse({'status': 'success', 'message': 'User created successfully!'}, status=201) return JsonResponse({'status': 'error', 'message': 'Method not allowed'}, status=405) @csrf_exempt def user_detail(request, username): if request.method == 'GET': user = users.find_one({'username': username}) if not user: return JsonResponse({'status': 'error', 'message': 'User not found'}, status=404) return JsonResponse(serialize_user(user)) elif request.method == 'PUT': new_data = json.loads(request.body) result = users.update_one({'username': username}, {'$set': new_data}) if result.matched_count == 0: return JsonResponse({'status': 'error', 'message': 'User not found'}, status=404) return JsonResponse({'status': 'success', 'message': 'User updated successfully!'}) elif request.method == 'DELETE': result = users.delete_one({'username': username}) if result.deleted_count == 0: return JsonResponse({'status': 'error', 'message': 'User not found'}, status=404) return JsonResponse({'status': 'success', 'message': 'User deleted successfully!'}, status=200) return JsonResponse({'status': 'error', 'message': 'Method not allowed'}, status=405)
正确测试命令(执行顺序)
- 创建用户
curl -X POST http://localhost:8000/user/ -H "Content-Type: application/json" -d "{\"username\": \"john_doe\", \"email\": \"john@example.com\", \"first_name\": \"John\", \"last_name\": \"Doe\"}"
- 查询用户
curl -X GET http://localhost:8000/user/john_doe/
- 更新用户
curl -X PUT http://localhost:8000/user/john_doe/ -H "Content-Type: application/json" -d "{\"email\": \"john.new@example.com\"}"
- 删除用户
curl -X DELETE http://localhost:8000/user/john_doe/
内容的提问来源于stack exchange,提问作者marc.mitrasca
相关产品推荐
相关产品推荐

