'How do I use flask render_template from a different directory [duplicate]

I need some help. Let me explain my situation. Let's assume that the main flask project is in ~/project as an example. Now the directory structure looks like

  • main.py
  • templates

inside of templates there is index.html. This is a standard project. Now if I was inside of ~ and I ran the command

python project/main.py

then I get an issue saying that Flask can't find index.html as a template. I assume the solution involves using the OS module. I'm not certain though.

The code for my main.py looks like this

from flask import Flask,render_template
app = Flask('app')

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

app.run(host='0.0.0.0', port=8080)

This works fine if i'm inside of the project directory. but not if i'm not in it

Can someone please help?

UPDATE: Using python3 instead of just python does not work.



Solution 1:[1]

I found the answer. Let me share it with you.

template_dir = os.path.abspath('~/project/templates')
app = Flask('app',template_folder=template_dir)

this is where the templates folder is being stored. this location is static. No matter where you are running from.

Solution 2:[2]

Have you tried FLASK_APP=project/main flask run on home directory?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 HACHI
Solution 2 Insung Park