I have a Django web-service where I have to take python code from users and run it in the backend and use that code for some purpose. Presently I have taken code by user and I store it in a file. When needed to run, I use a file descriptor to open the file and take the code as string, store the string and use exec on the string. Running it one time is fine but running it more than one times gives this particular error
missing "=" after """," in connection info string
If I don't use the exec part, this error no longer occurs. Is this the best way to run the python file. Is importing the python file directly better than this?
The way I use the running code is I force the user to store the final output in a variable called output_plots. Then, I retrieve the output_plots variable in my Django server code and print the variable output_plots.
def function() :
with open(file) as fp:
data = fp.read()
exec data in locals() #output_plots is in the exec data
print output_plots
So, finally the 2 questions arising are :
a) Is this the best method to run the python file. Are there better ways to do it?
b) Sometimes inside data variable which has the python code, some import statements don't work in the python code. How to solve that? I know this error is related to exec data in locals() but I don't know how to solve the problem?