Palash Shah
Palash Shah

Reputation: 51

django in memory uploaded file has no attribute starts with

i'm coding up a rest api where i'm passing a python file. i'd like to take the python file, import a function from it and use it.

I can read in the file using this: custom_file = request.FILES['custom']. If I print out the type of this, I get <class 'django.core.files.uploadedfile.InMemoryUploadedFile'>. This is a python file called test.py. ` I'd like to import a function from that file but I can't seem to do it properly. Here's what i'm trying:

        mod = import_module(custom_file)
        new_func = getattr(custom_file, file_name)
        df = new_func(json_file)

I think there's a confusion between what i'm supposed to be passing to import_module, it requires a string of the file, but i'm passing in the file as a request to my API. How would I go about doing this?

I've tried loading up the function without the request using the commands above (if i just have it in the same directory without the rest api) and it works. So I just need to figure out how to access the right information from the request call.

Upvotes: 0

Views: 247

Answers (1)

Mart&#237;
Mart&#237;

Reputation: 2851

Execute arbitrary code is usually a terrible idea as it would have full permissions.

That said, you first have to save the file into disk. I would create a temporary folder there using tempfile.mkdtemp (link to docs) and saving it there. Then import it as a module (see this question for more info on how you do that).

Upvotes: 1

Related Questions