I am making a REST API using FastAPI and Python. For example here is an api that takes an uploaded file, and returns an array that with the length of each line.
router = APIRouter()
@router.post('/api/upload1')
async def post_a_file(file: UploadFile):
result = []
f = io.TextIOWrapper(file.file, encoding='utf-8')
while True:
s = f.readline()
if not s: break
result.append(len(s))
return result
However this fails with error...
f = io.TextIOWrapper(file.file, encoding='utf-8')
AttributeError: 'SpooledTemporaryFile' object has no attribute 'readable'
If i change to
f = file.file
while True:
s = f.readline().decode('utf-8')
then it works, but that is stupid, because reading a "line" of bytes doesn't make sense.
What is the right way to do this?
EDIT: As I learned (see comments) it is not wrong to read a "line" of bytes, because the line break characters (either 0x0A or 0x0D0A) are the same in all character sets.