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.

Wow, the very thought of doing that makes me shudder.

If it’s something you really want to do, I can see a couple different options for this:

  1. Pickle the code on the sending side and unpickle it on the receiving side
  2. Write the received file to the local file system in an appropriate location and import it from there.
  3. Read the file data as a string, and compile / eval it to whatever you need.

I tried this but it didn’t seem to work, could you advise me on what to do.

So first, I read in the file from the curl command with: custom_file = request.FILES['custom'].

Then I try to save it to a temporary folder with: path = default_storage.save(tempfile.mkdtemp(), custom_file).

Then I go about importing the modules and files with this:

        sys.path.append(path)
        mod = import_module(path)

when doing this, I get a The joined path (/var/folders/tk/jb99sz1j0qgdjc12c7yxln500000gn/T/tmpcdstz219) is located outside of the base path component

I have no specific idea or knowledge about this, everything I say about this entire topic is all conjecture. Regardless, the error message seems pretty straight forward. It looks like it’s expecting the path being added to be under the base path of the app. You might need to configure a specific FileSystemStorage object pointing to somewhere within your app.
(I do feel compelled to add that this whole idea seems like a massive security issue on so many levels. I really hope that the rest of your environment is bulletproof, because an exploit here completely opens up your machine and creates a conduit for everything else local to it.)