首页 > 解决方案 > 如何在 Django Rest Framework 中检索外部 JSON 文件以与 React 一起使用?

问题描述

在我运行 Nginx 和 Gunicorn 的 EC2 实例上,我的目录中还有几个 json 文件。我最终希望 DRF 能够使用位于此目录中的指定 json 文件返回一个 Response 对象。

这是我认为我应该做的事情:当用户点击某物时,onClick 方法将调用 fetch() 并且我将传递“api/jsonfiles”以及我想要的文件的编号。urls.py 将有路径('api/jsonfiles/',views.JsonFileGetter)。在views.py 中的JsonFileGetter 类中,我想知道如何访问检索请求的文件并返回包含数据的响应对象?

标签: djangoreactjsnginxdjango-rest-framework

解决方案


你应该这样做:

1-首先,如您所说,创建 onClick 以 fetch() 例如像 DRF Apiapi/jsonfiles

2- 在 django 端创建一个 urls.py 并为其分配一个视图类。

3-在你的课堂上应该是这样的

# urls.py
path('jsonfile/<filename>/', JSONFileView.as_view(), name='file_retrieve'),

# Views.py
class JSONFileView(APIView):
    def get(self, request, filename):
        root_path = "Put root folder of files" 
        file_path = os.path.join(root_path, filename)
        with open(file_path, 'r') as jsonfile:
            json_data = json.loads(jsonfile)
        return Response(json_data)

推荐阅读