Lau*_*ard 12 django nginx amazon-s3 gunicorn amazon-elb
考虑我们当前的架构:
+---------------+
| Clients |
| (API) |
+-------+-------+
?
?
+-------+-------+ +-----------------------+
| Load Balancer | | Nginx |
| (AWS - ELB) +<-->+ (Service Routing) |
+---------------+ +-----------------------+
?
?
+-----------------------+
| Nginx |
| (Backend layer) |
+-----------+-----------+
?
?
----------------- +-----------+-----------+
File Storage | Gunicorn |
(AWS - S3) <-->+ (Django) |
----------------- +-----------------------+
Run Code Online (Sandbox Code Playgroud)
当客户端,移动设备或Web尝试在我们的服务器上上传大文件(超过GB)时,通常会面临空闲的连接超时.从他们的客户端库,在iOS上,或从我们的负载均衡器.
当客户端实际上载文件时,不会发生超时,因为连接不是"空闲",正在传输字节.但我认为当文件被转移到Nginx后端层并且Django开始将文件上传到S3时,客户端和我们的服务器之间的连接将变为空闲,直到上传完成.
有没有办法防止这种情况发生,我应该在哪一层解决这个问题?
您可以创建上传处理程序以将文件直接上传到 s3。这样你就不会遇到连接超时的情况。
https://docs.djangoproject.com/en/1.10/ref/files/uploads/#writing-custom-upload-handlers
我做了一些测试,它在我的情况下运行得很好。
例如,您必须使用 boto 启动新的 multipart_upload 并逐步发送块。
不要忘记验证块大小。如果您的文件包含超过 1 个部分,则至少 5Mb。(S3限制)
我认为如果你真的想直接上传到 s3 并避免连接超时,这是 django-queued-storage 的最佳替代方案。
您可能还需要创建自己的文件字段以正确管理文件而不是再次发送。
以下示例使用 S3BotoStorage。
S3_MINIMUM_PART_SIZE = 5242880
class S3FileUploadHandler(FileUploadHandler):
chunk_size = setting('S3_FILE_UPLOAD_HANDLER_BUFFER_SIZE', S3_MINIMUM_PART_SIZE)
def __init__(self, request=None):
super(S3FileUploadHandler, self).__init__(request)
self.file = None
self.part_num = 1
self.last_chunk = None
self.multipart_upload = None
def new_file(self, field_name, file_name, content_type, content_length, charset=None, content_type_extra=None):
super(S3FileUploadHandler, self).new_file(field_name, file_name, content_type, content_length, charset, content_type_extra)
self.file_name = "{}_{}".format(uuid.uuid4(), file_name)
default_storage.bucket.new_key(self.file_name)
self.multipart_upload = default_storage.bucket.initiate_multipart_upload(self.file_name)
def receive_data_chunk(self, raw_data, start):
buffer_size = sys.getsizeof(raw_data)
if self.last_chunk:
file_part = self.last_chunk
if buffer_size < S3_MINIMUM_PART_SIZE:
file_part += raw_data
self.last_chunk = None
else:
self.last_chunk = raw_data
self.upload_part(part=file_part)
else:
self.last_chunk = raw_data
def upload_part(self, part):
self.multipart_upload.upload_part_from_file(
fp=StringIO(part),
part_num=self.part_num,
size=sys.getsizeof(part)
)
self.part_num += 1
def file_complete(self, file_size):
if self.last_chunk:
self.upload_part(part=self.last_chunk)
self.multipart_upload.complete_upload()
self.file = default_storage.open(self.file_name)
self.file.original_filename = self.original_filename
return self.file
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1097 次 |
| 最近记录: |