我有一个 django 后端设置。其中我有几个文件夹,base(保存我的模型的应用程序),一个名为“api”的文件夹,其中有一个
views.py
和 urls.py
用于我的 api,以及一个名为 backend 的文件夹(djangos 基本文件夹,其中 settings.py
、wsgi.py
等)。
现在,我的views.py(在 api 文件夹中)中已经有一些已链接且正在运行的 API,我只是尝试创建一个新的 API。尽管我执行了相同的步骤,遵循相同的链接,但从我的前端访问时,此 API 不起作用,控制台显示:
Not Found: /api/getmodel/
\[25/Mar/2024 22:36:50\] "GET /api/getmodel/ HTTP/1.1" 404 3116"
当我转到
http://127.0.0.1:8000/api/getmodel/
时,我看到默认的 djangorestframework 视图,所以我知道该视图存在,并且该链接上实际上有一些东西。以下是相关文件:
urls.py
(在 api 文件夹中):
from django.urls import path
from . import views
from rest_framework_simplejwt.views import (
TokenRefreshView,
)
from .views import MyTokenObtainPairView
urlpatterns = [
path('registeruser/', views.register_user),
path('token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'),
path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path('createmodel/', views.create_model),
path('getmodel/', views.fetch_model),
]
views.py
(在 api 文件夹中):
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from django.contrib.auth.hashers import make_password
from base.models import User, HumanModel
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView
from django.http import JsonResponse
import subprocess
import os
#login tokenizer (working fine)
#login api here (working fine)
#example of working API
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def create_model(request):
data = request.data
username = request.user.username
print(username)
print(data)
#do a whole bunch of processing (left out for simplicity)
#api that is NOT working (saying not found)
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def fetch_model(request):
try:
# Attempt to fetch the HumanModel instance associated with the current user
human_model = HumanModel.objects.get(user=request.user)
# Check if a model_path exists
if human_model.model_path:
# Return the model_path if it exists
return Response({'model_path': human_model.model_path})
else:
# Return a message indicating the model_path is not available
return Response({'message': 'No model path exists for the current user.'})
except HumanModel.DoesNotExist:
# Return a response indicating no HumanModel instance exists for the current user
return Response({'message': 'No model information found for the current user.'}, status=404)
我已经让基本后端文件夹中的 urls.py 正常工作,并且它与我的其他 api 一起工作,所以我不知道问题是什么。这是供参考的文件:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path("admin/", admin.site.urls),
path("api/", include('api.urls'))
]
我不认为将我的 api 文件夹链接到后端文件夹中的
urls.py
是一个配置问题,因为其他 api(登录、注册、创建模型)都可以工作。再说一次,我可以转到 http://127.0.0.1:8000/api/getmodel/
并查看 djangorestframework 默认视图,但是当我的前端代码尝试使用 axios 转到该 url 时,它在 DJANGO 控制台中显示“未找到”。有什么想法吗?
请参阅上面的解释,即使视图在浏览器中可见,但它在控制台中找不到。我在
package.json
的 React 前端设置了正确的代理,我的其他 api 工作。这是我从前端获取数据的方式:
useEffect(() => {
const fetchModelPath = async () => {
if (!authTokens) return; // If there are no auth tokens, return early
try {
const response = await axios.get('/api/getmodel/', {
headers: {
Authorization: `Bearer ${authTokens.access}`,
},
});
if (response.data.model_path) {
setModelPath(response.data.model_path);
} else {
setModelPath("create");
}
} catch (error) {
console.error("There was an error fetching the model path", error);
setModelPath("create");
}
};
fetchModelPath();
}, [authTokens]);
您的前端可能在发出获取请求之前首先尝试HEADs请求。
使用curl、postman或其他api开发工具检查您的端点。 如果您的后端响应 200,请尝试将
HEAD
添加到 @api_view
装饰器。
@api_view(['HEAD', 'GET'])
@permission_classes([IsAuthenticated])
def fetch_model(request):
# rest of your code