-1

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.

HACHI
  • 1
  • 6

2 Answers2

0

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

Insung Park
  • 401
  • 3
  • 15
0

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.

HACHI
  • 1
  • 6
  • In practice, this solution is not recommended. If project location was changed (someone pull your project other directories..), then your project will be broken and need to change code every location changes. – Insung Park May 18 '22 at 04:28
  • Thats very true, but as of now. As a matter of convencice. I believe this is the best option – HACHI May 18 '22 at 04:33
  • To fix that issue, you would probably use some part of the OS module to get the location of the python file, and then get the templates folder from there. – HACHI May 18 '22 at 04:38