render_template HTML renders but variables not evaluated - python

I am trying to build an "enterprise grade" version of a flask app so am using blueprints and a fancy directory structure. I have a "toy" version of this app where everything is in a very flat directory structure with no blueprints and it works.
I have a route program that calcs some variables then passes them to render_template to generate html. The html displays in the browser but all of the variables appear to be set to NONE.
My app uses blueprints and SQLite3.
I have tried multiple things to isolate the error.
Make a textual change to html template to ensure the right template is being picked up. It is.
Pass trivial string variable to html template and see if they show up, they don't.
View source of rendered html, there is nothing where the flask variable names {{ x }} occur in the html template, including the {{ x }} text itself. So it appears the value None has been been used.
Test the code leading up to the render_template, it works perfectly.
My directory structure is: -
\myapp
app.py
\app
__init__.py
\main
__init__.py
routes.py
...
\meta
__init__.py
routes.py
...
\templates
...
base.html
index.html
The code in \meta\routes.py (which corresponds to the meta blueprint) works down to and including entitys = stmt.fetchall() and is: -
from flask import Flask, render_template, request
import sqlite3 as sql
from app.meta import bp
from app import Config
config = Config()
metafile = os.path.join(config.META_DIR, config.META_MS, config.META_DB)
#bp.route('/', methods=['GET', 'POST'])
#bp.route('/index', methods=['GET', 'POST'])
def index():
meta = sql.connect(metafile)
stmt = meta.cursor()
stmt.execute("SELECT * FROM [meta.Entity]")
entitys = stmt.fetchall()
return render_template("index.html", entitys = entitys)
In case it is relevant here is \meta\__init__.py: -
from flask import Blueprint
bp = Blueprint('meta', __name__)
The template html is as follows. The base.html is: -
<!doctype html>
<html>
<head>
{% if title %}
<title>{{ title }} - Metapplica</title>
{% else %}
<title>Metapplica</title>
{% endif %}
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="{{ url_for('static', filename = 'w3.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename = 'style.css') }}">
</head>
<body>
<div>
Home
</div>
<hr>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
{% block content %}{% endblock %}
</body>
</html>
and index.html is: -
{% extends "base.html" %}
{% block content %}
<h2>Entities</h2>
<table border = 1>
<thead>
<td>Entity</td>
<td>Action</td>
</thead>
{% for entity in entitys %}
<tr>
<td>{{ entity["Name"] }}</td>
<td>
List
Add
</td>
</tr>
{% endfor %}
</table>
{% endblock %}
Finally the rendered html is this: -
<!doctype html>
<html>
<head>
<title>Home - Metapplica</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/static/w3.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<div>
Home
</div>
<hr>
<h2>Entities </h2>
<table border = 1>
<thead>
<td>Entity</td>
<td>Action</td>
</thead>
</table>
</body>
</html>
In response to #Tobin's comment I have included the code that (should) be registering the blueprint. I use an application factory.
Here is app\__init__()
import logging
from logging.handlers import SMTPHandler, RotatingFileHandler
import os
from flask import Flask, session, redirect, url_for, escape, request, current_app
from config import Config
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
# Register blueprints
from app.errors import bp as errors_bp
app.register_blueprint(errors_bp, url_prefix='/err')
from app.auth import bp as auth_bp
app.register_blueprint(auth_bp, url_prefix='/auth')
from app.meta import bp as meta_bp
app.register_blueprint(meta_bp, url_prefix='/meta')
from app.main import bp as main_bp
app.register_blueprint(main_bp)
return app
and here is the code that calls it: -
from app import create_app
app = create_app()
I suspect that somehow when Flask renders the html template the passed variables are not available to the "flask engine" which is pointing somewhere else.
Nothing fails and there are no error messages.
What am I doing wrong?

Related

Python Flask - url_for{} not accessing static folder [duplicate]

This question already has an answer here:
Flask Python not loading main.css
(1 answer)
Closed 1 year ago.
Have a directory structure as follows:
Flask_project
-env
-src
--app2.py
-static
--css
---main.css
-templates
--base.html
--index.html
-app.py
If I load the page using app.py in the main folder, the main.css file is loaded fine using: python app.py. This works from the following file:
from flask import Flask, render_template, url_for # import
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)
However, if I load app2.py using python3 src\app2.py which is in the \src folder as follows, and redirects the template_folder:
from flask import Flask, render_template, url_for # import
app = Flask(__name__, template_folder='../templates')
#app.route('/')
def index():
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)
I am unable to load the css\main.css folder, I get the following error:
"GET /css/main.css HTTP/1.1" 404 -
I don't see why placing the app_whatever.py file in a sub directory (in this case \src) makes it unable to locate the main.css file?
For reference the base.html is as follows:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="{{url_for('static', filename='css/main.css') }}">
{% block head %}{% endblock %}
</head>
<body>
{% block body %}
{% endblock %}
</body>
</html>
And index.html is:
{% extends 'base.html' %}
{% block head %}
{% endblock %}
{% block body %}
<h1> Template </h1>
{% endblock %}
As mentioned in your second question, you need to define the location of your static-folder:
app = Flask(__name__, template_folder='../templates', static_folder='../static')

Re-Ask: Whats wrong with the Flask-Bootstrap?

OK
So you didn't like my last question
Here is a SECOND question, with much more information than actually needed. It's a very simple problem defining the base dir inside the flask-bootstrap module. If you managed to see my last question, I showed my code, but here is some more of the USELESS information you wanted for some odd reason:
Index.html
{% extends 'bootstrap/base.html' %}
<!-- TEST THINGS ON A DIFFERENT REPL! -->
<!DOCTYPE html>
<html>
<head>
<!-- This is for the tab -->
<title>Helliott-chip</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link href="{{ url_for('static', filename='style.css') }}" rel="stylesheet" type="text/css" />
</head>
<body>
<!-- Title on top -->
<h1><center>Helliot-Chip</center></h1>
<p>New User? Click to Register!</p>
<!-- Grey Menu Select -->
<div class="scrollmenu1">
{% if current_user.is_anonymous %}
Login
{% else %}
Logout
Profile
{% endif %}
Home
About
Explore
Videos
Music
</div>
{% block content %}
<h1>Hi, {{ current_user.username }}!</h1>
{% endblock %}
{% block app_content %}{% endblock %}
{% block scripts %}
{{ super() }}
{{ moment.include_moment() }}
{% endblock %}
</body>
</html>
init.py
import logging
from logging.handlers import SMTPHandler, RotatingFileHandler
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from config import Config
from flask_mail import Mail
from flask_bootstrap import Bootstrap
from flask_moment import Moment
app = Flask(__name__)
Bootstrap(app)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
login = LoginManager(app)
login.login_view = 'login'
mail = Mail(app)
moment = Moment(app)
from app import models, errors
So now that I have that down, my error (after I changed the index to base in the index.html):
[2021-04-13 17:18:39,365] INFO in debughelpers: Locating template "index.html":
1: trying loader of application "app"
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /home/runner/Website30/app/templates
-> found ('/home/runner/Website30/app/templates/index.html')
2: trying loader of blueprint "bootstrap" (flask_bootstrap)
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /opt/virtualenvs/python3/lib/python3.8/site-packages/flask_bootstrap/templates
-> no match
[2021-04-13 17:18:39,372] INFO in debughelpers: Locating template "bootstrap/base.html":
1: trying loader of application "app"
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /home/runner/Website30/app/templates
-> no match
2: trying loader of blueprint "bootstrap" (flask_bootstrap)
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /opt/virtualenvs/python3/lib/python3.8/site-packages/flask_bootstrap/templates
-> found ('/opt/virtualenvs/python3/lib/python3.8/site-packages/flask_bootstrap/templates/bootstrap/base.html')
172.18.0.1 - - [13/Apr/2021 17:18:39] "GET / HTTP/1.1" 200 -
[2021-04-13 17:18:40,173] INFO in debughelpers: Locating template "404.html":
1: trying loader of application "app"
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /home/runner/Website30/app/templates
-> found ('/home/runner/Website30/app/templates/404.html')
2: trying loader of blueprint "bootstrap" (flask_bootstrap)
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /opt/virtualenvs/python3/lib/python3.8/site-packages/flask_bootstrap/templates
-> no match
And my error before I changed it:
jinja2.exceptions.TemplateNotFound: bootstrap/index.html
Now this time without having my question being shut down from any answers in general (which I may note is opposing the purpose of this site) What would be wrong here? Is something wrong with the way I'm initializing flask-bootstrap, or is there some command I need to put in the terminal? Feel free to ask questions, and thanks a lot if it's a simple problem I'm missing. And I apologize for any unneeded attitude, I was just disappointed in the person who locked my last question for "not enough information".
There is an issue with the way you are initializing flask-bootstrap. This how you should go about it:
# Your previous imports
from flask_bootstrap import Bootstrap
app = Flask(__name__)
bootstrap = Bootstrap(app)
# ...
Basically, update the line:
Bootstrap(app)
to:
bootstrap = Bootstrap(app)
This is exactly what you have done for the other installed packages too.
Maintain the line {% extends 'bootstrap/base.html' %} in your base template (which is the parent template). Do not change it to {% extends 'bootstrap/index.html' %} This file inherits the styles, layout, features etc from bootstrap's base template.
<!-- base.html -->
{% extends 'bootstrap/base.html' %}
{% block head %}
<!-- Head information goes here -->
{% endblock %}
{% block navbar %}
<!-- Your navbar goes here -->
{% endblock %}
{% block content %}
<!-- flash message goes here -->
{% block app_content %}
<!-- Content from your custom HTML templates will go here -->
{% endblock %}
{% endblock %}
{% block scripts %}
<!-- Your scripts go here -->
{% endblock %}
In your index.html file which inherits your base,html, you will do:
<!-- index.html -->
{% extends 'base.html' %}
{% block app_content %}
<!-- Content goes here -->
{% endblock %}

python flask render_template and another return value

I use Python flask for my web application. the application provide a CSV file to download. CSV file is the response in below code block. Also I need to send a variable to html template. How can I have two return value?
#application.route("/log_analysis", methods=['POST'])
def get_response():
output='The result of your query : '+str(i-1)+' . The full report is downloaded automatically.'
cw.writerows(csv_rows)
response = make_response(si.getvalue())
response.headers["Content-Disposition"] = f"attachment; filename={return_file_name}"
response.headers["Content-type"] = "text/csv"
return render_template('base.html',output=output)
return response, 200
The output will be shown in the html but the response in the second return doesn't work.
After reading your question, I think what you are looking for is something like flash messages. The variable content you are passing in, is just text and used to display a message.
Flash messages
You'll need to set this up in your base.html or whatever template you are rendering.
Template
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="{{ url_for('static', filename='css/main.css')}}" rel="stylesheet">
</head>
<body>
<main>
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{{ category }}">
{{ message }}
</div>
{% endfor %}
{% endif %}
{% endwith %}
{% block content %}{% endblock %}
</main>
</body>
</html>
from flask import render_template, url_for, flash, redirect
#application.route("/log_analysis", methods=['POST'])
def get_response():
output=f'The result of your query : {i-1} . The full report is downloaded automatically.'
cw.writerows(csv_rows)
response = make_response(si.getvalue())
response.headers["Content-Disposition"] = f"attachment; filename={return_file_name}"
response.headers["Content-type"] = "text/csv"
flash(output,'success')
return response, 200
You can also try and do something like alerts in html template

Displaying a .txt file in my html using Python Flask

I want to display my log.txt in my log.html.
For some reason my page is completely blank.
And I dont get to see anything from my file.
Code:
def log():
with open("logs.txt", "r") as f:
content = f.read()
return render_template('log.html', content=content)
HTML LOG TEMPLATE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Log</title>
<link rel="stylesheet" href="/static/styles/nav.css" />
<link rel="stylesheet" href="/static/styles/basiclayout.css" />
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<style>
</style>
<body>
<ul class="nav">
<li ><a href="{{ url_for('hello_world') }}" >Home</a></li>
<li >Notepad</li>
<li >Explorer </li>
<li class="active">Log </li>
<li >Upload </li>
<li >Uploads </li>
<li >Logout</li>
</ul>
<div class="alert">
{% for message in get_flashed_messages() %}
{{ message }}
{% endfor %}
</div>
<pre>{{ content }}</pre>
</body>
</html>
Added my HTML Template now.
return Response(content, mimetype='text/plain')
but really you probably want to use something like logstash...
Maybe it would be better if for the log to read the file backwards in order to access the last log first.
pip3 install file-read-backwards
For example, I will show this code backwards:
In your case, it is necessary to replace app.py with logs.txt
from flask import Flask, render_template
from file_read_backwards import FileReadBackwards
app = Flask(__name__, template_folder="template")
with FileReadBackwards("app.py") as f:
# getting lines by lines starting from the last line up
b_lines = [ row for row in f ]
#app.route('/', methods=["GET", "POST"])
def index():
return render_template('index.html', b_lines=b_lines)
if __name__ == "__main__":
app.run(debug=True)
UPDATE - without libraries
from flask import Flask, render_template
app = Flask(__name__, template_folder="template")
#app.route('/', methods=["GET", "POST"])
def index():
b_lines = [row for row in reversed(list(open("app.py")))]
return render_template('index.html', b_lines=b_lines)
if __name__ == "__main__":
app.run(debug=True)
Put in your log.html:
<br>
Description:
<br>
<textarea id="stackoverflow" name="stackoverflow_review" rows="35" cols="55">
{% for line in b_lines %}
{{ line }}
{% endfor %}
</textarea>
output:
In your case, the latest changes from the logs.txt file will be displayed first.
There are two files one being "file.py" and the respective HTML file being invoked from the templates folder.
import sys
from flask import Flask, render_template, redirect, url_for, request
app = Flask(__name__, template_folder="/root/templates")
def search():
with open("test","r") as file:
content = file.readlines()
print(content)
return render_template("file2.html", content = content)
if __name__ == "__main__":
app.run(debug=True)
File2.html:
Not sure how to attach HTML file. attaching a screen shot . Please refer

flask isnt reading or interpreting css file

I'm basically trying to follow this tutorial ( http://net.tutsplus.com/tutorials/python-tutorials/an-introduction-to-pythons-flask-framework/)
Now when the css part comes in, and i copy the code it simply wont come out styled even afterr main.css is added it still shows up unstyled like if it wasn't importing the css file here's the HTML code
<!DOCTYPE html>
<html>
<head>
<title>Flask</title>
<strong><link rel="stylesheet" type"text/css" href="{{ url_for('static', filename='css/main.css') }}"></strong>
</head>
<body>
<header>
<div class="container">
<h1 class="logo">Flask App</h1>
</div>
</header>
<div class="container">
{% block content %}
{% endblock %}
</div>
</body>
</html>
layout.html ^
Home.html v
{% extends "layout.html" %}
{% block content %}
<div class="jumbo">
<h2>Welcome to the Flask app<h2>
<h3>This is the home page for the Flask app<h3>
</div>
{% endblock %}
routes.py v
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')
if __name__ == '__main__':
app.run(debug=True)
This is probably due to the directory structure of your app. By default, flask looks for the static directory in the same level as the file that the app object is created in. This is the example structure for a small application from the flask docs.
/yourapplication
/yourapplication.py
/static
/style.css
/templates
layout.html
index.html
login.html
You can also change the location of the static files by setting the "static_folder" attribute on the app object. Check the docs here for setting the static_folder

Categories