Home > Software engineering >  python file pass value to html with flask face Internal Server Error (jinja2.exceptions.TemplateNotF
python file pass value to html with flask face Internal Server Error (jinja2.exceptions.TemplateNotF

Time:02-02

python file pass value to html with flask

  • error

Internal Server Error
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.`

import mysql.connector
# from mysql import connector
import webbrowser
import time
import pymysql
from flask import Flask,render_template

app = Flask(__name__)

mydb = mysql.connector.connect(
  host="196.168.101.141",
  user="root",
  password="password123", 
  database="cool_db",  
  auth_plugin='mysql_native_password'
)
              
mycursor = mydb.cursor()
mycursor.execute("SELECT P_TITLE,P_DESC  FROM webpage WHERE P_ID = 'en_1-01'")                       
                                         
myresult = mycursor.fetchall()

print(myresult)    # does get the result I want 

# but below function not send "myresult" to html successfully
@app.route('/')
def index():
    return render_template("index.html", myresult = myresult)

if __name__ == "__main__":
    app.run()
  • index.html
<!DOCTYPE html>
<html>
    <body>
      <p> this is {{myresult}}</p>

    </body>
</html>

I already read through the discussion enter image description here

enter image description here

CodePudding user response:

You are getting this error because there is no index.html file present in the templates folder. In flask, you need to create a folder named templates in the same location where your app.py file is located. Inside that templates folder, you need to create the index.html file.

So, your directory structure should look like:

|- firstflaskapp.py
|- templates/
|   |- index.html

I am sure this will resolve your error.

The full directory structure followed used in flask is:

|- app.py
|- templates/
|   |- index.html
|   |- login.html
|   |- ...
|- static/
|   |- css/
|   |   |- main.css
|   |- images/
|   |   |- logo.png
|   |- ...
|- requirements.txt
  • app.py is the main Flask application file
  • templates/ directory contains HTML templates for the application
  • static/ directory contains static files like CSS, JS, images, etc.
  • requirements.txt is a text file containing the list of python libraries by the application.
  • Related