This is an educational question.
I've read multiple times that python's eval
has multiple security threats and that it should be avoided as much as possible. Then I opted for a containerized execution using docker sdk.
Here's a simplified, dummy snippet to illustrate my approach
import docker
# Define the generated code as a string
generated_code = """
result = int(n) ** int(p)
print(result)
"""
# Define the values for the variables n and p
n = 2
p = 3
# Create a Docker client
client = docker.from_env()
# Define a Docker image to use as the execution environment
image_name = "python:latest"
# Create a container and run the generated code within it
container = client.containers.run(
image=image_name,
command=["python", "-c", generated_code],
# environment={"n": str(n), "p": str(p)}, # <-- this does not work :(
detach=False,
)
# Print the container's output
print(container.decode())
Since I have no control over the code, I would like to specify an environment
(meaning both libs and variables) the way I would with eval
when calling it like this: eval(code, environment)
. Is there a way to do this with docker sdk ?
EDIT: Is preparing an image with the required environment and uploading it to dockerhub the only solution to this ?