2014-11-04 2 views
1

Bottle을 사용하여 업로드 API를 만듭니다. 아래 스크립트는 파일을 디렉토리에 업로드 할 수 있지만 해결해야 할 두 가지 문제가 있습니다. 하나는 전체 파일을 메모리에로드하지 않는 방법이고 다른 하나는 업로드 파일의 최대 크기를 설정하는 방법입니다.업로드하는 동안 전체 파일을 메모리에로드하지 않는 방법

업로드가 완료 될 때까지 파일을 계속 읽고 파일을 읽어 올 수 있습니까? upload.save(file_path, overwrite=False, chunk_size=1024) 함수는 전체 파일을 메모리로로드하는 것 같습니다. 튜토리얼에서 그들은 .read()is dangerous을 사용했다.

from bottle import Bottle, request, run, response, route, default_app, static_file 
app = Bottle() 

@route('/upload', method='POST') 
def upload_file(): 
    function_name = sys._getframe().f_code.co_name 
    try: 
     upload = request.files.get("upload_file") 
     if not upload: 
      return "Nothing to upload" 
     else: 
      #Get file_name and the extension 
      file_name, ext = os.path.splitext(upload.filename) 
      if ext in ('.exe', '.msi', '.py'): 
       return "File extension not allowed." 

      #Determine folder to save the upload 
      save_folder = "/tmp/{folder}".format(folder='external_files') 
      if not os.path.exists(save_folder): 
       os.makedirs(save_folder) 

      #Determine file_path  
      file_path = "{path}/{time_now}_{file}".\ 
         format(path=save_folder, file=upload.filename, timestamp=time_now) 

      #Save the upload to file in chunks    
      upload.save(file_path, overwrite=False, chunk_size=1024) 
      return "File successfully saved {0}{1} to '{2}'.".format(file_name, ext, save_folder) 

    except KeyboardInterrupt: 
     logger.info('%s: ' %(function_name), "Someone pressed CNRL + C") 
    except: 
     logger.error('%s: ' %(function_name), exc_info=True) 
     print("Exception occurred111. Location: %s" %(function_name)) 
    finally: 
     pass 

if __name__ == '__main__': 
    run(host="localhost", port=8080, reloader=True, debug=True) 
else: 
    application = default_app() 

나는 또한 file.write하지만 같은 경우를 시도했다. 파일이 메모리로 읽혀지고 컴퓨터가 멈 춥니 다. 이것에

file_to_write = open("%s" %(output_file_path), "wb") 
while True: 
    datachunk = upload.file.read(1024) 
    if not datachunk: 
     break 
    file_to_write.write(datachunk) 

관련, 나는 몇 SO posts 주장이 하나가 최대 파일 업로드 크기를 설정할 수있는 특성 MEMFILE_MAX을 보았다. 나는 그것을 설정하려했지만 크기에 상관없이 모든 파일이 영향을 미치지 않는 것으로 보인다.

확장명이 명확하거나 암호로 압축 된 오피스 문서를받을 수 있기를 바랍니다. Python3.4 병 0.12.7

+0

lukik, 이것을 해결할 수 있었습니까? –

+0

안녕하세요. 아래 제안 사항에도 불구하고 여전히 전체 파일을 메모리에로드하고있었습니다. 연결하는 클라이언트에 대한 SFTP 상자를 퍼팅 결국하지만 업로드 작업을 제어 할 필요가 여전히이 작동하도록 할 .. 모든 새로운 제안? – lukik

답변

1

를 사용

는 기본적으로, 당신은 루프에서 upload.read(1024)를 호출합니다. 이 (안된) 식으로 뭔가 :

with open(file_path, 'wb') as dest: 
    chunk = upload.read(1024) 
    while chunk: 
     dest.write(chunk) 
     chunk = upload.read(1024) 

는 (. uploadopen를 호출하지 마십시오 이미 당신을 위해 열려)

This SO answer없이 큰 파일을 읽는 방법 SOF 많은 예제를 포함하여 "소리내어".

+0

'f = open (upload.file)'을 실행하려고 시도했지만 type_error'잘못된 파일 : <_io.BufferedRandom name = 8>'이 나타납니다. 도전 과제 내가 가진 도전 과제는'upload = request.files.get ("upload_file")'업로드 파일을'open ('really_big_file')을 사용하여 읽을 수있는 파일로 변환하는 방법입니다. – lukik

+0

' 'upload.file'에'열려 있습니다; 그것은 이미 당신이 사용할 준비가 된 파일과 같은 객체입니다. 그것에서 다만 읽으십시오. –

+0

@ b4hand, 나는'open'을 호출하여'destination' 파일을 만들고'upload'에서 읽지 않습니다. –