0

I have a model that contains a FileField. I use it to upload .py files.

models.py

class FileModel(models.Model):
    file = models.FileField(null = True, blank = True, upload_to = 'files')
    file_name = models.CharField(max_length=200)

I want to retrieve the uploaded files and execute the code within a view.

views.py

def get_return_from_file(request):
    post = FileModel.objects.get(file_name__iexact='example_name')
    a = post.file.read()
    print (a)

Example uploaded python file 'example_name'

def main():
    return 'hello world'

if __name__ == "__main__":
    main()

However this returns

b'def main():\n return 'hello world'\n if name == "main":\n main()'

instead of

'hello world'

How can I execute the code in the FileField and access it's returned values instead of just reading it as a string?

Thanks!

William
  • 171
  • 1
  • 12

2 Answers2

0

example file:

def main():
    return 'hello world'

if __name__ == "__main__":
    print(main())

views.py

def get_return_from_file(request):
    post = FileModel.objects.get(file_name__iexact='example_name')
    a = post.file.read()
    exec(a)
nishant
  • 2,526
  • 1
  • 13
  • 19
  • This doesn't return 'hello world', if I instead write in views.py print (exec(a)) it returns None which suggests django isn't reading the uploaded file with this method. – William Feb 17 '19 at 19:39
  • thats because you are not returning any thing from your example .py file – nishant Feb 18 '19 at 03:08
-1

Use eval() for single line expression.

eval() only returns expression result.

Use exec() for statements, any valid python code block.

Docs: https://docs.python.org/3/library/functions.html

Debendra
  • 1,132
  • 11
  • 22