I'm testing a little code to work, but I can't get it to work, this is the flask/python part:
#from weasyprint import HTML
import flask
import os
##
##html = HTML('text.html')
##html.write_pdf('invoice.pdf')
app = flask.Flask(__name__)
#app.route('/')
def hello_world():
today = datetime.today().strftime("%B %-d, %Y")
navigation = [1,2,3]
return flask.render_template('text.html',navigation = navigation,fecha = today)
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)
this is the test html, that im trying to work on:
<!doctype html>
<html>
<head>
welcome {{fecha}}
</head>
<body>
{% for item in navigation %}
this is a test, and hello {{item}}world!!!
{% endfor %}
</body>
</html>
but the output is this :
welcome {{fecha}} {% for item in navigation %}this is a test, and hello {{item}}world!!!
{% endfor %}""" (brs a let out intetionally)
this is the current folder structure:
what am I missing to make this work as intended?
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
fruits = ['๐', '๐', '๐', '๐', '๐', '๐', '๐', '๐ฅญ', '๐', '๐', '๐', '๐']
return render_template('index.html', fruits = fruits)
if __name__ == '__main__':
app.run(debug = True)
Your .html files should be in templates folder otherwise it will not work. (CASE SENSITIVE)
<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Flask App</title>
</head>
<body>
{% for fruit in fruits %}
<li>{{ fruit }}</li>
{% endfor %}
</body>
</html>
Folder Structure
Output Image
Related
A string sample~text~11 is being passed as a parameter from index.html to plot.html using the Flask session.
I want to print the parameter using Brython on the page plot.html.
plot.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Plot</title>
<script type="text/javascript" src="../static/jquery/jquery-3.6.3.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
<script src="../static/brython/Brython-3.11.1/brython.js"></script>
<script src="../static/brython/Brython-3.11.1/brython_stdlib.js"></script>
</head>
<body onload="brython()">
<script type="text/python">
from browser import document
document <= "Hello World!"
document <= document.query['plot_param']
</script>
<h1>Plot page</h1>
<h3>{{plot_param}}</h3>
<h3 id="my_h3"></h3>
</body>
</html>
The above page is supposed to show the string sample~text~11 (see index.html) twice.
However, it is not doing what it was supposed to do. Brython is not parsing the parameter. Therefore, the string is shown only once (rather than twice).
How can I achieve what I want?
.
.
Additional Source Code:
app.py
from flask import Flask, session, render_template
from flask_socketio import SocketIO
from flask import request, redirect
async_mode = None
app = Flask(__name__)
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.secret_key = "super secret key"
socketio_obj = SocketIO(app)
#app.route('/', methods=['GET', 'POST'])
def index():
print("index()...called...")
if request.method == "POST":
print("POST method used ...")
if request.form.get('submit_button1'):
session["unique_key_str"] = request.form['text1']
return redirect("/plot")
# end-if
# end-if
return render_template('index.html')
# end-def
#app.route('/plot', methods=['GET', 'POST'])
def plot():
print("plot()...called...")
return render_template('plot.html', plot_param=session["unique_key_str"])
if __name__ == '__main__':
socketio_obj.run(app, debug=True)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="../static/jquery/jquery-3.6.3.js"></script>
<script type="text/javascript" src="../static/jquery/jquery.redirect.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
</head>
<body>
<form method="post" >
<input type="text" name="text1" value="sample~text~11" />
<input type="submit" name="submit_button1" value="Token value">
</form>
<h1>Index page</h1>
</body>
</html>
main.py
`from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')`
home.html
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>HOME</h1>
hello
</body>
</html>`
hello.html
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hello</title>
</head>
<body>
<h1>Hello</h1>
</body>
</html>`
home.html is displaying while clicking the address
hello.html is not displaying while clicking the hyper link
Try this code
In main.py: Created new #app.route('/hi') that returns hello.html when called from home.html (see below)
In home.html: Changed href="hello.html" To href="/hi" to call that Flask route:
Flask Code:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')
#app.route('/hi')
def hi_there():
return render_template('hello.html')
app.run()
home.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>HOME</h1>
hello
</body>
</html>
hello.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hello</title>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
It looks like you're missing a route in your main.py file for the hello.html page. You need to add a new route that maps to the URL path /hello.html and returns the hello.html template.
Good afternoon! I'm learning flask and try to make something like authorisation but it shows me message "werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'a'". I tryed to check my code but it didn't help me. If it's not difficult or you, please tell me where can be the problem. Thank you.
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<form action="/" method="POST">
<input type="text" name="a"/>
<input type="text" name="b" />
<input type="submit" name="send" value="Send">
</form>
</div>
{% for m in get_flashed_messages() %}
<div>{{m}}</div>
{%endfor%}
{{ Sum }}
Login!
</body>
</html>
login.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<form action="/" method="POST">
<input type="text" name="a"/>
<input type="text" name="b" />
<input type="submit" name="send" value="Send">
</form>
</div>
{% for m in get_flashed_messages() %}
<div>{{m}}</div>
{%endfor%}
{{ Sum }}
Login!
</body>
</html>
app.py:
from flask import Flask, render_template, redirect, abort
from flask.globals import request, session
from flask.helpers import flash, url_for
app = Flask(__name__)
app.config['SECRET_KEY'] = 'fddaeefgweef'
#app.route('/', methods=['POST', 'GET'])
def index():
Sum = ' '
if len(request.form['a']) > 2:
flash('completed!')
else:
flash('AAAAHHH')
if request.method == 'POST':
a = request.form['a']
b = request.form['b']
newSum = float(a)+float(b)
Sum = str(newSum)
else:
Sum = 'err'
return render_template('index.html', Sum=Sum)
#app.route('/login/', methods=['POST', 'GET'])
def login():
if 'userLogged' in session:
return redirect(url_for('profile', username=session['userLogged']))
elif request.form['nick'] == 'hey' and request.form['password'] == 123:
session['userLogged'] = request.form['nick']
return redirect(url_for('profile', username=session['userLogged']))
return render_template('login.html')
#app.route('/profile/<username>')
def profile(username):
if 'userLogged' not in session or session['userLogged'] != username:
abort(401)
return f'User {username}'
if __name__ == '__main__':
app.run(debug=True)
Here
#app.route('/', methods=['POST', 'GET'])
def index():
Sum = ' '
if len(request.form['a']) > 2:
flash('completed!')
else:
flash('AAAAHHH')
if request.method == 'POST':
a = request.form['a']
b = request.form['b']
newSum = float(a)+float(b)
Sum = str(newSum)
else:
Sum = 'err'
return render_template('index.html', Sum=Sum)
you are asking about value of a from FORM data indiscriminately, but that does not make sense in case of GET.
I have the following files on VS code and when I try to run them on my browser, it fails to identify that there is any reg.html template at all. What is the issue?
python file
from flask import Flask,
render_template, flash
app = Flask(__name__)
app.config["SECRET_KEY"] = "asdfghjkl"
#app.route("/")
def form():
return render_template("reg.html", title = "Form")
if __name__ == "__main__":
app.run(debug = True)
html file (reg.html)
!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login/Signup - ((title)) </title>
<!-- Bootstrap CSS-->
<link rel = "stylesheet" href = "(( url for('static', filename = 'css/bootstrap.min.css)' ))">
<link rel = "stylesheet" href = "(( url for('static', filename = 'css/site.css') ))">
</head>
<body>
<div class = "container">
<div class = "row">
<div class = "col-md-5">
<h1 class = "text-center">Registration form</h1>
</div>
<div class = "col-md-2"></div>
<div class = "col-md-2"></div>
</div>
</div>
<!-- Javascript -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.js.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src = "((url for ('static', filename = 'js/bootstrap.min.js')))">`</script>`
</body>
</html>
To solve this question, create a folder named templates, which is where Flask looks for templates by default, then put the reg.html in this folder:
start the program and you will observe the results:
Detailed information about flask, you can refer to Flask Tutorial.
from flask import Flask, render_template, url_for, jsonify, request
from translate import Translator
en_ge = Translator("geo")
ge_en = Translator("en","geo")
app = Flask("Translator")
#app.route("/send",methods=["GET","POST"])
def send():
if request.method == "POST":
word = request.form["word"]
return render_template("translator.html",word=en_ge.translate(f"{word}"))
return render_template("index.html")
app.run()
I am trying to make translator with flask, but unfortunately I start learning it 10 minutes ago :). I am just trying to win a bet and make it as fast as I can. Googled but I keep receiving server internal error. How to fix it, please help
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<meta charset="UTF-8">
<title>Translator</title>
</head>
<body>
<h1>แจแแแงแแแแ แกแแขแงแแ</h1>
<form method="POST" action="/send">
<div class="form-group">
<input type="text" name="word">
</div>
<input class="btn btn-primary" type="submit" value="Translate">
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<h1>{{word}}</h1>
</body>
</html>
I think u miss template_folder param in Flask object creation, something like
app = Flask("Translator", template_folder="full_path_fo_a_folder_where_your_html_is_stored")