访问Flask中的嵌套静态文件夹的可能性 [英] Possibility of accesing Nested Static Folder in Flask
问题描述
- > static< BR>
----> css< BR>
------->图片< BR>
我们可以通过浏览器访问css目录下的文件。
例如 http:// localhost:5000 / static / css / file1.css
图片目录通过浏览器?
Flask使用静态路径设置静态文件路径(默认为 / static
)和任何文本。从来源:
self.add_url_rule(self.static_url_path +'/< path:filename>',
endpoint ='static',
view_func = self.send_static_file)
send_to_static
传递这个路由分配给<$ c
$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $' = cache_timeout)
如果你看 source send_from_directory
你会看到它只是使用 safe_join(目录,文件名)
获取文件路径。
safe_join
本身只是做一些工作来规范化路径, ..
在文件名中。
回到 URL路径, path
匹配任何文本。它就像 string
,除了接受斜线。这意味着您可以在静态文件夹中使用任何级别的嵌套。像 /static/file.txt
和 /static/p/a/t/h/t/o/file.txt
将全部工作。只要网址以你的静态路径开头,你想要的行为就可以直接使用:
http:// localhost :5000 / static / css / images / image1.png
By default, Flask allows one level of nesting within the Static Folder. For instance
->static <BR>
---->css <BR>
------->images<BR>
We can access files within the css directory through the browser.
e.g. http://localhost:5000/static/css/file1.css
How can we access the files within images directory through the browser ?
Flask sets up the route for static files using your static path (defaults to /static
) and any text. From the source:
self.add_url_rule(self.static_url_path + '/<path:filename>',
endpoint='static',
view_func=self.send_static_file)
send_to_static
passes whatever this route assigns to filename
.
return send_from_directory(self.static_folder, filename,
cache_timeout=cache_timeout)
If you look at the source for send_from_directory
you will see that it just uses safe_join(directory, filename)
to get the path to the file.
safe_join
itself just does some work to normalize the path and watch out for things like ..
in the filename.
Going back to the URL route, path
matches any text. It's like string
except it accepts slashes. This means that you can use any level of nesting within your static folder. URLs like /static/file.txt
and /static/p/a/t/h/t/o/file.txt
will all work. So long as the URLs begin with your static path, the behavior you want works out of the box:
http://localhost:5000/static/css/images/image1.png
这篇关于访问Flask中的嵌套静态文件夹的可能性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!