werkzeug.routing.BuildError with Flask Python - python

**difference to the suggested repeat, my error stemmed from the following line being missing in the original code session['message']=request.form['message'] wherease in the suggested duplicate was missing the render_template component`
I am trying to create user sessions with Flask, I don't care about authentication. I just want a page where they enter their name, and then they are redirected to the main page. I tried to follow the example in this link here but I get a werkzeug.routing.BuildError. To summarise my python app is:
from flask import Flask, render_template
from flask import request, session, url_for,abort,redirect
app = Flask(__name__)
app.config['SECRET_KEY'] = 'F34TF$($e34D';
#app.route('/')
def home():
return render_template('index.html')
#app.route('/signup', methods=['POST'])
def signup():
session['username'] = request.form['username']
session['message']=request.form['message']
return redirect(url_for('message'))
#app.route("/message")
def message():
return render_template("message.html")
if __name__ == '__main__':
app.run(debug=True)
and index.html is:
{% extends "layout.html" %}
{% block content %}
<h1>Say something</h1>
<form method="post" action="{{ url_for('signup') }}">
<p><label>Username:</label> <input type="text" name="username" required></p>
<p><button type="submit">Send</button></p>
</form>
{% endblock %}
layout.html is:
<!doctype html>
<html lang="en">
<head>
<title>Say somthing</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>

You are getting that error because you don't have a route called message and yet you are redirecting to it.
#app.route('/signup', methods=['POST'])
def signup():
session['username'] = request.form['username']
# Create a message route first
return redirect(url_for('message'))
Here's a sample route called message
#app.route("/message")
def message():
return render_template("message.html")

Related

How to automatically refresh chat app to be in real-time

I have this very basic chat app, where everyone can chat in one huge group. And when I send messages, other people have to refresh their web page to see new messages. I am just wondering if anyone has any idea how to do this. By the way, the app is made with python Flask and HTML.
from flask import Flask, render_template, request, url_for, redirect
import database as db
app = Flask(__name__)
app.secret_key = 'ItDoesntMatter'
#app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
return render_template('/index.html', messages=db.get_messages())
#Else
message = request.form['message']
db.send_message(message)
return redirect(url_for('index'))
if __name__ == '__main__':
app.run()
<!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>Chat</title>
</head>
<body>
{% for message in messages %}
<div>At {{ message[1] }}: <strong>{{ message[0] }}</strong></div>
{% endfor %}
<form method="POST" action="/">
<input type="text" placeholder="message" name="message">
<button type="submit" id="btn">Send</button>
</form>
</body>
</html>
I tried to do this with a turbo-flask, but it didn't work. I was also on google for like 1 hour and I didn't find anything.

Method Not Allowed in Flask for IntegerField form

I'm trying to set up integer field validation on a form in Flask, but I keep getting 'Method Not Allowed'. I can't see what is wrong with my routes?
My main file is:
from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import IntegerField
# from perfect_numbers import classify
app = Flask(__name__)
app.config['SECRET_KEY'] = 'MySecretKey'
# num = 12
# Classify = classify(num)
class PerfectForm(FlaskForm):
number = IntegerField(4)
#app.route('/', methods=['POST'])
def form():
form = PerfectForm()
return render_template('index.html', form = form)
if __name__ == '__main__':
app.run(debug=True)
Then I have a standard layout.html file:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>PERFECT App</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
</head>
<body>
{% block body %}{% endblock %}
</body>
</html>
And my index.html is:
{% extends 'layout.html' %}
{% block body %}
<h1>PERFECT NUMBERS</h1>
<p>This is a basic Flask App to illustrate Aliquot Sums and Perfect Numbers</p>
<p>Input a number to check if it is abundant, perfect, or deficient</p>
<form action="{{ url_for('/') }}" method="POST">
{{ form.csrf_token }}
{{ form.number }}
</form>
<!-- {{ num }} is {{ classify }} -->
{% endblock %}
First, change the app.route() signature to
#app.route('/', methods=['POST', 'GET'])
You have to fill the form and submit for your app to receive a POST request. When you first load the page on your browser, you technically send a GET request to flask, and it returns the page.
To handle your POST request separately, do something like this :
#app.route('/', methods=['POST', 'GET'])
def form():
if request.method == 'POST':
# Do something with request (access form elements with request.get(key))
return 'Somehing here'
form = PerfectForm()
return render_template('index.html', form = form)

Python global variable not updating in real time flask

value=user_id is not taking the new value defined by def login():.for e.g. if the entered user_id from HTML page is 200, 300 and 100. The values will be assigned as 0, 200, 300. That is, when home page is displayed it will be showing user 0 for entered value 200, and for second time it is showing 200 for entered value 300 and for third time it is showing 300 for entered value 100.
I need a real time values i.e. for entered value 200 home page should have value 200, and for 300 it should be 300. Could anyone please help me with this? Please advice. Thanks in advance. Note: HTML code is not optimized.
from flask import Flask, render_template # Flask is the class within the flask library
from flask import request, redirect
user_id = int(0)
app = Flask(__name__) # Instance of the object Flask. __name__: this gets value of name of python script
#app.route('/', methods=["GET", "POST"]) # login page
def login():
if request.method == "POST":
global user_id
user_id = request.form['userid']
print(user_id)
return render_template("login.html")
#app.route('/home/') # This the URL i.e. home page
def home():
return render_template("home.html", value=user_id)
if __name__ == "__main__":
app.run(debug=True)
HTML Code for Login page here.
<!DOCTYPE html>
<html>
<head>
<title>Recommender System App</title>
<link rel="stylesheet" type="text/css" href="{{url_for('static',filename='css/main.css')}}">
</head>
<body>
<header>
<div class="container">
<h1 class="logo">Movie Recommender System</h1>
<strong><nav>
<ul class="menu">
</ul>
</nav></strong>
</div>
</header>
<form action="{{ url_for('login') }}" method="post">
<div class = "Login Fields">
<b>Username:</b> <input type="number" placeholder="Numbers only" name='userid'>
<p><b>Password:</b> <input type="password" placeholder="Enter Password" name= 'password' id="pwd"></p>
<input type="submit" onclick="check(this.form)" class="button">
</div>
<p></p>
<p></p>
<div>
<p>Test User IDs:</p>
<li>224</li>
<li>216</li>
<li>681</li>
<li>19</li>
<li>82</li>
<li>305</li>
<li>44</li>
<li>268</li>
<p>Password: 123Swaroop</p>
</div>
</form>
<script language="javascript">
function check(form)/*function to check userid & password*/
{
if(form.password.value == "123Swaroop")
{
window.open(href = "{{ url_for('home') }}")
}
else
{
alert("Wrong Password or User Id")/*displays error message*/
}
}
</script>
</body>
</html>
HTML code for home page here:
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<link rel="stylesheet" type="text/css" href="{{url_for('static',filename='css/main.css')}}">
</head>
<body>
<header>
<div class="container">
<h1 class="logo">Welcome User: {{ value }}</h1>
<strong><nav>
<ul class="menu">
</ul>
</nav></strong>
</div>
</header>
<div class = "home">
<h1>Top Rated Movies</h1>
<p>This is test website</p>
</div>
</body>
</html>
You also need to call the global value within your home() function:
from flask import Flask, render_template, request, redirect
user_id = int(0)
app = Flask(__name__)
#app.route('/', methods=["GET", "POST"])
def login():
if request.method == "POST":
global user_id
user_id = request.form['userid']
print(user_id)
return render_template("login.html")
#app.route('/home/')
def home():
global user_id
return render_template("home.html", value=user_id)
if __name__ == "__main__":
app.run(debug=True)
However, using global variables is usually considered bad practice so you could also consider something like this:
from flask import Flask, render_template, request, redirect
app = Flask(__name__)
#app.route('/', methods=["GET", "POST"])
def login():
return render_template("login.html")
def get_user_id():
try:
if request.method == "POST":
user_id = request.form['userid']
return user_id
else:
# Handle error or do something else
except:
# Handle error or do something else
#app.route('/home/')
def home():
try:
return render_template("home.html", value=get_user_id())
except:
# Handle error or do something else
if __name__ == "__main__":
app.run(debug=True)

use python pandas to show csv to placeholder in web file

I have a csv file and need to convert it to view it in html. I know python pandas can do it with
df = pd.read_csv("myfile.csv")
df.to_html('output.html')'
but I don't want to show it in single web page, I have index.html file and I want to show it in there but in another section.
found the answer using tablib
from flask import Flask, render_template
import tablib
import os
app = Flask (__name__)
dataset = tablib.Dataset()
with open(os.path.join(os.path.dirname(__file__),'email.csv')) as f:
dataset.csv = f.read()
#app.route("/")
def index():
data = dataset.html
#return dataset.html
return render_template('index.html', data=data)
if __name__ == "__main__":
app.run()
index.html
<html>
<head>
<meta charset="utf-8" />
<link rel=stylesheet type=text/css href="{{ url_for('static',
filename='css/style.css') }}"/>
<title>Show CSV</title>
</head>
<body>
<div class="table">
{% block body %}
{{ data|safe }}
{% endblock %}
</div>
</body>
</html>

Why am I getting a 500 error with this code?

I am trying to create a site with a webform using Flask, but I keep getting a 500 error
Here is my template/main.html
<DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sample Page</title>
<meta name="viewport" content="width=device-width"
initial=scale=1/>
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
<link href="{{ url_for('static', filename='favicon.ico') }}" rel="shortcut icon">
</head>
<h2>Hello, this site is meant to test my fill_web_form.py script</h2>
<br>
<br>
<h1>Test Form</h1>
<form action="/" method="post" name="login">
{{ render_field(form.test_form) }}<br>
<p><input type="submit" value="Sign In"></p>
</form>
</html>
Here is my init.py file
from flask import Flask, render_template
#import sqlite3
app = Flask(__name__)
#app.route('/')
def homepage():
return render_template("main.html")
if __name__ == "__main__":
app.run()
Here is my form.py file
from flask.ext.wtf import Form
from wtforms import StringField, BooleanField
from wtforms.validators import DataRequired
class LoginForm(Form):
test_form = StringField('test_form', validators=[DataRequired()])
Why do I keep getting a 500 error? I cant figure it out.
Run in debug mode app.run(debug=True) to see more information in browser.
You should import form and send to template. You may need secret_key to use csrf. etc.
from form import LoginForm
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
#app.route('/')
def homepage():
return render_template("main.html", form=LoginForm())

Categories

Resources