猿问

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

只是为了好玩,我试图了解如何使用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: urls 必须以前导斜杠开头。


我在这里看到了很多类似的问题,但不幸的是,我无法看到如何将答案用于我的特定问题。我可以以我作为用户可以要求说的方式配置网站<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吗?


HUWWW
浏览 383回答 1
1回答

蛊毒传说

所以你需要用你的python代码打开文件夹,提取正确的图片并发送给你的用户?你可以这样做file = "d:\genealogie\documenten\your_file_name" #you may consider a path library so you can do this in windows or Linux&nbsp;os.open(file) #you should really use a image library here. open is just a placeholder换句话说,您想在代码(函数、类等)中打开图像,然后对图像执行任何您需要执行的操作。例如将其返回给用户。我个人会尝试使用这样的东西:from flask import send_file&nbsp;file = "d:\genealogie\documenten\your_file_name" #you may consider a path library so you can do this in windows or Linux&nbsp;return send_file(file, mimetype='image/jpg') #in case of jpg image, you may opt to not use the mimetype你不能这样做documenten = "d:\genealogie\documenten"&nbsp;app = Flask(__name__, static_url_path='documenten')但为什么?基本上static_url_path是用户输入浏览器的网址。这与您在服务器上的文件夹结构无关。哎呀,你甚至不需要在你的服务器上有文件夹。您的互联网呈现的结构不必与您的文件系统的结构相关。基本上,这是两个完全不同的世界在这里碰撞。URL用于分层构建网络,主要应对组织结构(域、子域)。另一方面,文件服务器可以以多种方式构建。通常,您希望表示文件的性质和/或文件的年龄。顺便说一句,该mkdir命令会创建文件夹,但您已经拥有了一些。
随时随地看视频慕课网APP

相关分类

Python
我要回答