fhttpy/modules/http/file-handlers/binary.py

64 lines
1.7 KiB
Python

global handleBinary
def handleBinary(env):
filePath = env["fPath"]
fileExt = env["fileExt"]
connection = env["self"].connection
length = 0
lastModified = 0
with fileLock:
length = os.path.getsize(filePath)
try:
lastModified = os.path.getmtime(filePath)
except:
pass
lastModified = email.utils.formatdate(lastModified).replace("-0000","GMT")
rangeDefined = False
rangeStart = 0
rangeEnd = None
if "range" in env["headerList"]:
rangeDefined = True
rangeStart,rangeEnd = getRange(env["headerList"]["range"])
rangeStart,rangeEnd = convertRanges(rangeStart,rangeEnd,length)
if rangeStart == None:
raise # tell the client the request is invalid
mimetype = "application/octet-stream"
if fileExt in mimetypesBinary:
mimetype = mimetypesBinary[fileExt]
if not rangeDefined:
simpleResponse(connection,"200 OK",{
"Content-Length": str(length),
"Content-Type": mimetype,
"Accept-Ranges": "bytes",
"Date": env["requestTimeFormatted"],
"Last-Modified": lastModified
})
else:
simpleResponse(connection,"206 Partial Content",{
"Content-Range": "bytes " +str(rangeStart)+ "-" +str(rangeEnd - 1)+ "/" +str(length),
"Content-Length": str(rangeEnd - rangeStart),
"Content-Type": mimetype,
"Accept-Ranges": "bytes",
"Date": env["requestTimeFormatted"],
"Last-Modified": lastModified
})
cByte = rangeStart
while cByte < rangeEnd:
bytes = b""
rSize = readBufferSize
if cByte + rSize > rangeEnd:
rSize = rangeEnd - cByte
with fileLock:
with open(filePath,"rb") as file:
file.seek(cByte)
bytes = file.read(rSize)
connection.sendall(bytes)
cByte += rSize
fileHandlers[".*"] = handleBinary
for t in mimetypesBinary:
fileHandlers[t] = handleBinary