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

62 lines
1.5 KiB
Python
Raw Normal View History

2022-02-14 21:43:12 +00:00
global handleBinary
def handleBinary(env):
filePath = env["fPath"]
fileExt = env["fileExt"]
connection = env["self"].connection
length = 0
lastModified = None
2022-02-14 21:43:12 +00:00
with fileLock:
length = os.path.getsize(filePath)
try:
lastModified = os.path.getmtime(filePath)
except:
pass
2022-02-14 21:43:12 +00:00
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]
status = "200 OK"
headers = {
"Content-Length": str(length),
"Content-Type": mimetype,
"Accept-Ranges": "bytes",
"Date": env["requestTimeFormatted"]
}
if lastModified != None:
headers["Last-Modified"] = email.utils.formatdate(lastModified).replace("-0000","GMT")
if rangeDefined:
status = "206 Partial Content"
headers["Content-Range"] = "bytes " +str(rangeStart)+ "-" +str(rangeEnd - 1)+ "/" +str(length)
simpleResponse(connection,status,headers)
2022-02-14 21:43:12 +00:00
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