以前只知道使用下面这样的代码来创建我的Flask应用:

from flask import Flask
app = Flask(__name__)

不过从下面的Flask的 init 函数可以看出,其实还有好几个属性是可以在创建应用的时候就指定的:

 def __init__(self, import_name, static_path=None, static_url_path=None,
static_folder='static', template_folder='templates'):
_PackageBoundObject.__init__(self, import_name,
template_folder=template_folder)
if static_path is not None:
from warnings import warn
warn(DeprecationWarning('static_path is now called '
'static_url_path'), stacklevel=2)
static_url_path = static_path
if static_url_path is not None:
self.static_url_path = static_url_path
if static_folder is not None:
self.static_folder = static_folder
....

从上面的代码可以看出,在标准的 Flask 应用目录结构上面还是可以修改的,标准的目录结构如下:

/application
/app.py
/static
/style.css
/....
/templates
/layout.html
/index.html
/....

如果是这样的话,那么在使用@url_for(‘static’,filename=‘style.css’)@函数时,Flask会发送上面static目录下style.css文件的内容,但是如果我们不想把静态文件放在 static 这个目录下,而是 misc 这个目录下面,那么可以是这样的创建Flask 应用

app = Flask(__name__,static_folder='misc')

这个时候,@url_for(‘static’,filename=‘style.css’)@ 这个函数发送的文件将是 /misc/style.css 。同样,我们也可以这样指定 templates 的目录为其它的或者更加适合自己的风格的,当然咯,做为一个Python程序员,不建议把个人风格带到程序里面去。

标签: none

评论已关闭