Troubleshoot TemplateNotFound error from Flask under Gunicorn

前端 未结 3 1413
故里飘歌
故里飘歌 2021-02-19 10:23

I\'ve got a Flask app that I\'m trying to deploy using Gunicorn and nginx. However, although it works fine locally, it throws a TemplateNotFound error when I run in with Gunicor

相关标签:
3条回答
  • 2021-02-19 10:53

    I have just spent 2 hours in a very similar situation and thought I'd post what ended up being the solution.

    I was suddenly getting TemplateNotFound errors in the Apache logs from my Flask application, in production, which had been running fine until then. This resulted in 500 errors across the site.

    First issue was that the TemplateNotFound errors did not show unless I had Flask's "debug" flag on -- there was no sign of any problems at all in the Apache log despite LogLevel set to info.

    Running the app "locally" (Flask listens on localhost:5000) was fine (one can test the pages via wget 127.0.0.0:5000). It turned out that a copy of the main web app python code had somehow landed in the directory above where it should have been. This was imported by wsgi first and, as a result, the relative path to templates was incorrect.

    0 讨论(0)
  • 2021-02-19 11:07

    Are your templates in [app root]/templates/?

    If so, check to be sure your path is correct. Put this as the first line in the view that handles your homepage:

    return app.root_path
    

    If that's what you expect to see - or if you're using Blueprints or another method that changes the default Jinja Environment somehow - it's a little more complicated.

    Oddly, Jinja doesn't seem to have a jinja2.Environment.FileSystemLoader.get_search_path() method. I assumed it would have one :(

    0 讨论(0)
  • 2021-02-19 11:14

    Today, I experienced identical problems after a long period of my Flask app behaving quite normally (ie not throwing TemplateNotFound exceptions). None of the approaches mentioned by others here hit the mark or seemed appropriate (eg app.debug, path manipulation).

    Instead, I tracked it down to the standard Flask app initialisation line:

    app = Flask(__name__)
    

    I had changed __name__ to another value (to get access to a named logger), not expecting for all this carnage to unfold :-) Don't change this value unless you are very familiar with Flask internals.

    0 讨论(0)
提交回复
热议问题