2013-06-03 37 views
2

我在Python/Flask網絡應用程序中使用用戶提供的名稱作爲路徑組件:例如,用戶創建一個名爲「hello」的項目,提示我的web應用程序將一個名爲「data/hello /」的文件夾存儲用戶將上傳的文件。我想知道如何清理用戶提供的名稱,例如,用戶不能輸入「../hello」,並且要在不同的目錄中創建文件夾。最好的基於路徑的解決方案,我能想出是這樣的:如何清理Python和Flask中用戶提供的路徑?

import os.path 
rpath = os.path.relpath(input_path) 
safepath = rpath[rpath.index('../'):] 

有沒有更好的辦法,以確保我的web應用程序不訪問data目錄以外的文件?謝謝!

回答

5

WERKZEUG提供secure_filename以幫助此,作爲一個例子在Flask docs

@app.route('/', methods=['GET', 'POST']) 
def upload_file(): 
    if request.method == 'POST': 
     file = request.files['file'] 
     if file and allowed_file(file.filename): 
      filename = secure_filename(file.filename) #Sanitised here 
      file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) 
      return redirect(url_for('uploaded_file', 
            filename=filename)) 
提供
相關問題