I was having issues with render_template as part of a function in a larger program. It wouldn’t launch the html file that i passed to it as an argument. I stripped everything out and it is still not doing anything. Not getting any errors, verified that html file is in the templates folder, as well as specified the folder via app = Flask(name, template_folder=’../templates’).
Below is the python code:
from flask import Flask, render_template
from replit import web
app = Flask(__name__, template_folder='../templates')
@app.route('/')
def index():
return render_template('renderindex.html',username=web.auth.name,userid=web.auth.user_id)
Below is the html code:
<body>
<main>
<h1>Templating</h1>
<!-- This is the jinja syntax to use variables passed in from render_template. -->
<h2>Hello, {{ username }}!</h2>
<p>Your Replit UserID is {{ userid }}.</p>
</main>
</body>
Project Structure:
Documents
static
templates
renderindex.html
rendertest.py
Snippet of the problem from full program:
import requests
import jwt
import datetime
import time
import json
import sys
import os
from flask import Flask, request, jsonify, render_template
app = Flask(__name__, template_folder='templates\')
@app.route('/')
def index():
return open('webpage.html').read()
@app.route('/store_values', methods=['POST'])
def store_values():
data = request.get_json()
production_order = data['productionOrder']
print("Production Order:", production_order)
production_order = "P50012960"
# Call the function to make API requests
response_data = make_api_requests(production_order)
query_results = json.loads(response_data)
print("Query Results:", query_results)
# You can return a response if needed
return(display_results(query_results))
@app.route('/')
def display_results(query_results):
return render_template('results.html', data=query_results)
def make_api_requests(production_order):
# Your API request code here
url = 'confidential'
authorization_response = requests.post(
url,
data={
###confidential
}
)
if authorization_response.status_code == 200:
print('Connected to the API successfully')
#print('Response:', authorization_response.text)
else:
print('Failed to connect to the API. Status code:', authorization_response.status_code)
authorization_data = authorization_response.json()
access_token = authorization_data["access_token"]
print("ACCESS TOKEN:n")
print(access_token)
base_url = 'confidential'
sql_query = "confidential"
# Construct the complete URL
url = f"{base_url}/jobs/"
# Set up the request headers
aheaders = {'Authorization': 'Bearer ' + access_token}
aheaders['Content-Type'] = 'text/plain' ##jb
aheaders['accept'] = 'application/json' ##jb
# Make the request to execute the SQL query (THIS WORKS)
response = requests.post(url, headers=aheaders, data=sql_query) ##jb
# (THIS WORKS)
if response.status_code == 200:
print('Query executed successfully')
print('Response:', response.json())
elif response.status_code == 202: ##added elif :status code 202 = running
print('query is running')
print('Response:', response.json())
else:
print('Failed to execute the query. Status code:', response.status_code)
data = response.json()
queryId = data["queryId"]
path = data["location"]
status = data["status"]
result_url = f"{base_url}/jobs/{queryId}/result/"
status_url = f"{base_url}/jobs/{queryId}/status/"
time.sleep(5)
#print('Response:', response.json())
# Make a GET request to retrieve the query results
status_response = requests.get(status_url, params={"offset": 0, "limit": 100}, headers=aheaders)
time.sleep(2)
result_response = requests.get(result_url, params={"offset": 0, "limit": 100}, headers=aheaders)
time.sleep(2)
print("Result response", result_response.status_code)
print("Status response", status_response.status_code)
# Check if the request was successful
if result_response.status_code == 200:
print('Query results retrieved successfully')
print('Response:', result_response.text)
# Here, you can parse/process the query results based on the response format (e.g., JSON, CSV)
else:
print('Failed to retrieve query results. Status code:', result_response.status_code)
print('Response:', result_response.text)
return result_response.text
if getattr(sys, 'frozen', False):
template_folder = os.path.join(sys._MEIPASS, 'templates')
app.template_folder = template_folder
if __name__ == '__main__':
TxtPathCurrentFile = os.path.abspath(__file__)
TxtPathCurrentDir = os.path.dirname(TxtPathCurrentFile)
TxtPathTemplatesDir = os.path.join(TxtPathCurrentDir, 'templates')
app.template_folder = TxtPathTemplatesDir
#optional to see webpage
#webbrowser.open_new("http://127.0.0.1:5000")
app.run(debug=False)
2
Answers
You forgot the
return
keyword.Solution
Whenever you are working with Flask, you need to run the instance itself at the end.
As an additional note: I strongly suggest the following implementation as this considers if flask is being packed in an exe.