Flask代码结构组织

如果Flask代码结构组织如下:

flaskProject:.
            │  config.py
            │  my.sqlite
            │  README.md
            │
            ├─.idea
            │  │  .gitignore
            │  │  XXX.xml # pycharm/idea的控制文件
            │
            ├─app
            │  │  routes.py # 路由视图函数
            │  │  __init__.py
            │  │
            │  └─__pycache__
            │          routes.cpython-37.pyc
            │          __init__.cpython-37.pyc
            │
            ├─static
            ├─templates #模板
            │      404.html
            │      500.html
            │      base.html
            │
            └─__pycache__
                    app.cpython-37.pyc

此时在视图函数当中对模板进行渲染的时候,如果写成下面这样会报错:Cannot find templates

@app.errorhandler(404)
def handle(e):
    return render_template('404.html'), 404

如果告诉程序templates的所在位置就可以解决:

app=Flask(__name__,template_folder='../templates')

static也是相同原理。原因是flask默认的是放置模板文件夹叫做templates且和运行文件在同一级目录下。