1

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?

Stevie
  • 326
  • 3
  • 16
  • It depends if you want to retrieve the content of the json file (as if it was a json output produced by DRF) or if you want to serve the json files as you would with any kind of file. See this answer for effective file download with Django: https://stackoverflow.com/questions/1156246/having-django-serve-downloadable-files – matthieu.cham Mar 06 '19 at 11:21

2 Answers2

2

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)
Reza Torkaman Ahmadi
  • 2,958
  • 2
  • 20
  • 43
0
class TestAPI(APIView):
    def get(self, request):
        with open("filepath", "r") as f:
            airlines_json = json.load(f)
        return Response(airlines_json)
BiswajitPaloi
  • 586
  • 4
  • 16