Home > Software design >  How do I use flask render_template from a different directory
How do I use flask render_template from a different directory

Time:05-18

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.

CodePudding user response:

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

CodePudding user response:

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.

  • Related