无法访问Django API端点,请求返回404错误排查求助
问题描述
配置Django项目的API端点后,访问http://127.0.0.1:8000/api/line-chart-data/、http://127.0.0.1:8000/api/candlestick-data/等多个端点均返回404错误,无法获取预期的JSON格式数据。以下是项目相关配置代码:
urls.py(项目根目录)
""" URL configuration for mysite project. The `urlpatterns` list routes URLs to For more information please see: https://docs.djangoproject.com/en/5.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ # mysite/urls.py from django.contrib import admin from django.urls import path from .views import line_chart_data, candlestick_data, bar_chart_data, pie_chart_data from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('charts.urls')), path('api/candlestick-data/', candlestick_data), path('api/line-chart-data/', line_chart_data), path('api/bar-chart-data/', bar_chart_data), path('api/pie-chart-data/', pie_chart_data), ]
views.py(项目根目录)
# mysite/views.py from rest_framework.response import Response from rest_framework.decorators import api_view @api_view(['GET']) def candlestick_data(request): data = { "data": [ {"x": "2023-01-01", "open": 30, "high": 40, "low": 25, "close": 35}, {"x": "2023-01-02", "open": 35, "high": 45, "low": 30, "close": 40}, ] } return Response(data) @api_view(['GET']) def line_chart_data(request): data = { "labels": ["Jan", "Feb", "Mar", "Apr"], "data": [10, 20, 30, 40] } return Response(data) @api_view(['GET']) def bar_chart_data(request): data = { "labels": ["Product A", "Product B", "Product C"], "data": [100, 150, 200] } return Response(data) @api_view(['GET']) def pie_chart_data(request): data = { "labels": ["Red", "Blue", "Yellow"], "data": [300, 50, 100] } return Response(data)
settings.py(项目根目录)
""" Django settings for mysite project. Generated by 'django-admin startproject' using Django 5.1.1. For more information on this file, see https://docs.djangoproject.com/en/5.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True CORS_ALLOW_ALL_ORIGINS = True ALLOWED_HOSTS = ['localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware' ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/5.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', # Next.js frontend in development ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] } # Password validation # https://docs.djangoproject.com/en/5.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/5.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/5.1/howto/static-files/ STATIC_URL = 'static/' # Default primary key field type # https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.contrib.auth.models.BigAutoField'
解决方案
1. 调整URL匹配顺序
Django的URL路由从上到下匹配,一旦找到匹配规则就会停止后续匹配。你的根urls.py中,path('', include('charts.urls'))放在API路由前面,如果charts/urls.py存在空路径或通配符路由(比如path('', ...)),会优先拦截所有请求,导致API路由无法触发。
修改根urls.py,将API路由移到include('charts.urls')之前:
urlpatterns = [ path('admin/', admin.site.urls), # 先匹配API路由 path('api/candlestick-data/', candlestick_data), path('api/line-chart-data/', line_chart_data), path('api/bar-chart-data/', bar_chart_data), path('api/pie-chart-data/', pie_chart_data), # 最后匹配charts应用的路由 path('', include('charts.urls')), ]
2. 检查charts/urls.py的路由规则
若调整顺序后仍返回404,打开charts/urls.py检查是否有冲突规则:
- 是否定义了
path('', ...)这类空路径路由 - 是否使用正则表达式匹配所有路径(如
re_path(r'^.*$', ...))
如有此类规则,需缩小其匹配范围,避免覆盖API路由。
3. 验证视图函数导入
确认项目根目录的views.py存在,且line_chart_data、candlestick_data等函数名称拼写正确、定义完整。
4. 重启开发服务器
修改URL配置后,重启Django开发服务器确保配置生效。
内容的提问来源于stack exchange,提问作者Rahim Askerov
相关产品推荐
相关产品推荐

