I might also recommend optimizing by skipping all these checks and instead using send_file right away and capturing the errors for missing files.  this really needs to be quick.

btw, have you tried this in the browser?  Is it painfully slow?