code

Flask는 템플릿 파일이 존재하더라도 TemplateNotFound 오류를 발생시킵니다.

codestyles 2020. 12. 3. 07:53
반응형

Flask는 템플릿 파일이 존재하더라도 TemplateNotFound 오류를 발생시킵니다.


파일을 렌더링하려고합니다 home.html. 내 프로젝트에 파일이 있지만 jinja2.exceptions.TemplateNotFound: home.html렌더링하려고하면 계속 표시됩니다. Flask가 내 템플릿을 찾을 수없는 이유는 무엇입니까?

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html')
/myproject
    app.py
    home.html

올바른 위치에 템플릿 파일을 만들어야합니다. templatesPython 모듈 옆 하위 디렉토리에 있습니다.

이 오류는 디렉토리에 home.html파일 이 없음을 나타냅니다 templates/. 파이썬 모듈과 동일한 디렉토리에 해당 디렉토리를 생성했는지, 실제로 home.html해당 하위 디렉토리에 파일을 넣었는지 확인하십시오 . 앱이 패키지 인 경우 패키지 내부에 템플릿 폴더를 만들어야 합니다.

myproject/
    app.py
    templates/
        home.html
myproject/
    mypackage/
        __init__.py
        templates/
            home.html

또는 템플릿 폴더의 이름을 다른 templates이름으로 지정하고 기본값으로 이름을 바꾸고 싶지 않은 경우 Flask에 다른 디렉터리를 사용하도록 지시 할 수 있습니다.

app = Flask(__name__, template_folder='template')  # still relative to module

EXPLAIN_TEMPLATE_LOADING옵션로 설정하여 주어진 템플릿을 찾으려고 시도한 방법을 설명하도록 Flask에 요청할 수 있습니다 True. 로드 된 모든 템플릿 에 대해 레벨에서 Flask에app.logger 기록 된 보고서를 받게 됩니다 INFO.

검색이 성공했을 때의 모습입니다. 이 예에서 foo/bar.html템플릿은 템플릿을 확장 base.html하므로 두 가지 검색이 있습니다.

[2019-06-15 16:03:39,197] INFO in debughelpers: Locating template "foo/bar.html":
    1: trying loader of application "flaskpackagename"
       class: jinja2.loaders.FileSystemLoader
       encoding: 'utf-8'
       followlinks: False
       searchpath:
         - /.../project/flaskpackagename/templates
       -> found ('/.../project/flaskpackagename/templates/foo/bar.html')
[2019-06-15 16:03:39,203] INFO in debughelpers: Locating template "base.html":
    1: trying loader of application "flaskpackagename"
       class: jinja2.loaders.FileSystemLoader
       encoding: 'utf-8'
       followlinks: False
       searchpath:
         - /.../project/flaskpackagename/templates
       -> found ('/.../project/flaskpackagename/templates/base.html')

Blueprint는 자체 템플릿 디렉토리등록 할 수 있지만, Blueprint를 사용하여 더 큰 프로젝트를 논리 단위로 쉽게 분할 할 수있는 경우에는 필요하지 않습니다. Blueprint 당 추가 경로를 사용하는 경우에도 기본 Flask 앱 템플릿 디렉터리가 항상 먼저 검색됩니다.


Flask는 기본적으로 디렉토리 템플릿을 사용한다고 생각합니다. 따라서 귀하의 코드는 이것이 귀하의 hello.py라고 가정해야합니다.

from flask import Flask,render_template

app=Flask(__name__,template_folder='template')


@app.route("/")
def home():
    return render_template('home.html')

@app.route("/about/")
def about():
    return render_template('about.html')

if __name__=="__main__":
    app.run(debug=True)

그리고 작업 공간 구조는

project/
    hello.py        
    template/
         home.html
         about.html    
    static/
           js/
             main.js
           css/
               main.css

또한 home.html 및 about.html 이름으로 두 개의 html 파일을 만들고 해당 파일을 템플릿 폴더에 넣습니다.


이유는 모르겠지만 대신 다음 폴더 구조를 사용해야했습니다. 나는 "템플릿"을 한 단계 위로 올렸다.

project/
    app/
        hello.py
        static/
            main.css
    templates/
        home.html
    venv/

이것은 아마도 다른 곳에서 잘못 구성되었음을 나타낼 수 있지만 그것이 무엇인지 알 수 없었고 이것이 작동했습니다.


After following this thread and others for a solution to the same issue without success I found a working solution for my current project. (Please note that the above accepted Answer provided for file/project structure is going to work for most cases and is absolutely correct, I'm just showing what specifically worked for me.)

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

the same worked for /static/style.css after discovering .css files weren't linking properly to .html files...

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

in addition to properly setting up the project structure, we have to tell flask to look in the appropriate level of the directory hierarchy.

i hope this helps


Check that:

  1. the template file has the right name
  2. the template file is in a subdirectory called templates
  3. the name you pass to render_template is relative to the template directory (index.html would be directly in the templates directory, auth/login.html would be under the auth directory in the templates directory.)
  4. you either do not have a subdirectory with the same name as your app, or the templates directory is inside that subdir.

If that doesn't work, turn on debugging (app.debug = True) which might help figure out what's wrong.


You need to put all you .html files in the template folder next to your python module. And if there are any images that you are using in your html files then you need put all your files in the folder named static

In the following Structure

project/
    hello.py
    static/
        image.jpg
        style.css
    templates/
        homepage.html
    virtual/
        filename.json

I had the same error turns out the only thing i did wrong was to name my 'templates' folder,'template' without 's'. After changing that it worked fine,dont know why its a thing but it is.


When render_template() function is used it tries to search for template in the folder called templates and it throws error jinja2.exceptions.TemplateNotFound when :

  1. the html file do not exist or
  2. when templates folder do not exist

To solve the problem :

create a folder with name templates in the same directory where the python file is located and place the html file created in the templates folder.


Another alternative is to set the root_path which fixes the problem both for templates and static folders.

root_path = Path(sys.executable).parent if getattr(sys, 'frozen', False) else Path(__file__).parent
app = Flask(__name__.split('.')[0], root_path=root_path)

If you render templates directly via Jinja2, then you write:

ENV = jinja2.Environment(loader=jinja2.FileSystemLoader(str(root_path / 'templates')))
template = ENV.get_template(your_template_name)

참고URL : https://stackoverflow.com/questions/23327293/flask-raises-templatenotfound-error-even-though-template-file-exists

반응형