【发布时间】:2017-05-10 03:26:50
【问题描述】:
tl;dr 版本:如何让我的 Flask 应用加载不在项目目录中的图像?
我正在构建(作为一个有趣的项目)一个 Flask 应用程序,它被设计为一个命令行应用程序,它从浏览器的当前工作目录中加载一个随机图像。这是应用程序结构的样子。
+-- imgdisplay/
+-- imgdisplay/
+-- imgdisplay.py
+-- static/
+-- styling.css
+-- templates/
+-- img.html
+-- setup.py
+-- LICENSE
+-- README.md
我的setup.py 有一个entry_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>
总而言之,这是一个非常简单的 Flask 应用程序。像我这样的菜鸟会建造的东西。
在我的桌面上,我有一个名为images/ 的文件夹,我在其中放置了一张图片。我可以在浏览器中显示文件名字符串,但无法显示图像;我希望在浏览器中看到加载的图像,但我得到的只是显示无法找到图像的图标。请原谅我在这里的菜鸟,但我在这里缺少的关键概念是什么?
【问题讨论】:
-
如果有人想要上下文,我正在尝试将其构建为一个文件夹的前端界面,我可以在其中放入新图像并使用 Raspberry Pi 在浏览器中重新加载。尝试在这里发挥创意:-)
-
文中已说明。 "我可以在浏览器中显示图片文件名,但是不能显示图片。"
-
我很抱歉,但我感到沮丧来自这种认为我是新手 SO 用户的感觉。我所展示的正是我迄今为止所做的。我的网络开发经验几乎为零;我的大部分 SO 经验都是在数据科学领域。这是我对您的问题的回答:我不要求图像,但我应该这样做吗?这里没有抛出错误,并且我已经设置了静态目录(请参阅顶部发布的目录结构)。
-
stackoverflow.com/a/41316717/5802335你的答案就在这里。