Unable to load templates using url_for - python

I have a RESTful API that is built with flask, and on the home page / I want to build a web GUI into it. In order to do so I'm trying to build a flask app into the Index part of my API calls:
class Index(Resource):
def get(self):
from flask import Response, render_template, Flask
from lib.interface.settings import get_db_folders, get_file_type_count, get_recent_scans, make_keys
log_request(request, "/", "GET")
recent_scans = get_recent_scans(DATABASE_FILES_PATH, amount=10)
all_folders = get_db_folders(DATABASE_FILES_PATH)
file_types = get_file_type_count(DATABASE_FILES_PATH)
website = Flask(__name__)
#website.route("/everything")
def show_all():
return Response(render_template(
"everything.html"
))
#website.route("/upload")
def upload():
return Response(render_template(
"upload.html"
))
#website.route("/api")
def apidocs():
return Response(render_template(
"apidocs.html"
))
return Response(render_template(
"index.html", recent_scans=recent_scans,
all_scans_length=len(all_folders),
file_types=file_types, recent_scan_length=len(recent_scans) + 1
))
Everything works fine when I load into the main screen (/). I can see the index.html page. However when trying to redirect to a page called "everything.html" I get an error (the error depends on how I'm trying it as seen below):
If I use <li><span>All Uploads</span></li> in everything.html the error I get is:
...
<li><span>All Uploads</span></li>
TypeError: url_for() takes exactly 1 argument (2 given)
If I do <li><span>All Uploads</span></li>
I get the following error:
...
raise BuildError(endpoint, values, method, self)
BuildError: Could not build url for endpoint 'everything'. Did you mean 'getstrings' instead?
If I do <li><span>All Uploads</span></li> I get:
...
<li><span>All Uploads</span></li>
TypeError: url_for() takes exactly 1 argument (2 given)
And so on and so forth. I'm pretty sure the problem is the way I'm trying to do this part (putting it into an API, etc) but I'm not sure if there is a work around that might work? As of right now my head.html file looks like this:
<!doctype html>
<head>
<meta charset="UTF-8">
<title>Sandbox - {% block title %}{% endblock %}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='base.css') }}">
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
<script src="{{ url_for('static', filename='base.js') }}"></script>
</head>
<header id="display-port">
<img id="header-image" src="{{ url_for('static', filename='base_image.png') }}"/>
</header>
<body>
<nav class="navigation-pane">
<h3 id="navigation-header">Navigation:</h3>
<ul>
<li><span>All Uploads</span></li>
<li><span>Upload Files</span></li>
<li><span>API Documentation</span></li>
</ul>
</nav>
<section class="content">
<h3>Current File Type Counts:</h3>
<ul>
{% for key in file_types.keys() %}
<li>{{ key.upper() }}: {{ file_types[key] }}</li>
{% endfor %}
</ul>
{% block header %}{% endblock %}
{% block content %}{% endblock %}
</section>
</body>
My index.html file looks like this:
{% extends "head.html" %}
{% block title %}Home{%endblock%}
{% block header %}
<h1>Recent Scans:</h1>
{% endblock %}
{% block content %}
<h5>Total Database Scans: {{ all_scans_length }}</h5>
<ul>
{% for i in range(0, recent_scan_length) %}
<li>Hash: {{ recent_scans[i] }}</li>
{% endfor %}
</ul>
{% endblock %}
Directory structure looks like this:
.
├── __init__.py
├── main.py
├── static
│   ├── base.css
│   ├── base.js
│   ├── favicon.ico
│   └── base_image.png
├── templates
│   ├── apidocs.html
│   ├── everything.html
│   ├── head.html
│   ├── index.html
│   └── upload.html
├── wsgi.py
And my everything.html file has nothing in it. I think it is worth noting that I am able to load from the static folder in head.html without problem. So question being as stated above, what is causing the issue? How can I fix it?

Related

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 %}

render_template HTML renders but variables not evaluated

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?

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

How should my Django file structure be set up?

I'm trying to set up my django file structure. I really don't understand this. It just isn't pointing to where I'd like it to go:
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
PROJECT_PATH = os.path.realpath(BASE_DIR)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(PROJECT_PATH,'static/')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(PROJECT_PATH,'media/')
I'm trying to build a file structure like this:
mysite
myapp
static
admin
css
js
img
media
tmp
templates
base.html
manage.py
So I'd like to get the settings.py to point to the right direction, I'm just at a loss doing so.
--------- edit ----------
It's not loading any of my content in those files, except for the templates
<html>
<head>
<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}css/main.css">
<!-- Remove line below to disable test link -->
Back To Test Page
<title>My site - {% block title %}{% endblock %}</title>
{% block head %}
{% endblock %}
</head>
<body>
<style type="text/css">
body {background-color: #ADADAD; background-image:url('{{STATIC_URL}}img/r.jpg'); background-attachment:fixed;}
<ul>
<li>test</li>
<li>test</li>
<li>test</li>
</ul>
</style>
<div id="content">
{% block content %}
{% endblock %}
</div>
<div id="footer">
{% block footer %}
© Copyright 2014 by Me.
{% endblock %}
</div>
</body>
</html>
The picture doesn't get loaded
You can set your project structure according to this sample project Link.and you can also use Unipath for set you dynamic path in your setting.py file. you can run this project with collect static or without collect static.

why is GAE not finding the files in my templates folder?

I'm so confused. The thing worked fine last night and all of a sudden today stopped working.
The purpose of this page is to generate a list of colors. The templates are located in their own folder called "templates", but GAE can't seem to find these templates at all.
What am I doing wrong here?
main2.py:
import bottle
from bottle import static_file
from google.appengine.ext.webapp import util
from bottle import route
# Load the template system
from jinja2 import Environment, FileSystemLoader
# Indicate from where the templates will be loaded
env = Environment(loader=FileSystemLoader('./templates/'))
# for randomly picking colors
import random
colors = 'green red blue';
#route('/favicon.ico')
def send_image():
filename = 'favicon.ico'
return static_file(filename, root='./images/', mimetype='image/ico');
#route('/hello')
def hello():
template = env.get_template('home.html');
color_list = colors.split();
num_colors = random.randint(0,len(color_list)+1);
color_list = color_list[:num_colors];
return template.render(title="Color List Page!", color_list=color_list);
util.run_wsgi_app(bottle.default_app())
app.yaml
application: yao-webapp2
version: 1
api_version: 1
runtime: python
handlers:
- url: .*
script: main2.py
/templates/base.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>
{% block title %}
I am stupid as heck: I forgot to fill in a title.
{% endblock %}
</title>
</head>
<body>
{% block content %}
No body knows the trouble I've seen.
{% endblock %}
</body>
</html>
/templates/home.html
{% extends "base.html" %}
{% block title %}
{{page_title}}
{% endblock %}
{% block content %}
<h1>Some Colors I know </h1>
<p>I have a list of colors that I know</p>
{% if color_list %}
<ul>
{% for color in color_list %}
<li> {{ color }} </li>
{% endfor %}
</ul>
{% else %}
<p>Oops! No colors.</p>
{% endif %}
{% endblock %}
not sure what error you are getting but i would try to use absolute paths.
instead of
env = Environment(loader=FileSystemLoader('./templates/'))
try to use this code:
templatespath = os.path.join(os.path.dirname(__file__), "templates")
env = Environment(loader=FileSystemLoader(templatespath))

Categories