用Python编写的文件响应器示例
发布时间:2023-12-11 01:04:48
下面是使用Python编写的文件响应器示例:
import os
import mimetypes
class FileResponder:
def __init__(self, root_dir):
self.root_dir = root_dir
def get_content_type(self, file_path):
mime_type, _ = mimetypes.guess_type(file_path)
if not mime_type:
mime_type = 'application/octet-stream'
return mime_type
def get_file_path(self, url_path):
normalized_path = os.path.normpath(url_path).lstrip('/')
file_path = os.path.join(self.root_dir, normalized_path)
if not os.path.exists(file_path):
raise FileNotFoundError('File not found')
if not os.path.isfile(file_path):
raise IsADirectoryError('Path is a directory')
return file_path
def get_response(self, url_path):
try:
file_path = self.get_file_path(url_path)
content_type = self.get_content_type(file_path)
with open(file_path, 'rb') as file:
data = file.read()
return 200, {'Content-Type': content_type}, data
except FileNotFoundError:
return 404, {'Content-Type': 'text/plain'}, b'File not found'
except IsADirectoryError:
return 403, {'Content-Type': 'text/plain'}, b'Directory listing not allowed'
# 使用示例
responder = FileResponder('/path/to/root/directory')
# 获取文件响应
status, headers, data = responder.get_response('/path/to/file.txt')
if status == 200:
print('Content-Type:', headers['Content-Type'])
print('Data:', data)
# 获取文件不存在的响应
status, headers, data = responder.get_response('/path/to/nonexistent_file.txt')
if status == 404:
print('Content-Type:', headers['Content-Type'])
print('Data:', data)
# 获取路径为目录的响应
status, headers, data = responder.get_response('/path/to/directory')
if status == 403:
print('Content-Type:', headers['Content-Type'])
print('Data:', data)
以上示例中,FileResponder 类接受一个根目录参数 root_dir,并提供了 get_content_type、get_file_path 和 get_response 方法。
- get_content_type 方法使用 mimetypes 模块来获取文件的 MIME 类型,如果无法确定 MIME 类型,则默认为 application/octet-stream。
- get_file_path 方法将 URL 路径转换为文件路径,并对路径的合法性进行检查。如果路径指向的文件不存在,则抛出 FileNotFoundError。如果路径指向的是一个目录,而不是文件,则抛出 IsADirectoryError。
- get_response 方法根据 URL 路径获取文件响应。首先调用 get_file_path 方法获取文件路径,然后使用 get_content_type 方法获取文件的 MIME 类型。最后,使用 open 函数读取文件内容,返回状态码、头部和数据。
在使用示例中,首先创建一个 FileResponder 实例,并传入根目录路径。然后可以调用 get_response 方法获取文件响应。根据状态码可以判断文件是否成功获取,如果成功可以读取返回的数据。
需要注意,示例中的路径为示意用途,实际使用时应根据实际情况进行修改。另外,示例中使用了 Python 3 的异常处理机制来处理文件和路径错误,你可以根据需求进行进一步的错误处理。
