2016-12-25 60 views
3

TL加載圖像;博士版本:如何讓我的瓶的應用程序不加載圖像在項目目錄?瓶應用:從當前工作目錄

我正在構建(作爲一個有趣的項目)Flask應用程序,它是一個命令行應用程序,用於從瀏覽器中的當前工作目錄加載一個隨機圖像。這是應用程序結構的樣子。

+-- imgdisplay/ 
    +-- imgdisplay/ 
     +-- imgdisplay.py 
     +-- static/ 
      +-- styling.css 
     +-- templates/ 
      +-- img.html 
    +-- setup.py 
    +-- LICENSE 
    +-- README.md 

setup.pyentry_points關鍵字論點如下:

entry_points={ 
    'console_scripts': [ 
     'imgdisplay=imgdisplay.imgdisplay:start_server' 
    ] 

這讓我從任何地方開始的命令行應用程序imgdisplay。我已經證實這部分工作沒有問題。

imgdisplay.py代碼如下所示:

from flask import Flask, render_template 
import webview 
import click 
from random import choice 
import os 
import os.path as osp 
import logging 

app = Flask(__name__) 


# logging.setLevel(logging.DEBUG) 

@app.route('/') 
def hello(name=None): 
    files = os.listdir(os.getcwd()) 
    image = choice([f for f in files if f[-4:] == '.jpg']) 
    # tried the following line, but didn't work. 
    # image = osp.join(os.getcwd(), image) 
    # logging.info(image) 
    return render_template('img.html', name=name, files=files, image=image) 


@click.command() 
@click.option('--port', default=5000, help='Port', prompt='Port') 
@click.option('--host', default='localhost', help='Host', prompt='Host') 
def start_server(port=5000, host='localhost'): 
    app.run(host='localhost', port=port) 


if __name__ == '__main__': 
    start_server() 

img.html模板如下所示:

<!doctype html> 
<head> 
<link href="https://fonts.googleapis.com/css?family=PT+Sans" rel="stylesheet"></link> 
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styling.css') }}"> 
</head> 
<body> 
    <title>Hello from Flask</title> 
    {% if name %} 
     <h1>Hello {{ name }}!</h1> 
    {% else %} 
     <h1>Hello, World!</h1> 
    {% endif %} 

    {{ image }} 

    {% if image %} 
     <img src="{{ image }}"></img> 
    {% endif %} 

</body> 

總而言之,這是一個非常簡單的應用程序瓶。像我這樣的小事會建立。

在我的桌面,我有一個名爲images/文件夾,在其中我把一個單一的形象。我可以在瀏覽器中顯示文件名字符串,但無法顯示圖像;我希望看到在瀏覽器中加載的形象,但我得到的是顯示圖像無法找到圖標。請原諒我在這裏的低調,但我在這裏錯過的關鍵概念是什麼?

+0

如果有人想開發方面,我想建立這個作爲前端界面中,我可以在新的圖像下降,在瀏覽器中重新加載,使用樹莓派的文件夾。試圖讓創意在這裏:-) – ericmjl

+0

那是在文字寫得很清楚了。 「我可以在瀏覽器中顯示圖像文件名,但無法顯示圖像。「 – ericmjl

+0

對不起,但我覺得這種感覺令人沮喪,因爲我是一個新手SO用戶,我所展示的正是我迄今爲止所做的,我的web開發經驗接近於零;大多數我的SO經驗一直存在於數據科學領域,下面是我對你的問題的迴應:我沒有要求這個圖像,但是我應該這樣做嗎?這裏沒有錯誤,並且我設置了靜態目錄(參見目錄結構右上角) – ericmjl

回答

1

我可以在瀏覽器中顯示的文件名字符串

這不是瀏覽器的網絡功能,這是一個瀏覽器本地文件系統的功能,但是,當你把路徑如/home/yetship/images/test.jpg在在HTML這樣的:

<html> 
    <body> 
     <img src="/home/yetship/images"></img> 
    </body> 
</html> 

它肯定將無法工作,因爲如果你訪問你的網站的網址:http://localhost:8080,img標籤不會與路徑/home/yetship/images,而不是你的電腦發現的形象,它會找到圖像http://localhost:8080/home/yetship/images,所以,如果你想要讓它顯示,應以下this guide,讓您image目錄靜態目錄,你應該讓img標籤爲:

<img src="image/test.jpg"></img> 

,而不是

<img src="/home/yetship/image/test.jpg"></img> 

和瓶將在您的image目錄中找到的圖像,並顯示在你的瀏覽器。

我希望這可以幫助你。