File Download Handling with Generators and Permission Verification in Falcon
from wsgiref import simple_server
import falcon
import os
class FileResource:
def on_get(self, req, resp):
target_file = '/path/to/target_file.txt'
if not os.access(target_file, os.R_OK):
resp.status = falcon.HTTP_403
resp.media = {'error': 'File access denied'}
return
resp.stream = self.file_stream(target_file)
resp.downloadable_as = os.path.basename(target_file)
resp.status = falcon.HTTP_200
def file_stream(self, file_path, buffer_size=8192):
with open(file_path, 'rb') as f:
while True:
segment = f.read(buffer_size)
if not segment:
break
yield segment
app = falcon.App()
file_handler = FileResource()
app.add_route('/download', file_handler)
if __name__ == '__main__':
httpd = simple_server.make_server('0.0.0.0', 8000, app)
httpd.serve_forever()
Verifying File Permissions
Use os.access() to check permissions before file operations:
import os
# Check existence and permissions for /data/sample.txt
exists = os.access("/data/sample.txt", os.F_OK)
readable = os.access("/data/sample.txt", os.R_OK)
writable = os.access("/data/sample.txt", os.W_OK)
executable = os.access("/data/sample.txt", os.X_OK)
print(f"File exists: {exists}")
print(f"Read allowed: {readable}")
print(f"Write allowed: {writable}")
print(f"Execute allowed: {executable}")
Typical output when file has read/write permisssions but not execute:
File exists: True
Read allowed: True
Write allowed: True
Execute allowed: False