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

Django静态JSON接口500 TypeError问题排查

问题描述

接触Python/Django仅5天,已完成注册API开发:接收请求中的username、password、password2字段,通过django.contrib.auth.models.User类存储用户信息,用户名重复时返回“username is duplicate”提示,已解决存储后响应过大的问题。

现需开发GET接口返回预存的stations.json文件(路径为register/static/stations.json),已在settings.py中配置STATICFILES_DIRS、STATIC_URL、STATIC_ROOT,并完成views.py和urls.py的对应配置,但请求http://127.0.0.1:8000/api/stations/时出现500 Internal Server Error(TypeError),需排查解决。


相关代码

settings.py

STATICFILES_DIRS = [
   os.path.join(BASE_DIR, 'register/static/')
]
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

views.py

from django.shortcuts import render
from django.contrib.auth.models import User
from .serializers import RegisterSerializer
from rest_framework import generics
from django.http import JsonResponse
from django.conf import settings
import json

class RegisterView(generics.CreateAPIView):
    queryset = User.objects.all()
    serializer_class = RegisterSerializer
    
def get_stations(request):
    with open(settings.STATICFILES_DIRS[0] + '/stations.json', 'r') as f:
        data = json.load(f)
    return JsonResponse(data)

register/urls.py

from django.urls import path
from register.views import RegisterView
from . import views

urlpatterns = [
    path('register/', RegisterView.as_view(), name='auth_register'),
    path('stations/', views.get_stations, name='get_stations'),
]

setup/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('api/', include('register.urls')),
]

排查与解决

核心问题分析

触发TypeError的主要原因有两点:

  1. 路径拼接不规范:直接用字符串+拼接路径可能出现格式异常(如重复斜杠),且不具备跨平台兼容性;
  2. JsonResponse参数缺失:若stations.json内容为列表结构,JsonResponse默认不允许直接返回非字典类型数据,未指定safe=False会抛出TypeError。

修复步骤

1. 规范路径拼接

使用os.path.join替代字符串拼接,确保路径在任意操作系统下都有效:

def get_stations(request):
    # 用os.path.join安全拼接路径
    file_path = os.path.join(settings.STATICFILES_DIRS[0], 'stations.json')
    with open(file_path, 'r') as f:
        data = json.load(f)
    return JsonResponse(data, safe=False)

2. 添加safe=False参数

如果stations.json的内容是数组(列表)结构,必须添加该参数——JsonResponse默认仅支持返回字典类型,返回列表时需显式关闭安全校验。

3. 额外检查项

  • 确认stations.json确实存在于register/static/目录下,且文件为有效的JSON格式(无语法错误);
  • 检查文件权限,确保Django进程拥有读取该文件的权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 20:57:29