gpt4 book ai didi

Python - flask : Static folder outside root directory

转载 作者:行者123 更新时间:2023-12-04 13:43:08 25 4
gpt4 key购买 nike

只是为了好玩,我想了解如何使用 Python 创建网站和 Flask .该网站必须在我自己的计算机上运行,​​而我将是唯一的客户。到目前为止,我完成了我想做的大部分工作,但现在我遇到了一个我无法解决的技术问题。

在客户端,我想显示服务器返回的图像。在 my __init__.py我放置了 app = Flask(__name__, static_url_path='/static')并在我的 html 文档中 <img src="/static/images/2012035.jpg" height="150px"> .这就像一个魅力。

但实际上,我的图像在目录 d:\genealogie\documenten 中,这是在应用程序目录之外,我不想将超过 2000 个文件复制到目录 static/images .

我试过:

documenten = "d:\genealogie\documenten"
os.mkdir(documenten)

这给出了 WinError 183因为目录已经存在。

我也试过:
documenten = "d:\genealogie\documenten"
app = Flask(__name__, static_url_path='documenten')

这给出了 ValueError : url 必须以斜杠开头。

我在这里看到了很多类似的问题,但不幸的是,我无法看到如何将答案用于我的特定问题。我可以以我作为用户可以要求说 <img src="documenten/2012035.jpg" height="150px"> 的方式配置网站吗? ,也许与一些或其他 localhost字首?任何帮助都受到高度赞赏。

编辑

我想要做的是让服务器访问服务器目录之外的目录。也许我可以通过在 WAMP 中展示这可以多么容易地做到这一点来说明这一点。 .我们只需要在文件 httpd.conf 中添加几行.例如:
Include "C:/wamp64/alias/*"

Alias /adressen "d:/adressen"
<Directory "d:/adressen">
Options Indexes FollowSymLinks Multiviews
AllowOverride all
Require all granted
</Directory>

Alias /genealogie "d:/genealogie"
<Directory "d:/genealogie">
Options Indexes FollowSymLinks Multiviews
AllowOverride all
Require all granted
</Directory>

服务器及其所有文件都在 c:/wamp64 中及其子目录。但是当我们包含 <img src="http://localhost/genealogie/documenten/doc1064.jpg"><img src="http://localhost/adressen/doc5127.jpg">html文档,尽管它们实际上位于远离 WAMP 的地方,但它们的显示效果很好。 ,即使在不同的驱动器上。所以我的问题是:我们可以用 FLASK 做到这一点吗?还有吗?

最佳答案

所以你需要用你的python代码打开文件夹,提取正确的图片并发送给你的用户?

你可以这样做

file = "d:\genealogie\documenten\your_file_name" #you may consider a path library so you can do this in windows or Linux 
os.open(file) #you should really use a image library here. open is just a placeholder

换句话说,您想在代码(函数、类等)中打开图像,然后对图像执行任何您需要执行的操作。例如将其返回给用户。

我个人会尝试使用这样的东西:
from flask import send_file 
file = "d:\genealogie\documenten\your_file_name" #you may consider a path library so you can do this in windows or Linux
return send_file(file, mimetype='image/jpg') #in case of jpg image, you may opt to not use the mimetype

你不能这样做
documenten = "d:\genealogie\documenten" 
app = Flask(__name__, static_url_path='documenten')

但为什么?
基本上是 static_url_path是用户在浏览器中输入的 url。这与您在服务器上的文件夹结构无关。哎呀,你甚至不需要在你的服务器上有文件夹。

您的互联网呈现的结构不必与您的文件系统的结构相关。基本上,这是两个完全不同的世界在这里碰撞。

URL用于分层构建网络,主要应对组织结构(域、子域)。另一方面,文件服务器可以以多种方式构建。通常,您希望表示文件的性质和/或文件的年龄。

顺便说一句, mkdir命令创建文件夹,但您已经有了一些。

关于Python - flask : Static folder outside root directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53970696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com