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!