【轉載】前端上傳文件,python作爲後端接收並保存到本地--Tornado上傳文件--分片上傳文件--更換pip下載源

背景:在改造caffe自帶demo時,增加了一個更新模型的功能,需要將用戶訓練好的caffemodel上傳到服務器,並替換到已經存在的caffemodel文件,重新加載上傳的caffemodel文件並運行。最終改動結果頁面如下:

1、使用Tornado上傳文件

在海洋生物識別的過程中有一個上傳本地圖片進行檢測的功能,對應這個功能進行了修改,但是出現以下錯誤,基本意思是Tornado默認上傳大小爲100MB 如果超過該大小就會出現以下錯誤。這裏可以通過修改max_buffer_size屬性來改變默認的上傳大小,但是這裏會有風險,因爲Tornado是通過單字符串讀入內存中的。

'Content-Length too' long when uploading file using Tornado

錯誤解釋:

Tornado has a configurable limit on upload size (defaulting to 10MB). You can increase the limit by 
passing max_buffer_size to the HTTPServer constructor (or Application.listen). However, since 
Tornado (version 3.1) reads the entire upload body into a single contiguous string in memory, it's 
dangerous to make the limit too high.

不過這裏如果小於100MB 的小文件還是推薦使用的,代碼可以參考caffedemo的,關鍵代碼如下

前端

 <script type="text/javascript">
      $(document).ready(
        function(){
          $('#classifyfile').attr('disabled',true);
          $('#imagefile').change(
            function(){
              if ($(this).val()){
                $('#formupload').submit();
              }
            }
          );
        }
      );
    </script>
<body>
 <form id="formupload" class="form-inline" role="form" action="classify_upload" method="post" enctype="multipart/form-data">
        <div class="form-group">
          <label for="imagefile">檢測本地圖像:</label>
          <input type="file" name="imagefile" id="imagefile">
        </div>
        <!--<input type="submit" class="btn btn-primary" value="Classify File" id="classifyfile"></input>-->
      </form>
</body>

Python後端代碼:

@app.route('/model_upload', methods=['POST'])
def model_upload():
    try:
        # We will save the file to disk for possible data collection.

        model_file = flask.request.files['model_file']

        filename_ = werkzeug.secure_filename(model_file.filename)
        filename = os.path.join(UPLOAD_MODEL_FOLDER, filename_)
        model_file.save(filename)
        #filename = filename
        #imagefile.save(filename)
        logging.info('Saving to %s.', filename)
        #image = exifutil.open_oriented_im(filename)
        return flask.render_template(
            'right_update.html', has_result=True,
            result=(True, '上傳成功')
        )
        #start_from_terminal(app)
    except Exception as err:
        logging.info('Uploaded model open error: %s', err)
        return flask.render_template(
            'right_update.html', has_result=True,
            result=(False, 'Cannot open uploaded caffemodel.')
        )

2、使用分片上傳文件

感謝博主提供的代碼,十分有幫助。請參考 大文件分片傳輸

這裏爲了展示效果粘貼一下效果圖

上傳成功

上傳錯誤

3、更換pip下載源

由於在使用pip install 下載一下包時候由於網絡原因總是超時,這裏解決有三種方法,分別是:

(1)更換下載源

(2)fq

(3)修改默認超時時間

這裏參考了替換pip下載源

寫入內容爲:

[global]
timeout = 6000
index-url = https://pypi.douban.com/simple
trusted-host = pypi.douban.com

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章