using flask variables in html templates - python

When I try to use a varible from a url argument the text disappears, here's the app.py code:
from flask import Flask, render_template
import os
TEMPLATE_DIR = os.path.abspath('templates')
STATIC_DIR = os.path.abspath('static')
app = Flask(__name__, template_folder=TEMPLATE_DIR, static_folder=STATIC_DIR)
#app.route('/<string:name>')
def home(name):
return render_template('index.html', variable=name)
Here's what I am doing in the index.html file in templates folder:
<body>
<h1 class="header">Hello {{ name }}</h1>
<h3>Attention! This is a testing website with learning purpouses.</h3>
</body>
But when I run the app.py no error is displayed but it doesnt display the Hello {{ name }} line

Try this since you have assigned your name value to variable in your code :
<body>
<h1 class="header">Hello {{ variable }}</h1>
<h3>Attention! This is a testing website with learning purpouses.</h3>
</body>

Related

Flask Flatpages not able to load table of contents

I made the following small website as an introduction to Flask, and already it doesn't work! It's not able to load the table-of-contents page.
My app.py, which is the server is as follows:
import os
from flask import Flask, request, render_template
from flask_flatpages import FlatPages
from Engine.nerve_net import Nerve_Tree
# Some configuration, ensures:
# 1. Pages are loaded on request.
# 2. File name extension for pages is html.
DEBUG = True
FLATPAGES_AUTO_RELOAD = DEBUG
FLATPAGES_EXTENSION = '.html'
#Instantiate the Flask app
app = Flask(__name__)
app.config.from_object(__name__)
pages = FlatPages(app)
#app.route("/")
#app.route("/index")
def index():
return render_template('index.html') #This returns the main welcome page
#app.route("/contents")
def contents():
return render_template('contents.html', pages=pages) #This returns the table of contents page
# URL Routing - Flat Pages: Retrieves the page path
#app.route("/<path:path>/")
def page(path):
page = pages.get_or_404(path)
return render_template("page.html", page=page)
if __name__ == "__main__":
app.run(debug=True)
My table of contents, the page which displays all files within the pages directory is as follows:
{% extends "tab.html" %}
{% block content %}
</br>
<h2>TABLE OF CONTENTS</h2>
<ul>
{% for page in pages %}
<li>
<a href="{{ url_for("page", page=page.path) }}">{{ page.title }}
</li>
{% else %}
<li>No pages so far</li>
{% endfor %}
</ul>
{% endblock content %}
In this example there is only one page in the pages directory named ncs1.html, which is as follows:
title: Hello
published: 2010-12-22
Hello, *World*!
Lorem ipsum dolor sit amet
Pointing the browser to my main welcome page on http://127.0.0.1:5000/ renders the page successfully. However pointing my browser to the table-of-contents-page on http://127.0.0.1:5000/contents gives the following error:
Could not build url for endpoint 'page' with values ['page']. Did you forget to specify values ['path']?
Where am I going wrong?
As the author above mentioned, changing the table-of-contents code worked:
<a href="{{ url_for('page', path=page.path) }}"

NameError: global name 'flask' is not defined

I am fairly new to Python web programming. Request your assistance in handling the error I am getting while running a test application please. Trying to run the command - python run.py - from Powershell. It gives the error given in the title. Trying the instructions provided in this link
run.py
from tweet_harvester import app
app.run(port=8080)
Config.py
import os
DEBUG = True
TWITTER_CONSUMER_KEY = os.environ['TWITTER_CONSUMER_KEY']
TWITTER_CONSUMER_SECRET = os.environ['TWITTER_CONSUMER_SECRET']
TWITTER_ACCESS_TOKEN = os.environ['TWITTER_ACCESS_TOKEN']
TWITTER_ACCESS_TOKEN_SECRET = os.environ['TWITTER_ACCESS_TOKEN_SECRET']
init.py
from flask import Flask, json, request, render_template
import tweepy
app = Flask(__name__)
app.config.from_object('config')
auth = tweepy.OAuthHandler(app.config['TWITTER_CONSUMER_KEY'],app.config['TWITTER_CONSUMER_SECRET'])
auth.set_access_token(app.config['TWITTER_ACCESS_TOKEN'],app.config['TWITTER_ACCESS_TOKEN_SECRET'])
tweepy_api = tweepy.API(auth)
def get_tweets(username):
tweets = tweepy_api.user_timeline(screen_name=username)
return [{'tweet': t.text,'created_at': t.created_at,'username': username, 'headshot_url': t.user.profile_image_url}
for t in tweets]
#app.route('/tweet-harvester/<string:username>')
def tweets(username):
return flask.render_template('tweets.html', tweets=get_tweets(username))
tweets.html - pasting only the relevant portion of header and body section
<title>Tweet Harvester</title>
<body>
<div class="container">
<h1 class="p-3">Tweet Harvester</h1>
{% for tweet in tweets %}
<div class="list-group">
<a href="#" class="list-group-item list-group-item-action flex-column align-items-start">
<div class="d-flex w-100 justify-content-between">
<img src="{{tweet.headshot_url}}" class="w-12 p-1 float-left image-thumbnail">
<h5 class="ml-10 w-75 mb-1">{{ tweet.tweet }}</h5>
<small>{{ tweet.created_at }}</small>
</div>
</a>
</div>
{% endfor %}
You have not imported render_template from flask. You need to import it before using.
from flask import render_template
Because you are using the render_template incorrectly I guess.
It should be flask.render_template()
OR (better) for using it in your way you just need to import it from flask as
from flask import render_template

How to display a variable in HTML

I am making a web app using Python and have a variable that I want to display on an HTML page. How can I go about doing so? Would using {% VariableName %} in the HTML page be the right approach to this?
This is very clearly explained in the Flask documentation so I recommend that you read it for a full understanding, but here is a very simple example of rendering template variables.
HTML template file stored in templates/index.html:
<html>
<body>
<p>Here is my variable: {{ variable }}</p>
</body>
</html>
And the simple Flask app:
from flask import Flask, render_template
app = Flask('testapp')
#app.route('/')
def index():
return render_template('index.html', variable='12345')
if __name__ == '__main__':
app.run()
Run this script and visit http://127.0.0.1:5000/ in your browser. You should see the value of variable rendered as 12345

404 error for CSS file in Flask Application

I am unable to find exact path of .css file in my flask app. Following is relevant code
layout.html
<!DOCTYPE html>
<html>
<head>
<title>An App</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<div id="container">
<div id="heading"><h3>App</h3></div>
{% block content %}{% endblock %}
</div>
</body>
</html>
+app
+static
style.css
+templates
__init__.py
forms.py
models.py
views.py
db_repository
.gitignore
app.db
config.py
db_create.py
The one with + sign are folders
Update:
I tried this in __init__.py, same result
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import os
app = Flask(__name__)
app.config.from_object('config')
app._static_folder = os.path.abspath("static/style.css")
print os.path.abspath(app._static_folder)
db = SQLAlchemy(app)
from app import views, models
The link http://127.0.0.1:5000/static/style.css gives 404 error
Static should be on the same level as templates, not under app. Have you tried that?
I you want to change the route to the static asset's folder you could do:
app = Flask(__name__, static_folder='app/static')
check this here

duplicated url_prefix in Flask using blueprint

Sorry I've searched inside the stackoverflow and googled, but no useful information found.
I have an flask application,
python version 2.6
flask version 0.9
its application hierarchy is like
application/
__init__.py
app.py
hello/
__init__.py
view.py
templates/
hello.html
both files init.py are empty
app.py
-----------------------
from flask import Flask
from flup.server.fcgi import WSGIServer
from hello.view import hello
app = Flask(__name__)
app.debug = True
app.register_blueprint(hello, url_prefix='/hello')
if __name__ == '__main__':
WSGIServer(app, bindAddress='/tmp/app.sock').run()
view.py
-----------------------
import os
from flask import Blueprint, render_template, abort
from jinja2 import TemplateNotFound
hello = Blueprint('hello', __name__, template_folder='templates')
#hello.route('/')
def get_index():
try:
return render_template('hello.html')
except TemplateNotFound:
abort(404)
hello.html
-----------------------
<!DOCTYPE html>
<html>
<head>
{% block head %}
<meta charset="utf-8">
{% endblock %}
</head>
<body>
<div>
{% block body %}
<h1>Click Me</h1>
{% endblock %}
</div>
</body>
</html>
It works fine when I enter localhost:8080/hello, but turns out error if I click the link in html. I found its url value is href="/hello/hello/" (Should it be /hello/ right?).
I know hello.get_index is mapped to /hello/, but have no idea that the first one hello/ comes from. Any hint is appreciated.
Have you tried removing the url_prefix parameter when you regisger the blueprint? For example, what if you change the following from :
app.register_blueprint(hello, url_prefix='/hello')
to
app.register_blueprint(hello)

Categories