0

I'd like to create an http response with an mp4 video as the content
Following the advice I found here this is what I have so far:

    resp = Response()
    resp.status_code = 200
    with open("unit_tests/unit_test_data/testvid 2 - public_2.mp4", "rb") as vid:
        resp._content = vid.read(1024 * 1024)
    resp.headers = {"content-length": "13837851"}

This response is then to be used as follows :

    with open(fname, "wb") as file:
        for data in resp.iter_content(chunk_size=1024):
            size = file.write(data)

However in the second part, when trying to read the content of my response I get the following error:

    AttributeError: 'NoneType' object has no attribute 'read'  

Any help is welcome, thanks!

Frazic
  • 77
  • 9

1 Answers1

0

Here are multiple snippets for the logic that can help you. (not tested, so might need some corrections)

myFileNameToSend = "unit_tests/unit_test_data/testvid 2 - public_2.mp4"

Step 1: Encode the file you want to send as base64 string

import base64
myFileToSend = open(myFileNameToSend, 'rb')
myFileContent = myFileToSend.read()
myFileStringToSend = base64.b64encode(myFileContent).decode('ascii')

Step 2: Actually sending the string over as response

from fastapi import Request,FastAPI, File, UploadFile, Form
import requests
api = FastAPI()
@api.get("/test") #this is where your webserver is listening for post requests
def test():
    return {"filename": myFileNameToSend.split("/")[-1],"dataAsAscii":myFileStringToSend}

Step 3: Decoding base64 string back to bytes

import json
import base64
import requests
jsonReceived = initialRequest.json() #initialRequest is your request object to which you are expecting to get a response
myFileNameReceived = jsonReceived["filename"]
myFileStringReceived = jsonReceived["dataAsAscii"].encode('ascii')
myFileReceived = base64.b64decode(myFileStringReceived)
f = open(myFileNameReceived, 'wb')
f.write(myFileReceived)
f.close()
Joshua
  • 551
  • 4
  • 13