Run python File With get request flask API
To be honest this code looks pretty dangerous. exec is dangerous in its own right, and using it in conjunction with user-provided input makes an explosive combination.
One flaw is the path traversal vulnerability. For example, providing a file name like &quot;../root/something/script.py&quot; I should be able to invoke files outside your directory. The file has to exist to be executed, but a hacker might find some file lying on your system, that can be exploited in a way you did not foresee.
Your script also does not verify that the resulting path really exists (for this, simply use os.path.exists). Thus, validation of user input is lacking.
And probably this code can be exploited in ways I have not thought about.
But since you are reading files from a specific directory, you could simply run a dir of that location, using for example the os.scandir function, and then you can generate a whitelist of files that are allowed to run. Anything else should be disallowed outright.
Personally I would ditch this approach. It would be better to build a library of functions, and invoke only functions that are known and understood, rather than arbitrary files. The rule of thumb is that user input can never be trusted, so it has to be validated thoroughly.