Issue
On my EC2 instance, which is running Nginx and Gunicorn, I also have several json files in a directory. I ultimately want DRF to be able to return a Response object with the specified json file located in this directory.
Here is what I think I should do: When a user clicks something, the onClick method will call fetch() and I will pass, say, 'api/jsonfiles' as well as the number of the file I want. urls.py will have path('api/jsonfiles/', views.JsonFileGetter). In the class JsonFileGetter within views.py, I am wondering how I can access retrieve the requested file and return a Response object containing the data?
Solution
You should do it as follow:
1- First as you said create onClick to fetch() for example an DRF Api like api/jsonfiles
2- On the django side create a urls.py and assign a views class to it.
3- and in your class it should be for example like this
# 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)
Answered By - Reza Torkaman Ahmadi
Answer Checked By - - Willingham (ReactFix Volunteer)