0

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?

2 Answers2

0

According to that other subject (How to execute a file within the python interpreter?), it might be a good idea for you to try using the function execfile(filename, variables).

So you just need to import the file from your users as you do, and then execute the file itself with execfile instead of storing it in another variable before use. Don't know if it will solve your problem, but I'm sure it will not hurt (quite the opposite) to execute the file directly instead of storing it in a temp variable.

Since you're using Python 2.7 ans not python 3.X it should work for you.

Community
  • 1
  • 1
Kaël
  • 163
  • 1
  • 13
0

you can use execfile(filename, variables) to execute it , but be careful , users can execute dangerous code , they can execute a rm -fr * command and delete all your files for example,

what you need is a pysandbox , so all executed code will not modify the environment !

Vasseurth
  • 6,354
  • 12
  • 53
  • 81