2013-08-23 29 views
2

我目前正在將所有靜態文件移動到S3,以及允許一些圖像上傳到我的網站。總的來說,這是非常驚人的。我將所有現有的css和js文件全部上傳到S3,但是我在上傳圖像並將其保存到S3時遇到了一些麻煩。燒瓶url_for錯誤地鏈接到模板以外的靜態頁面

具體來說,這是我如何處理我的視圖中上傳文件:

image_file = request.files["imageurl"] 
if image_file and allowed_file(image_file.filename): 
    fn = "products/%s" % secure_filename(image_title + "." + image_file.filename.split(".")[-1]) 
    image_file.save(url_for('static', filename=fn)) 
else: 
    response = app.make_response(render_template(
     'admin/newImage.html', 
     title=title, 
     error="That Image file is invalid.") 
    ) 
    return response 

這是一個POST請求處理程序的所有包裝材料。這裏的問題是,url_for('static')無法鏈接到正確的路徑,所以我在任何時候嘗試保存這樣的圖像時都會得到IOError

通常我會認爲我只是在對我的目錄結構做一些愚蠢的事情,但url_for的相同模式對我的靜態目錄中的文件非常適用。任何想法如何彌補這一點?這裏是我的目錄結構(下調觀看)

├── SpoolEngine 
│   ├── admin.py 
│   ├── __init__.py 
│   ├── templates 
│   │   ├── admin 
│   │   │   ├── base.html 
│   │   ├── base.html 
│   │   ├── _forms.html 
│   │   ├── posts 
│   │   │   ├── complete.html 
│   │   └── super_user 
│   │    ├── base.html 
│   ├── users.py 
│   └── views.py 
└── static 
    ├── css 
    │   ├── admin.css 
    │   └── zebraTable.css 
    ├── img 
    │   └── subtle_grunge.png 
    ├── js 
    │   ├── compatibility.js 
    │   ├── list.js 
    │   ├── login.js 
    │   └── profiler.js 
    └── products 

以供參考,url_for完美的作品中/static/css和鏈接從admin.py任何想法錯了網址?

回答

1

url_for返回一個url路徑。不是文件系統路徑。

所以你試圖保存你的文件在/static/something這對系統來說意味着一個從文件系統根目錄開始的路徑,而不是你的應用程序路徑。

你可以用的東西爲你的文件static路徑這樣

static_path_to_save = os.path.join([app.root_path, '/static', fn]) 

只是一個側面說明,與上傳打交道時,記得要sanityze所有的路徑,並仔細檢查了目的地。最佳做法適用,例如,如果使用用戶提供的filename(如果生成文件名,最好是剝離斜槓)。

在你的代碼中,如果2個用戶上傳一個相同名稱的文件,相互覆蓋,我也會看到一個問題。但這在你的情況下可能是安全的。