Python - Flask:根目录外的静态文件夹

Fre*_*ons 5 python wamp flask

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

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

但事实上,我的图像位于d:\genealogie\documenten应用程序目录之外的一个目录中,我不想将超过 2000 个文件复制到该目录中static/images

我试过:

documenten = "d:\genealogie\documenten"
os.mkdir(documenten)
Run Code Online (Sandbox Code Playgroud)

给出 aWinError 183因为该目录已经存在。

我也尝试过:

documenten = "d:\genealogie\documenten"
app = Flask(__name__, static_url_path='documenten')
Run Code Online (Sandbox Code Playgroud)

这给出了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>
Run Code Online (Sandbox Code Playgroud)

服务器及其所有文件都位于c:/wamp64及其子目录中。但是,当我们在文档中包含<img src="http://localhost/genealogie/documenten/doc1064.jpg">和 时,这两个图像都会很好地显示,尽管事实上它们实际上位于很远的地方,甚至位于不同的驱动器上。所以我的问题是:我们也可以这样做吗?<img src="http://localhost/adressen/doc5127.jpg">htmlWAMPFLASK

not*_*353 2

那么您需要使用 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
Run Code Online (Sandbox Code Playgroud)

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

我个人会尝试使用这样的东西:

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
Run Code Online (Sandbox Code Playgroud)

你不能这样做

documenten = "d:\genealogie\documenten" 
app = Flask(__name__, static_url_path='documenten')
Run Code Online (Sandbox Code Playgroud)

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

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

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

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