You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DRF应用移动端POST请求遇400错误未进入端点,如何排查修复?

DRF端点POST请求返回400但未进入视图/中间件的排查问题

问题场景

在Django Rest Framework(DRF)应用中,移动端调用/users/generate_otp/端点时返回400错误,但无法定位故障原因。仅部分用户的移动端出现此问题,其他用户正常;且使用Postman发送相同参数的请求时,端点返回成功。

移动端失败请求日志

Sep 02 11:11:29 myapp heroku/router at=info method=POST path="/users/generate_otp/?device_token=cBB2x2Y2L04qpQCbYukR31%3AAPA91bEHqCZ3ztI9wim0EzxVZ1Nv6clZMfsDxw7_6reWIVkm5dQcxuWlifnfxkn7Ope_2wTM75_TMw6BV-pAZyEYdrICz1dsk2gX6_aYJwz0-H3SDR2vLWvceiioUs21dTwXQIMwmBN1&mobile=%2B13104014335&device_type=ios" host=myhost.com request_id=fad10208-c01d-4f64-9640-1aff889ab3ee fwd="66.246.86.216" dyno=web.1 connect=0ms service=1ms status=400 bytes=28 protocol=https

Postman成功请求日志

Sep 02 11:41:48 myapp heroku/router at=info method=POST path="/users/generate_otp/?device_token=cKY2x2Y2L04qpQCbYukR31%3AAPA91bEHqCZ3ztI9wim0EzxVZ1Nv6clZMfsDxw7_6reWIVkm5dQcxuWlifnfxkn7Ope_2wTM75_TMw6BV-pAZyEYdrICz1dsk2gX6_aYJwz0-H3SDR2vLWvceiioUs21dTwXQIMwmBN1&mobile=%2B13104014335&device_type=ios" host=myhost.com request_id=4ddabe5f-619d-4665-aff5-28afb9ac277d fwd="66.246.86.216" dyno=web.1 connect=0ms service=572ms status=200 bytes=1686 protocol=https

已尝试的调试操作

  1. 视图内添加打印语句:在generate_otp方法开头添加打印逻辑,但语句从未执行,说明请求未进入视图:
@action(detail=False, methods=["POST"])
def generate_otp(self, request):
    """
    给指定手机号发送登录用一次性密码,若用户不存在则自动注册
    """
    print("IN GENERATE OTP", flush=True)
    print("IN GENERATE OTP, request.data =", request.data, flush=True)
    print("IN GENERATE OTP, request.headers =", request.headers, flush=True)
  1. 添加请求日志中间件:自定义中间件尝试打印请求详情,但无任何输出:
class RequestLoggingMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        print("--- RequestLoggingMiddleware ---")
        print(request.method, request.path)
        print(request.GET)
        print(request.POST)
        print(request.body)
        print("--------------------------------", flush=True)
        response = self.get_response(request)
        return response
  1. 配置调试与日志:在settings.py中设置DEBUG = True,并配置Django请求日志级别:
logger = logging.getLogger("django.request")
logger.setLevel(logging.DEBUG)

疑问

  • 该故障的可能原因是什么?
  • 哪些情况会导致请求未进入端点就返回400错误?
  • 如何进一步调试并修复此问题?

内容的提问来源于stack exchange,提问作者Dylan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 17:44:52