'Trying to Upload database file using python requests and sending to django API

Hi I have a database file. I want to send this database file via python requests post method to my django server and store this database file somewhere in my server.

I have following code to send the database file:

database = {'uploaded_file': open('<my_local_path>/Old_DB.sqlite3', 'rb')}
response = requests.post('http:192.168.20.4/api/app/receive-database', data=database)
print(response.status_code)

On my API:

class DatabaseReceive(views.APIView):
    permission_classes = (permissions.AllowAny,)

    def post(self, request):
        database = request.data
        data = database.get('uploaded_file')
        try:
            newDB = open('<path_to_store_the_database>/New_DB.sqlite3', 'wb')
            newDB.write(data)
            result = "Sucess"
        except Exception as e:
            result = e
        return Response(status=status.HTTP_200_OK, data=result)

So, basically I am sending the database as a binary file to my api. On my api, I am creating another binary file and trying to write the binary contents from database to my to this new binary file making it a new database. Here I can see that 'data' is a binary contents, but I'm not being able to write this 'data' to my newDB binary file.



Solution 1:[1]

Update

I figured the issue. I had to make the following changes to make it work:

For sending the database file, we need to use files attribute

response = requests.post('http:192.168.20.4/api/app/receive-database', files=database)

On the API,

def post(self, request):
    database = request.data
    data = database.get('uploaded_file')
    try:
        newDB = open('<path_to_store_the_database>/New_DB.sqlite3', 'wb')
        newDB.write(data.read())
        newDB.close()
        result = "Sucess"
    except Exception as e:
        result = str(e)
    return Response(status=status.HTTP_200_OK, data=result)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Praveg S