如何从flask服务器中的外部文件夹访问文件? [英] How to access file from an external folder in flask server?

查看:97
本文介绍了如何从flask服务器中的外部文件夹访问文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Flask 的新手,对于将外部文件夹中的库包含到 html 模板中感到非常困惑.我知道如何从 static 文件夹中包含,但我想将我的代码和库文件保存在单独的文件夹中.所以,我的目录结构类似于:

I am new to flask and am very confused regarding including libraries from external folders into the html template. I know how to include from the static folder, but I want to keep my code and the library files in separate folders. So, my directory structure is something like:

./main_directory
|
|_./Code
| |_./flask_script.py
| |_./static
|
|_./Libraries

我知道 send_from_directory() 函数,但我不明白如何使用它.我见过的最常见的事情是:

I know about the send_from_directory() function but I don't understand exactly how to use it. The most common thing I have seen is:

@app.route('/cdn/<path:filename>')
def custom_static(filename):
    return send_from_directory(app.config['CUSTOM_STATIC_PATH'], filename)

这是来自另一个 StackOverflow 答案.但是在这种情况下,cdn 是什么?另外,app.confg['CUSTOM_STATIC_PATH'] 的值是多少?以及应该在 HTML 模板中完成哪些工作才能使这项工作正常进行?

Which is from another StackOverflow answer. But here what is cdn in this case? Also, what is the value of app.confg['CUSTOM_STATIC_PATH'] set to? And what all should be done in the HTML template to make this work?

推荐答案

一般来说,用flask 提供静态文件只对开发有好处.实际上,在上线时,建议以其他方式提供静态文件,例如在您的应用程序前面放置一个 Web 服务器并将文件服务委托给它,或者将文件放在文件存储中,例如 AWS S3.

In general serving static files with flask is only good for development. Realistically, when going live it is advised to serve static files otherwise, for example having a web server in front of your app and delegating file serving to it, or putting the files in a file store, like AWS S3.

关于你的 custom_static 路由,在这种情况下 cdn 只是一个 url 前缀(它可以是任何东西),然后你可以从诸如 .(cdn 前缀可以提示您这些文件稍后会移动到 CDN 并且不在生产中由flask 提供).

Regarding your custom_static route, cdn in this case is simply a url prefix (it can be anything), you can then address your static assets from templates like <img src="/cdn/test.jpg">. (The cdn prefix can give you a hint that these files are later moved to a CDN and aren't served by flask in production).

app.config['CUSTOM_STATIC_PATH'] 应设置为包含自定义静态文件的目录的绝对路径.

app.config['CUSTOM_STATIC_PATH'] should be set to the absolute path to the directory containing your custom static files.

这篇关于如何从flask服务器中的外部文件夹访问文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆