I am having a ymal file and a html file where some of the content in the ymal file is loaded into the html file (see below). I would like to add linebreaks to the string in the ymal file such that it is shown in separate lines when the html file is loaded. I am using flask and jupyter to load the html file.
The html file is loaded correctly but whatever i try it seems that I cannot get the string to break where I want it to.
Does anyone can help me to add linebreaks in the yaml files such that they are shown in the html file?
Thank you.
python code:
import oyaml as yaml
from flask import Flask
from flask import render_template
app = Flask(__name__)
app.config['JSON_SORT_KEYS'] = False
#app.route('/')
def index():
website_data = yaml.load(open('_config.yaml'))
return render_template('home.html', data=website_data)
if __name__ == '__main__':
app.run()
My yaml code:
profile:
first_name: |
I would like to have a break here.\n
And then I would also to have a break here\\
But it does not work whatever I try</br>.
My html code:
<!DOCTYPE html>
<html>
<body>
<h1>My homepage</h1>
<p>{{ data.profile.first_name }} </p>
<p>This is a test website again</p>
</body>
</html>
Related
I am building a website with flask on python. I am new to web development.
I built an HTML page, and now I need it's contents - number of buttons on the page for example - to be possibly different and automatic on each launch of app.py (the flask app running the website). Let's say that the number will be random between 1-10, a number generated in the app.py.
Does this mean that I need to change the HTML on every app.py launch, this by using python and editing the text file "index.html"? Is this bad practice and not a good way of achieving the goal? Are there other better methods to launch an input-dependent HTML page?
Thanks!
Code example:
def change_HTML_page(path,num):
# here read the text file in path, which is an HTML file, page description.
# inside in some place add more rows to describe buttons,
# as many as num.
# Add rows like this one <input type="button" id="i_bnutton" value="i" onclick="change_button_appearence(this)" />
# save text file afer the change
num_of_buttons = randint(0, 10)
page_path = r"docs/pages/index.html"
change_HTML_page(page_path, num_of_buttons);
#app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
Best way is to pass the num_of_buttons inside the html render command and constract all input buttons with a jinja loop inside your html.
Your code should look like below:
FLASK:
#app.route('/')
def index():
num_of_buttons = randint(0, 10)
return render_template('index.html', num_of_buttons=num_of_buttons)
if __name__ == '__main__':
app.run(debug=True)
And inside your HTML:
{% for i in range(0,num_of_buttons) %}
<input type="button" id="{{i}}_bnutton" value="{{i}}" onclick="change_button_appearence(this)" />
{% endfor %}
This question already has an answer here:
Flask css not updating [closed]
(1 answer)
Closed 2 years ago.
Flask app is rendering a previous version of my css file (I have saved and made changes, but when I inspect page, the css file shown is a previous version). Maybe previous version of css file is somehow stuck in the cache? I tried restarting browser, no luck .
Here is the code:
Part of app.py file (the part where I'm rendering the HTML file):
from flask import Flask,render_template,url_for,request
from twilio.rest import Client
app = Flask(__name__, template_folder='templates')
app.static_folder = 'static'
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
pd.core.common.is_list_like = pd.api.types.is_list_like
import pandas_datareader as pdr
#import yahoo finance api fixer
import fix_yahoo_finance as fyf
from pandas_datareader import data as pdr
from datetime import datetime, timedelta
#app.route('/')
def home():
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)
index.html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles.css') }}" />
</head>
<body>
<h1>Ticker Predictor</h1>
<h2>Using Machine Learning to Predict Tomorrow's Stock Prices</h2>
<br>
<h3>Simply enter a valid stock ticker below and hit the predict button to receive a text message of tomorrow's predicted opening price of that stock within around 10 minutes!</h3>
<!-- Main Input For Receiving Query to our ML -->
<form action="{{ url_for('predict')}}"method="post">
<input type="text" placeholder="Input Stock Ticker Here" required="required" />
<button type="submit">Predict</button>
</form>
{{ prediction_text }}
</body>
</html>
And here is the file structure:
TickerPredictor
|--static/
|--styles.css
|--templates/
|--index.html
|--app.py
Any help would be much appreciated! Thank you!
your app.py should be something like this
from flask import Flask,render_template
app = Flask(__name__)
#app.route('/')
def home():
return render_template('index.html')
if __name__ == "__main__":
DEBUG = True
HOST = '0.0.0.0'
app.run(debug=DEBUG, host=HOST)
In your app.py file you did not mention the host. Update your app.py file and it should work.
Thanks to help from Rahul and stackoverflow.com/questions/21714653/flask-css-not-updating , I just performed a hard reload in my browser to clear the cache (CMD + SHIFT + R). In other words, the previous version of the css file was getting stored in the browser cache, clearing the cache gets rid of previous css file version and most recent version is then displayed (which is obviously what I want). Thanks everyone!
I have written a piece of code that matches if the string has anything of the pattern text.someExtension, In my case, it would be fileName.png in the string, converts it into an img tag and displays on the HTML file using python and flask. Let us take the example string:
"What is the output of this program? e.png"
the code matches e.png and it then replaces e.png by
"<br><img src="{{url_for('static', filename='pics/e.png')}}" /><br>"
The image e.png is put in the folder pics inside the static folder.
If this string is pushed into a flask variable even by adding Markup() to it it isn't rendering the image but showing the following output.
output on html page
why is it so? Any way to make it display the image e.png?
my code is:
import re
from flask import Flask, Markup, render_template
app = Flask(__name__)
def rep(x):
text = re.findall(r'\w+[.]\w+', x)
for i in text:
b ="<img src=\"{{ url_for('static',filename='pics/"+i+"')}}\">"
x=x.replace(i,b)
return x
#app.route('/')
def home():
a = "What is the output of this program? e.png"
a = rep(a)
return render_template('new.html',var=Markup(a))
if __name__ == '__main__':
app.run(debug=True, host='localhost', port=8032)
And the HTML file is,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{var}}
</body>
</html>
The problem is that the value you're passing to your template is a string and even though the string you're inserting is formatted with the {{ brackets, flask doesn't interpret those. Notice if you look at the html being served, it actually contains the string 'url_for'...
You're also not even importing the url_for function from flask, so that wouldn't have worked anyway.
The solution:
import re
from flask import Flask, url_for, Markup, render_template
app = Flask(__name__)
def rep(x):
text = re.findall(r'\w+[.]\w+', x)
for i in text:
b ="<img src='" + url_for('static', filename='pics/'+i) + "'>"
x=x.replace(i,b)
return x
#app.route('/')
def home():
a = "What is the output of this program? e.png"
a = rep(a)
return render_template('new.html', var=Markup(a))
#app.route('/static/<path:path>')
def static_file(path):
return send_from_directory('static', path)
if __name__ == '__main__':
app.run(debug=True, host='localhost', port=8032)
The html file can remain unchanged. This solution
separately tells the flask server to listen and serve the static files under the /static page.
Creates the html with the image url by string concatenation, instead of trying to use template rendering.
I'm trying to create a simple program which will replace {{ test }} with 'Hello world' by following a tutorial, however I am stumped and when I open the HTML file - as {{ test }} is shown on the page instead of 'Hello World' which is what should be appearing.
Any help would be appreciated because I am very unsure on what to do to fix this, thanks.
I am unsure if I have even linked the two files, as to my knowledge it was never specified in the video and I have only just noticed that there is no link between the two files.
Python Code:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def homepage():
return render_template('index.html', test='hello world')
if __name__ == '__main__':
homepage()
else:
print('Please run this file as main, not as module.')
HTML Code:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<p> {{ test }} </p>
</body>
</html>
Flask is a webserver. You are not meant to call the functions with app.route. Replace the last part with:
if __name__ == '__main__':
app.run()
and then visit http://127.0.0.1:5000/ in your browser. The template file is not meant to change.
If for some reason you don't want to run a server but you just want to create HTML files, then use Jinja2, the template engine behind Flask.
I was creating a simple website using web.py framework . But when i ran the website it gave template error.
My html file code
def with (greeting)
<html>
<head>
<title> "This is a web project"</title>
<body>
<H1>"Yoyo honey singh"</H1>
<H6>greeting<H6>
</body>
</head>
</html>
My python file code
import web
urls = ("/","Index")
app = web.application(urls,globals())
render = web.template.render("\templates")
class Index:
def GET(self):
greeting = "HELLO WORLD"
return render.index(greeting = greeting)
if __name__ == "__main__":
app.run()
I placed the index.html file in the template folder and the python script in the bin folder. The directory structure is like
D:\WEBSITE
WEBSITE
NAME
init.py
bin
app.py
tests
init.py
docs
templates
According to the documentation you should put a $ before each python statement in the template. Therefore the first file becames:
$def with (greeting)
<html>
<head>
<title> "This is a web project"</title>
<body>
<H1>"Yoyo honey singh"</H1>
<H6>$greeting<H6>
</body>
</head>
</html>