# Buggy code
def put(self, name):
    """add new datasource"""
    data = {}

    def on_field(field):
        print(f"\n\n{field}\n\n")
        name = field.field_name.decode()
        value = field.value.decode()
        data[name] = value

    def on_file(file):
        data["file"] = file.file_name.decode()

    temp_dir_path = tempfile.mkdtemp(prefix="datasource_file_")

    if request.headers["Content-Type"].startswith("multipart/form-data"):
        parser = multipart.create_form_parser(
            headers=request.headers,
            on_field=on_field,
            on_file=on_file,
            config={
                "UPLOAD_DIR": temp_dir_path.encode(),  # bytes required
                "UPLOAD_KEEP_FILENAME": True,
                "UPLOAD_KEEP_EXTENSIONS": True,
                "MAX_MEMORY_FILE_SIZE": 0,
            },
        )

        while True:
            chunk = request.stream.read(8192)
            if not chunk:
                break
            parser.write(chunk)
        parser.finalize()
        parser.close()
    else:
        data = request.json

    if "query" in data:
        query = request.json["query"]
        source_type = request.json["integration_id"]
        ca.default_store.save_datasource(name, source_type, query)
        os.rmdir(temp_dir_path)
        return ca.default_store.get_datasource(name)

    ds_name = data["name"] if "name" in data else name
    source = data["source"] if "source" in data else name
    source_type = data["source_type"]

    if source_type == "file":
        file_path = os.path.join(temp_dir_path, data["file"])
    else:
        file_path = None

    ca.default_store.save_datasource(ds_name, source_type, source, file_path)
    os.rmdir(temp_dir_path)

    return ca.default_store.get_datasource(ds_name)


# Traceback (PermissionError)
Exception on /datasources/Somedata [PUT] Traceback (most recent call last): File "C:\Users\jp299\AppData\Roaming\mindsdb_gui\mindsdb_server\env\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request rv = self.dispatch_request() File "C:\Users\jp299\AppData\Roaming\mindsdb_gui\mindsdb_server\env\lib\site-packages\flask\app.py", line 1936, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "C:\Users\jp299\AppData\Roaming\mindsdb_gui\mindsdb_server\env\lib\site-packages\flask_restx\api.py", line 375, in wrapper resp = resource(*args, **kwargs) File "C:\Users\jp299\AppData\Roaming\mindsdb_gui\mindsdb_server\env\lib\site-packages\flask\views.py", line 89, in view return self.dispatch_request(*args, **kwargs) File "C:\Users\jp299\AppData\Roaming\mindsdb_gui\mindsdb_server\env\lib\site-packages\flask_restx\resource.py", line 44, in dispatch_request resp = meth(*args, **kwargs) File "C:\Users\jp299\AppData\Roaming\mindsdb_gui\mindsdb_server\env\lib\site-packages\flask_restx\marshalling.py", line 248, in wrapper resp = f(*args, **kwargs) File "C:\Users\jp299\AppData\Roaming\mindsdb_gui\mindsdb_server\env\lib\site-packages\mindsdb\api\http\namespaces\datasource.py", line 114, in put ca.default_store.save_datasource(ds_name, source_type, source, file_path) File "C:\Users\jp299\AppData\Roaming\mindsdb_gui\mindsdb_server\env\lib\site-packages\mindsdb\interfaces\datastore\datastore.py", line 81, in save_datasource os.replace(file_path, source) PermissionError: [WinError 32] El proceso no tiene acceso al archivo porque est� siendo utilizado por otro proceso: 'C:\\Users\\jp299\\AppData\\Local\\Temp\\datasource_file_pzpfjtzc\\Somedata.xlsx' -> 'C:\\Users\\jp299\\AppData\\Roaming\\mindsdb_gui\\mindsdb_server\\env\\lib\\site-packages/var/datastore\\Somedata\datasource\\Somedata.xlsx'

# Fixed code
def put(self, name):
    """add new datasource"""
    data = {}

    def on_field(field):
        print(f"\n\n{field}\n\n")
        name = field.field_name.decode()
        value = field.value.decode()
        data[name] = value

    file_object = None

    def on_file(file):
        nonlocal file_object
        data["file"] = file.file_name.decode()
        file_object = file.file_object

    temp_dir_path = tempfile.mkdtemp(prefix="datasource_file_")

    if request.headers["Content-Type"].startswith("multipart/form-data"):
        parser = multipart.create_form_parser(
            headers=request.headers,
            on_field=on_field,
            on_file=on_file,
            config={
                "UPLOAD_DIR": temp_dir_path.encode(),  # bytes required
                "UPLOAD_KEEP_FILENAME": True,
                "UPLOAD_KEEP_EXTENSIONS": True,
                "MAX_MEMORY_FILE_SIZE": 0,
            },
        )

        while True:
            chunk = request.stream.read(8192)
            if not chunk:
                break
            parser.write(chunk)
        parser.finalize()
        parser.close()

        if file_object is not None and not file_object.closed:
            file_object.close()
    else:
        data = request.json

    if "query" in data:
        query = request.json["query"]
        source_type = request.json["integration_id"]
        ca.default_store.save_datasource(name, source_type, query)
        os.rmdir(temp_dir_path)
        return ca.default_store.get_datasource(name)

    ds_name = data["name"] if "name" in data else name
    source = data["source"] if "source" in data else name
    source_type = data["source_type"]

    if source_type == "file":
        file_path = os.path.join(temp_dir_path, data["file"])
    else:
        file_path = None

    ca.default_store.save_datasource(ds_name, source_type, source, file_path)
    os.rmdir(temp_dir_path)

    return ca.default_store.get_datasource(ds_name)