How to install a library and execute the code with a POST request? [Django]
I am trying to execute the python code which I am taking as user input and returning the output of the code but I want to use a library to find the time complexity of the program but it obviously gives module not found error when I try to execute the code with library in it.
Here is my frontend which I created using react.

Python code is running perfectly when I do not introduce any libraries. What I am doing is I am sending the code to django through REST Api and executing the code writing the output in a file and returning the output as shown below -
My viewsets.py file -
from rest_framework.viewsets import ModelViewSet
from .models import Code
from .serializers import CodeSerializer
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK, HTTP_204_NO_CONTENT
import sys
class CodeViewSet(ModelViewSet):
queryset = Code.objects.all()
serializer_class = CodeSerializer
lookup_field = "id"
@action(detail=True, methods=["HEAD", "GET", "POST"], url_path="runcode")
def runcode(self, request, id=None):
if request.method in ("GET", "HEAD"):
return Response(status=HTTP_204_NO_CONTENT)
else:
code_data = self.get_object()
try:
orig_stdout = sys.stdout
sys.stdout = open('file.txt', 'w')
exec(code_data.code)
sys.stdout.close()
sys.stdout = orig_stdout
output = open('file.txt', 'r').read()
except Exception as e:
sys.stdout.close()
sys.stdout = orig_stdout
output = e
print(output)
return Response(output, status=HTTP_200_OK)
My models.py for reference -
from django.db import models
from django_extensions.db.fields import AutoSlugField
class Code(models.Model):
code = models.TextField()
I am executing the code in my viewsets.py where I routed the request to .../id/runcode url. I want to run a script or something like that on the POST request so that the code execution can install the libraries on the POST request so that ModuleNotFound error wont occur when using external libraries.
Example -
I am taking code input as -
def single_loop(n):
for i in range(n):
print(n+1)
and then I want to execute the following code for the above input -
import big_o
def single_loop(n):
def single_loop(n):
for i in range(n):
print(n+1)
print(big_o.big_o(single_loop, big_o.datagen.n_, n_repeats=20, min_n=2, max_n=100)[0])
I am getting the error big-o Module not found so I want to run a script or something to install the library so that execution happens perfectly.
Thank you in advance.