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.
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>
i cannot access the text box data in the back end. i wanna use the textbox value in the backend but it says 400 badrequest. Please help me with this. i cannot see where my code went wrong.i cannot access the text box data in the back end. i wanna use the textbox value in the backend but it says 400 badrequest. Please help me with this. i cannot see where my code went wrong.
python
from flask import Flask, render_template, url_for, request,redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import tweepy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db= SQLAlchemy(app)
#app.route('/')
def index():
return render_template('home.html')
#app.route('/getlivedata', methods=['POST','GET'])
def stream():
if request.method =="POST":
rows = request.form['numtweets']
else:
return render_template('home.html')
if __name__ == "__main__":
app.run(debug=True)
html
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>CodePen - Navigation PageDesign/Lesson</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="sara mazal lessons">
<meta name="keywords" content="HTML, CSS, JavaScript, mazal, icons">
<meta name="author" content="Sara Mazal">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Josefin+Sans:wght#200;300;400;500&family=Raleway:wght#100;200;300;400;500&family=Roboto:wght#300;400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/particlesjs/2.2.3/particles.min.js"></script><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel="stylesheet" href="{{ url_for('static',filename='css/style.css') }}">
</head>
<body>
<!-- partial:index.partial.html -->
<section class="nav">
<h1>LIVE TWITTER DATA ANALYSIS</h1>
<h3 class="span loader">
<span class="m">S</spam><span class="m">E</spam><span class="m">N</spam><span class="m">T</spam><span class="m">I</spam><span class="m">M</spam><span class="m">E</spam><span class="m">N</spam><span class="m">T</spam><span class="m">A</spam><span class="m">L</spam><span class="m"> </span><span class="m">A</spam><span class="m">N</spam><span class="m">D</spam><span class="m"> </span><span class="m">C</spam><span class="m">A</spam><span class="m">T</spam><span class="m">E</spam><span class="m">G</spam><span class="m">O</spam><span class="m">R</spam><span class="m">I</spam><span class="m">C</spam><span class="m">A</spam><span class="m">L</spam> </h3>
<div class="nav-container"><a class="nav-tab" href="#tab-pwa">PWA</a><a class="nav-tab" href="#tab-graphql">GraphQL</a><a class="nav-tab" href="#tab-next">NEXT</a><a class="nav-tab" href="#tab-typescript">TYPESCRIPT</a><a class="nav-tab" href="#tab-deno">DENO</a><span class="nav-tab-slider"></span></div>
</section>
<form action="#" method="post">
<main class="main">
<section class="slider" id="tab-pwa">
<h1>PWA</h1>
<input type="text" name="numtweets">
<h3>GetLiveData</h3>
<h2>the best of both worlds...</h2>
</section>
<section class="slider" id="tab-graphql">
<h1>GraphQL</h1>
<h2>a query language for APIs</h2>
</section>
<section class="slider" id="tab-next">
<h1>NEXT</h1>
<h2>framework for Production</h2>
</section>
<section class="slider" id="tab-typescript">
<h1>TYPESCRIPT</h1>
<h2>giving you better tooling at any scale</h2>
</section>
<section class="slider" id="tab-deno">
<h1>DENO</h1>
<h2>a modern runtime</h2>
</section>
</main>
</form>
<canvas class="background"></canvas>
<!-- partial -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js'></script><script src="{{ url_for('static',filename='js/script.js') }}"></script>
</body>
</html>
Change your form action to "/getlivedata" so it would post the data there. Also, it seems that you are using the as the way to go to the url. Use a submitnbutton instead.
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
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")
I am trying to display my html files using python alone. Such as I would python code.py and I would be able to access my html at localhost:8080
html files are static files that access each other. For example, index.html directs to contact.html and all of them access css folder.
How do I open my html files so it displays it on the webpage?
below is what I have so far.
html_file = []
with open("index.html", "r") as f:
for line in f.readlines():
html_file.append(line)
Is there way to do python code.py and when I access localhost:8000 that would show me the code? and I can access each page.
here is an example html file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>title</title>
<link rel="stylesheet" href="./css/style.css">
</head>
<body>
<header>
<img class="resize" src="./pictures/logo.png" alt="logo">
<nav>
<ul class="nav-links">
<li class="active">Home</li>
<li>Contact</li>
</ul>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script type="text/javascript">
$(document).on('click', 'ul li', function(){
$(this).addClass('active').siblings().removeClass('active')
})
</script>
</nav>
</header>
</body>
</html>
There's way to do so using the python web frameworks like Flask or Django. In a typical flask scenario your code would look like this:-
1) Install flask:-
pip install flask
2) Write your code.py like this:-
from flask import Flask, url_for
from flask import render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('hello.html')
3) Next create a templates folder inside which put your html file which I have named it to be hello.html
templates > hello.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>title</title>
<link rel="stylesheet" href="./css/style.css">
</head>
<body>
<header>
<img class="resize" src="./pictures/logo.png" alt="logo">
<nav>
<ul class="nav-links">
<li class="active">Home</li>
<li>Contact</li>
</ul>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script type="text/javascript">
$(document).on('click', 'ul li', function(){
$(this).addClass('active').siblings().removeClass('active')
})
</script>
</nav>
</header>
</body>
</html>
4) Your directory structure would look like this:-
/code.py
/templates
/hello.html
5) Run python code.py and you can see your page on localhost:5000.