2017-04-24 35 views
1

我在這裏提到的鏈接:More than one static path in local Flask instance,並試圖讓顯示在瀏覽器選項卡中的圖像文件,但不能這樣做。無法排除錯誤。 stored_name是存儲在由app config常量變量指定的路徑中的文件的物理文件名:'UPLOAD_FOLDER'。 此文件夾不在靜態文件夾及其子文件夾路徑中。我想增加文件(也可能是圖像文件)的存儲容量,稍後添加硬盤空間,如果我使用靜態文件夾存儲,這很困難。我不希望應用程序初始化(工作)瓶子api中的自定義靜態路徑?

代碼片段中重寫靜態文件夾:

從瓶進口send_from_directory

@app.route('/api/v1.0/docs/<path:filename>', methods=["GET"]) 
def img_render(filename): 
    print 'Called here' 
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename) 


@app.route('/api/v1.0/docs/<int:doc_id>',methods=["GET"]) 
def image_rendering(doc_id): 
    s = select([docs]).where(docs.c.id==doc_id) 
    rs = conn.execute(s).fetchone() 
    filename = str(rs[docs.c.stored_name]) 

    return url_for('img_render', filename=filename) 

HTML模板:

<!DOCTYPE html> 
<html> 
    <body> 
    <img src="{{url_for('img_render', filename=filename) }}" /> 
    </body> 
</html> 

的模板在模板文件夾中。如果我的應用程序的初始化過程覆蓋原來的靜態文件夾,我能夠獲得在瀏覽器中顯示的圖像,但我不得不改變我的參考應用程序的靜態文件夾OR我會上傳圖片到靜態文件夾從應用程序,我不想做的什麼是錯誤的,它只是顯示圖像的瀏覽器例如路徑:

/api/v1.0/docs/1_20160707_121214.jpg

,而不是圖像本身?代碼中的錯誤在哪裏?使用燒瓶v0.11,linux 2.7。

回答

1

image_rendering方法返回一個字符串(這是你在瀏覽器中看到的)時,它應該返回一個模板渲染的結果。

替換「mytemplate.html」具有下列樣品在HTML模板的名稱。

from flask import render_template 

@app.route('/api/v1.0/docs/<int:doc_id>',methods=["GET"]) 
def image_rendering(doc_id): 
    s = select([docs]).where(docs.c.id==doc_id) 
    rs = conn.execute(s).fetchone() 
    filename = str(rs[docs.c.stored_name]) 

    return render_template('mytemplate.html', filename=filename) 

這是一個簡單的Flask應用程序在Windows中工作。在我的d:\ temp文件夾中有一個文件test.jpg。確保您的Flask應用程序具有正確的權限來讀取上傳文件夾中的文件。要通過瀏覽http://127.0.0.1:5000/api/v1.0/docs/99:在templates文件夾

from flask import Flask, send_from_directory, render_template 

app = Flask(__name__) 
app.config['UPLOAD_FOLDER'] = 'd:/temp' 


@app.route('/') 
def hello_world(): 
    return 'Hello World!' 


@app.route('/api/v1.0/docs/<path:filename>', methods=["GET"]) 
def img_render(filename): 
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename=filename, mimetype='image/jpeg') 


@app.route('/api/v1.0/docs/<int:doc_id>',methods=["GET"]) 
def image_rendering(doc_id): 
    # ignore doc_id, we'll use a constant filename 
    filename = 'test.jpg' 
    return render_template('test.html', filename=filename) 


if __name__ == '__main__': 
    app.run() 

的test.html:

<!DOCTYPE html> 
<html> 
    <body> 
    <img src="{{url_for('img_render', filename=filename) }}" /> 
    </body> 
</html> 
+0

我已經嘗試了上面也。它只是顯示縮略圖,而不是實際的圖像。 – user956424

+0

在你的'img_render'函數中,不是打印'在這裏調用',而是打印傳遞給函數的文件名,即'打印文件名'。這是圖像的預期名稱嗎? – pjcunningham

+0

是的,我得到的文件名正確 – user956424