django - 如何在 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 类中,我想知道如何访问检索请求的文件并返回包含数据的响应对象?
解决方案
你应该这样做:
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)
推荐阅读
- pandas - 在 pandas 中获取等于给定行的值的列名
- node.js - 使用纪元时间戳作为客户端输入的 Postgres 数据查询?
- alpha - 以透明背景录制
- python - 使用 Runge-Kutta 算法 python 求解罗斯勒振荡器
- c# - 从查找表中批量读取的有效方法
- javascript - 如何通过定义特定的代码属性映射此对象数组以获取完整对象?
- mysql - 两个单独的更新涉及一个 SQL 查询中的不同列
- spring-boot - spring security自定义表达式中访问http请求
- hypothesis-test - 有没有办法将一组曲线分为两组或三组?
- javascript - 添加源后如何选择与原始图像大小相同的图像源?