from __future__ import absolute_import

import os
import shutil
import tempfile
import contextlib

import boto3
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
from celery import shared_task
from django.conf import settings


@shared_task
def submit_comment(comment):
    with TemporaryDirectory() as path:
        fields = [
            ("comment_on", comment["document_id"]),
            ("general_comment", comment["comment"]),
        ]
        try:
            files = [
                ('uploadedFile', (file_['name'], open(
                    fetch_file(path, file_['key'], file_['name']), "rb")))
                for file_ in comment.get('files', [])
            ]
            fields.extend(files)
            data = MultipartEncoder(fields)
            response = requests.post(
                settings.REGS_API_URL,
                data=data,
                headers={
                    "Content-Type": data.content_type,
                    "X-Api-Key": settings.REGS_API_KEY
                }
            )
        finally:
            for file_ in files:
                file_[1][1].close()

        print(response.text)


@contextlib.contextmanager
def TemporaryDirectory(*args, **kwargs):
    try:
        path = tempfile.mkdtemp(*args, **kwargs)
        yield path
    finally:
        shutil.rmtree(path)


def fetch_file(path, key, name):
    session = boto3.Session(
        aws_access_key_id=settings.ATTACHMENT_ACCESS_KEY_ID,
        aws_secret_access_key=settings.ATTACHMENT_SECRET_ACCESS_KEY,
    )
    s3 = session.client('s3')
    dest = os.path.join(path, name)
    s3.download_file(settings.ATTACHMENT_BUCKET, key, dest)
    return dest

@@ -307,36 +307,45 @@
 ith 
-TemporaryDirectory(
+AttachmentSet(comment
 ) as 
-p
 at
-h
+tachments
 :%0A  
@@ -488,270 +488,35 @@
     
-try:%0A            files = %5B%0A                ('uploadedFile', (file_%5B'name'%5D, open(%0A                    fetch_file(path, file_%5B'key'%5D, file_%5B'name'%5D), %22rb%22)))%0A                for file_ in comment.get('files', %5B%5D)%0A            %5D%0A            fields.extend(files)%0A    
+fields.extend(attachments)%0A
     
@@ -559,20 +559,16 @@
         
-    
 response
@@ -597,20 +597,16 @@
         
-    
 settings
@@ -628,28 +628,24 @@
             
-   
- 
 data=data,%0A 
@@ -655,20 +655,16 @@
         
-    
 headers=
@@ -665,20 +665,16 @@
 aders=%7B%0A
-    
         
@@ -732,20 +732,16 @@
         
- 
-   
 %22X-Api-K
@@ -783,26 +783,28 @@
     
-    
 %7D%0A    
+    )%0A
         
 )%0A  
@@ -803,39 +803,158 @@
     
-)%0A        finally
+print(response.text)%0A%0A%0A@contextlib.contextmanager%0Adef AttachmentSet(comment):%0A    '''%0A    Assembles a collection of tuples of the form
 :%0A    
+%5B%0A
         
 for 
@@ -953,27 +953,107 @@
     
-for file_ in files:
+('uploadedFile', ('fileName1', file-object1),%0A        ('uploadedFile', ('fileName2', file-object2),
 %0A   
@@ -1061,193 +1061,646 @@
     
+...%0A
     
+%5D%0A
     f
-ile_%5B1%5D%5B1%5D.close()%0A%0A        print(response.text)%0A%0A%0A@contextlib.contextmanager%0Adef TemporaryDirectory(*args, **kwargs):%0A    try:%0A        path = tempfile.mkdtemp(*args, **kwargs)
+or POSTing as a multipart/form-data upload.%0A    comment%5B'files'%5D is a collection of dicts where for each dict:%0A        - dict%5B'key'%5D specifies the file to be attached from S3%0A        - dict%5B'name'%5D specifies the name under which the file is to be%0A          attached.%0A    On context exit, the file objects are closed and the locally%0A    downloaded files are deleted.%0A    '''%0A    try:%0A        path = tempfile.mkdtemp()%0A        attachments = %5B%0A            ('uploadedFile', (file_%5B'name'%5D,%0A                              fetch_file(path, file_%5B'key'%5D, file_%5B'name'%5D)))%0A            for file_ in comment.get('files', %5B%5D)%0A        %5D
 %0A   
@@ -1710,20 +1710,27 @@
   yield 
-p
 at
-h
+tachments
 %0A    fin
@@ -1747,62 +1747,304 @@
     
-shutil.rmtree(path)%0A%0A%0Adef fetch_file(path, key, name):
+for file_ in attachments:%0A            attachments%5B1%5D%5B1%5D.close()%0A        shutil.rmtree(path)%0A%0A%0Adef fetch_file(path, key, name):%0A    '''%0A    Returns a file object corresponding to a local file stored at %60%60path+name%60%60%0A    whose content is downloaded from S3 where it is stored under %60%60key%60%60%0A%0A    '''
 %0A   
@@ -2342,13 +2342,25 @@
  return 
-dest
+open(dest, %22rb%22)
 %0A

Make entire attachment assembly context managed.