0

Let's say that we have a database with existing data, the data is updated from a bash script and there is no related model on Django for that. Which is the best way to create an endpoint on Django to be able to perform a GET request so to retrieve the data?

What I mean is, that if there was a model we could use something like:

class ModelList(generics.ListCreateAPIView):
    queryset = Model.objects.first()
    serializer_class = ModelSerializer

The workaround that I tried was to create an APIView and inside that APIView to do something like this:

class RetrieveData(APIView):

    def get(self, request):

        conn = None
        try:
            conn = psycopg2.connect(host=..., database=..., user=..., password=..., port=...)

            cur = conn.cursor()
            cur.execute(f'Select * from ....')
            fetched_data = cur.fetchone()
            cur.close()
            res_list = [x for x in fetched_data]
            json_res_data = {"id": res_list[0],
                             "date": res_list[1],
                             "data": res_list[2]}
            return Response({"data": json_res_data)
        except Exception as e:
            return Response({"error": 'Error'})
        finally:
            if conn is not None:
                conn.close()

Although I do not believe that this is a good solution, also is a bit slow ~ 2 sec per request. Apart from that, if for example, many Get requests are made at the same time isn't that gonna create a problem on the DB instance, e.g lock table etc?

So I was wondering which is a better / best solution for this kind of problems. Appreciate your time!

Ioan Kats
  • 523
  • 1
  • 7
  • 19
  • One reason it might be slow is that you are **connecting** to the database before each request, and taht takes some times. You could speed up the process by having and maintaining a pool of connections to that DB (rather than logging in and logging out after each request). – Jordan Kowal May 16 '21 at 10:11
  • Hello @JordanKowal, thanks for your time. Yeap it is pretty obvious that connecting every time is not good, I was wondering if there is a Django alternative for that. – Ioan Kats May 16 '21 at 14:01
  • Maybe check out [this topic](https://stackoverflow.com/questions/16596261/pulling-data-to-the-template-from-an-external-database-with-django). It talks about using Django ORM to READ (and never update) an external database – Jordan Kowal May 16 '21 at 14:06
  • Hello again, it proposes connecting on the db for every request, same with what I am currently doing, thanks anyways – Ioan Kats May 16 '21 at 15:42

0 Answers0