1

This is absolutely new field for me, and I just confused about how this work

Flask server

$ more flask-hello-world.py 
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return render_template('index.html') #"Hello World!"

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

index.html

$ more index.html 
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>untitled</title>
</head>
<body>

Hello worlds
</body>
</html>

Test

$ curl 127.0.0.1:5000
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request.  Either the server is overloaded or there is an error in the application.</p>

When I return "Hello World!" it does work properly. Why am I getting an error when I try return render_template('index.html')?

zabumba
  • 12,172
  • 16
  • 72
  • 129

2 Answers2

6

First of all you should turn on debugging for your Flask app, so you see a meaningful error instead of a canned HTTP 500 Internal Server Error.

app.debug = True
app.run()

or

app.run(debug=True)

What could be wrong with your Flask app

From your source code I see you have not imported render_template

So that is at least one issue, fix it with:

from flask import Flask, render_template
# The rest of your file here

Template names and directory

There is a parameter template_folder you can use to tell Flask where to look for your templates. According to linked documentation, that value defaults to templates which means Flask by default looks for templates in a folder called templates by default. So if your templates are on the project root instead of a folder, use:

E.g. if your templates are in the same directory is the app:

app = Flask(__name__, template_folder='.') # '.' means the current directory
bakkal
  • 54,350
  • 12
  • 131
  • 107
  • I put the `.py` and the `index.html` in the same folder ... that's the problem right ?! the templates should go a special folder? – zabumba Jan 25 '16 at 15:59
  • 1
    Yes `templates` is the default, but I provided code for it to look for the templates in the same folder as the flask app – bakkal Jan 25 '16 at 16:00
3

You need to put your templates in templates folder, or ovride it in:

app = Flask(__name__, template_folder='.')
ahmed
  • 5,430
  • 1
  • 20
  • 36